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 = getDataLayout();
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 addBypassSlowDiv(32, 8);
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);
517 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
523 if (Subtarget->hasCmpxchg16b()) {
524 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
527 // FIXME - use subtarget debug flags
528 if (!Subtarget->isTargetDarwin() &&
529 !Subtarget->isTargetELF() &&
530 !Subtarget->isTargetCygMing()) {
531 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
534 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
535 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
536 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
537 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
538 if (Subtarget->is64Bit()) {
539 setExceptionPointerRegister(X86::RAX);
540 setExceptionSelectorRegister(X86::RDX);
542 setExceptionPointerRegister(X86::EAX);
543 setExceptionSelectorRegister(X86::EDX);
545 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
546 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
548 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
549 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
551 setOperationAction(ISD::TRAP, MVT::Other, Legal);
553 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
554 setOperationAction(ISD::VASTART , MVT::Other, Custom);
555 setOperationAction(ISD::VAEND , MVT::Other, Expand);
556 if (Subtarget->is64Bit()) {
557 setOperationAction(ISD::VAARG , MVT::Other, Custom);
558 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
560 setOperationAction(ISD::VAARG , MVT::Other, Expand);
561 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
564 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
565 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
567 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
568 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
569 MVT::i64 : MVT::i32, Custom);
570 else if (TM.Options.EnableSegmentedStacks)
571 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
572 MVT::i64 : MVT::i32, Custom);
574 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
575 MVT::i64 : MVT::i32, Expand);
577 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
578 // f32 and f64 use SSE.
579 // Set up the FP register classes.
580 addRegisterClass(MVT::f32, &X86::FR32RegClass);
581 addRegisterClass(MVT::f64, &X86::FR64RegClass);
583 // Use ANDPD to simulate FABS.
584 setOperationAction(ISD::FABS , MVT::f64, Custom);
585 setOperationAction(ISD::FABS , MVT::f32, Custom);
587 // Use XORP to simulate FNEG.
588 setOperationAction(ISD::FNEG , MVT::f64, Custom);
589 setOperationAction(ISD::FNEG , MVT::f32, Custom);
591 // Use ANDPD and ORPD to simulate FCOPYSIGN.
592 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
593 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
595 // Lower this to FGETSIGNx86 plus an AND.
596 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
597 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
599 // We don't support sin/cos/fmod
600 setOperationAction(ISD::FSIN , MVT::f64, Expand);
601 setOperationAction(ISD::FCOS , MVT::f64, Expand);
602 setOperationAction(ISD::FSIN , MVT::f32, Expand);
603 setOperationAction(ISD::FCOS , MVT::f32, Expand);
605 // Expand FP immediates into loads from the stack, except for the special
607 addLegalFPImmediate(APFloat(+0.0)); // xorpd
608 addLegalFPImmediate(APFloat(+0.0f)); // xorps
609 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
610 // Use SSE for f32, x87 for f64.
611 // Set up the FP register classes.
612 addRegisterClass(MVT::f32, &X86::FR32RegClass);
613 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
615 // Use ANDPS to simulate FABS.
616 setOperationAction(ISD::FABS , MVT::f32, Custom);
618 // Use XORP to simulate FNEG.
619 setOperationAction(ISD::FNEG , MVT::f32, Custom);
621 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
623 // Use ANDPS and ORPS to simulate FCOPYSIGN.
624 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
625 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
627 // We don't support sin/cos/fmod
628 setOperationAction(ISD::FSIN , MVT::f32, Expand);
629 setOperationAction(ISD::FCOS , MVT::f32, Expand);
631 // Special cases we handle for FP constants.
632 addLegalFPImmediate(APFloat(+0.0f)); // xorps
633 addLegalFPImmediate(APFloat(+0.0)); // FLD0
634 addLegalFPImmediate(APFloat(+1.0)); // FLD1
635 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
636 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
638 if (!TM.Options.UnsafeFPMath) {
639 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
640 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
642 } else if (!TM.Options.UseSoftFloat) {
643 // f32 and f64 in x87.
644 // Set up the FP register classes.
645 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
646 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
648 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
649 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
650 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
651 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
653 if (!TM.Options.UnsafeFPMath) {
654 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
655 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
656 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
657 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
659 addLegalFPImmediate(APFloat(+0.0)); // FLD0
660 addLegalFPImmediate(APFloat(+1.0)); // FLD1
661 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
662 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
663 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
664 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
665 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
666 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
669 // We don't support FMA.
670 setOperationAction(ISD::FMA, MVT::f64, Expand);
671 setOperationAction(ISD::FMA, MVT::f32, Expand);
673 // Long double always uses X87.
674 if (!TM.Options.UseSoftFloat) {
675 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
676 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
677 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
679 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
680 addLegalFPImmediate(TmpFlt); // FLD0
682 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
685 APFloat TmpFlt2(+1.0);
686 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
688 addLegalFPImmediate(TmpFlt2); // FLD1
689 TmpFlt2.changeSign();
690 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
693 if (!TM.Options.UnsafeFPMath) {
694 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
695 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
698 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
699 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
700 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
701 setOperationAction(ISD::FRINT, MVT::f80, Expand);
702 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
703 setOperationAction(ISD::FMA, MVT::f80, Expand);
706 // Always use a library call for pow.
707 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
708 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
709 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
711 setOperationAction(ISD::FLOG, MVT::f80, Expand);
712 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
713 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
714 setOperationAction(ISD::FEXP, MVT::f80, Expand);
715 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
717 // First set operation action for all vector types to either promote
718 // (for widening) or expand (for scalarization). Then we will selectively
719 // turn on ones that can be effectively codegen'd.
720 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
721 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
722 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
737 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
739 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
740 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
770 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
775 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
776 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
777 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
778 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
779 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
780 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
781 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
782 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
783 setTruncStoreAction((MVT::SimpleValueType)VT,
784 (MVT::SimpleValueType)InnerVT, Expand);
785 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
786 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
787 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
790 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
791 // with -msoft-float, disable use of MMX as well.
792 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
793 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
794 // No operations on x86mmx supported, everything uses intrinsics.
797 // MMX-sized vectors (other than x86mmx) are expected to be expanded
798 // into smaller operations.
799 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
800 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
801 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
802 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
803 setOperationAction(ISD::AND, MVT::v8i8, Expand);
804 setOperationAction(ISD::AND, MVT::v4i16, Expand);
805 setOperationAction(ISD::AND, MVT::v2i32, Expand);
806 setOperationAction(ISD::AND, MVT::v1i64, Expand);
807 setOperationAction(ISD::OR, MVT::v8i8, Expand);
808 setOperationAction(ISD::OR, MVT::v4i16, Expand);
809 setOperationAction(ISD::OR, MVT::v2i32, Expand);
810 setOperationAction(ISD::OR, MVT::v1i64, Expand);
811 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
812 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
813 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
814 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
815 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
816 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
818 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
819 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
820 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
821 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
822 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
823 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
824 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
825 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
826 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
827 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
829 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
830 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
832 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
833 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
834 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
835 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
836 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
837 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
838 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
839 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
840 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
841 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
842 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
843 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
846 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
847 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
849 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
850 // registers cannot be used even for integer operations.
851 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
852 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
853 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
854 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
856 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
857 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
858 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
859 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
860 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
861 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
862 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
863 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
864 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
865 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
866 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
867 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
868 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
869 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
870 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
871 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
872 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
874 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
875 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
876 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
877 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
879 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
880 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
881 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
883 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
885 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
886 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
887 MVT VT = (MVT::SimpleValueType)i;
888 // Do not attempt to custom lower non-power-of-2 vectors
889 if (!isPowerOf2_32(VT.getVectorNumElements()))
891 // Do not attempt to custom lower non-128-bit vectors
892 if (!VT.is128BitVector())
894 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
895 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
896 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
899 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
900 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
901 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
902 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
903 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
904 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
906 if (Subtarget->is64Bit()) {
907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
908 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
911 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
912 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
913 MVT VT = (MVT::SimpleValueType)i;
915 // Do not attempt to promote non-128-bit vectors
916 if (!VT.is128BitVector())
919 setOperationAction(ISD::AND, VT, Promote);
920 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
921 setOperationAction(ISD::OR, VT, Promote);
922 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
923 setOperationAction(ISD::XOR, VT, Promote);
924 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
925 setOperationAction(ISD::LOAD, VT, Promote);
926 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
927 setOperationAction(ISD::SELECT, VT, Promote);
928 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
931 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
933 // Custom lower v2i64 and v2f64 selects.
934 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
935 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
936 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
937 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
939 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
940 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
942 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
944 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
947 if (Subtarget->hasSSE41()) {
948 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
949 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
950 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
951 setOperationAction(ISD::FRINT, MVT::f32, Legal);
952 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
953 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
954 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
955 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
956 setOperationAction(ISD::FRINT, MVT::f64, Legal);
957 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
959 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
960 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
962 // FIXME: Do we need to handle scalar-to-vector here?
963 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
965 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
966 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
967 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
968 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
969 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
971 // i8 and i16 vectors are custom , because the source register and source
972 // source memory operand types are not the same width. f32 vectors are
973 // custom since the immediate controlling the insert encodes additional
975 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
976 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
977 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
978 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
980 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
982 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
983 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
985 // FIXME: these should be Legal but thats only for the case where
986 // the index is constant. For now custom expand to deal with that.
987 if (Subtarget->is64Bit()) {
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
993 if (Subtarget->hasSSE2()) {
994 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
995 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
997 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
998 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1000 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1001 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1003 if (Subtarget->hasAVX2()) {
1004 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1005 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1007 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1008 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1010 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1012 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1013 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1015 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1016 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1018 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1022 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1023 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1024 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1025 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1026 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1027 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1028 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1030 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1031 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1032 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1034 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1035 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1036 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1037 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1038 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1039 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1040 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1041 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1043 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1044 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1045 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1046 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1047 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1048 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1049 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1050 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1052 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1053 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1054 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1056 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1058 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1059 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1061 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1062 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1064 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1065 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1067 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1068 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1069 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1070 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1072 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1073 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1074 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1076 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1077 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1078 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1079 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1081 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1082 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1083 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1084 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1085 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1086 setOperationAction(ISD::FMA, MVT::f32, Custom);
1087 setOperationAction(ISD::FMA, MVT::f64, Custom);
1090 if (Subtarget->hasAVX2()) {
1091 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1092 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1093 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1094 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1096 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1097 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1098 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1099 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1101 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1102 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1103 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1104 // Don't lower v32i8 because there is no 128-bit byte mul
1106 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1108 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1109 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1111 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1112 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1114 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1116 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1117 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1118 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1119 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1121 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1122 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1123 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1124 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1126 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1127 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1128 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1129 // Don't lower v32i8 because there is no 128-bit byte mul
1131 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1132 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1134 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1135 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1137 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1140 // Custom lower several nodes for 256-bit types.
1141 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1142 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1143 MVT VT = (MVT::SimpleValueType)i;
1145 // Extract subvector is special because the value type
1146 // (result) is 128-bit but the source is 256-bit wide.
1147 if (VT.is128BitVector())
1148 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1150 // Do not attempt to custom lower other non-256-bit vectors
1151 if (!VT.is256BitVector())
1154 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1155 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1156 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1157 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1158 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1159 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1160 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1163 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1164 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1165 MVT VT = (MVT::SimpleValueType)i;
1167 // Do not attempt to promote non-256-bit vectors
1168 if (!VT.is256BitVector())
1171 setOperationAction(ISD::AND, VT, Promote);
1172 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1173 setOperationAction(ISD::OR, VT, Promote);
1174 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1175 setOperationAction(ISD::XOR, VT, Promote);
1176 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1177 setOperationAction(ISD::LOAD, VT, Promote);
1178 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1179 setOperationAction(ISD::SELECT, VT, Promote);
1180 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1184 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1185 // of this type with custom code.
1186 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1187 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1188 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1192 // We want to custom lower some of our intrinsics.
1193 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1194 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1197 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1198 // handle type legalization for these operations here.
1200 // FIXME: We really should do custom legalization for addition and
1201 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1202 // than generic legalization for 64-bit multiplication-with-overflow, though.
1203 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1204 // Add/Sub/Mul with overflow operations are custom lowered.
1206 setOperationAction(ISD::SADDO, VT, Custom);
1207 setOperationAction(ISD::UADDO, VT, Custom);
1208 setOperationAction(ISD::SSUBO, VT, Custom);
1209 setOperationAction(ISD::USUBO, VT, Custom);
1210 setOperationAction(ISD::SMULO, VT, Custom);
1211 setOperationAction(ISD::UMULO, VT, Custom);
1214 // There are no 8-bit 3-address imul/mul instructions
1215 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1216 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1218 if (!Subtarget->is64Bit()) {
1219 // These libcalls are not available in 32-bit.
1220 setLibcallName(RTLIB::SHL_I128, 0);
1221 setLibcallName(RTLIB::SRL_I128, 0);
1222 setLibcallName(RTLIB::SRA_I128, 0);
1225 // We have target-specific dag combine patterns for the following nodes:
1226 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1227 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1228 setTargetDAGCombine(ISD::VSELECT);
1229 setTargetDAGCombine(ISD::SELECT);
1230 setTargetDAGCombine(ISD::SHL);
1231 setTargetDAGCombine(ISD::SRA);
1232 setTargetDAGCombine(ISD::SRL);
1233 setTargetDAGCombine(ISD::OR);
1234 setTargetDAGCombine(ISD::AND);
1235 setTargetDAGCombine(ISD::ADD);
1236 setTargetDAGCombine(ISD::FADD);
1237 setTargetDAGCombine(ISD::FSUB);
1238 setTargetDAGCombine(ISD::FMA);
1239 setTargetDAGCombine(ISD::SUB);
1240 setTargetDAGCombine(ISD::LOAD);
1241 setTargetDAGCombine(ISD::STORE);
1242 setTargetDAGCombine(ISD::ZERO_EXTEND);
1243 setTargetDAGCombine(ISD::ANY_EXTEND);
1244 setTargetDAGCombine(ISD::SIGN_EXTEND);
1245 setTargetDAGCombine(ISD::TRUNCATE);
1246 setTargetDAGCombine(ISD::UINT_TO_FP);
1247 setTargetDAGCombine(ISD::SINT_TO_FP);
1248 setTargetDAGCombine(ISD::SETCC);
1249 setTargetDAGCombine(ISD::FP_TO_SINT);
1250 if (Subtarget->is64Bit())
1251 setTargetDAGCombine(ISD::MUL);
1252 setTargetDAGCombine(ISD::XOR);
1254 computeRegisterProperties();
1256 // On Darwin, -Os means optimize for size without hurting performance,
1257 // do not reduce the limit.
1258 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1259 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1260 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1261 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1262 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1263 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1264 setPrefLoopAlignment(4); // 2^4 bytes.
1265 benefitFromCodePlacementOpt = true;
1267 // Predictable cmov don't hurt on atom because it's in-order.
1268 predictableSelectIsExpensive = !Subtarget->isAtom();
1270 setPrefFunctionAlignment(4); // 2^4 bytes.
1274 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1275 if (!VT.isVector()) return MVT::i8;
1276 return VT.changeVectorElementTypeToInteger();
1280 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1281 /// the desired ByVal argument alignment.
1282 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1285 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1286 if (VTy->getBitWidth() == 128)
1288 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1289 unsigned EltAlign = 0;
1290 getMaxByValAlign(ATy->getElementType(), EltAlign);
1291 if (EltAlign > MaxAlign)
1292 MaxAlign = EltAlign;
1293 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1294 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1295 unsigned EltAlign = 0;
1296 getMaxByValAlign(STy->getElementType(i), EltAlign);
1297 if (EltAlign > MaxAlign)
1298 MaxAlign = EltAlign;
1305 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1306 /// function arguments in the caller parameter area. For X86, aggregates
1307 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1308 /// are at 4-byte boundaries.
1309 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1310 if (Subtarget->is64Bit()) {
1311 // Max of 8 and alignment of type.
1312 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1319 if (Subtarget->hasSSE1())
1320 getMaxByValAlign(Ty, Align);
1324 /// getOptimalMemOpType - Returns the target specific optimal type for load
1325 /// and store operations as a result of memset, memcpy, and memmove
1326 /// lowering. If DstAlign is zero that means it's safe to destination
1327 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1328 /// means there isn't a need to check it against alignment requirement,
1329 /// probably because the source does not need to be loaded. If
1330 /// 'IsZeroVal' is true, that means it's safe to return a
1331 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1332 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1333 /// constant so it does not need to be loaded.
1334 /// It returns EVT::Other if the type should be determined using generic
1335 /// target-independent logic.
1337 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1338 unsigned DstAlign, unsigned SrcAlign,
1341 MachineFunction &MF) const {
1342 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1343 // linux. This is because the stack realignment code can't handle certain
1344 // cases like PR2962. This should be removed when PR2962 is fixed.
1345 const Function *F = MF.getFunction();
1347 !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1349 (Subtarget->isUnalignedMemAccessFast() ||
1350 ((DstAlign == 0 || DstAlign >= 16) &&
1351 (SrcAlign == 0 || SrcAlign >= 16))) &&
1352 Subtarget->getStackAlignment() >= 16) {
1353 if (Subtarget->getStackAlignment() >= 32) {
1354 if (Subtarget->hasAVX2())
1356 if (Subtarget->hasAVX())
1359 if (Subtarget->hasSSE2())
1361 if (Subtarget->hasSSE1())
1363 } else if (!MemcpyStrSrc && Size >= 8 &&
1364 !Subtarget->is64Bit() &&
1365 Subtarget->getStackAlignment() >= 8 &&
1366 Subtarget->hasSSE2()) {
1367 // Do not use f64 to lower memcpy if source is string constant. It's
1368 // better to use i32 to avoid the loads.
1372 if (Subtarget->is64Bit() && Size >= 8)
1377 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1378 /// current function. The returned value is a member of the
1379 /// MachineJumpTableInfo::JTEntryKind enum.
1380 unsigned X86TargetLowering::getJumpTableEncoding() const {
1381 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1383 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1384 Subtarget->isPICStyleGOT())
1385 return MachineJumpTableInfo::EK_Custom32;
1387 // Otherwise, use the normal jump table encoding heuristics.
1388 return TargetLowering::getJumpTableEncoding();
1392 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1393 const MachineBasicBlock *MBB,
1394 unsigned uid,MCContext &Ctx) const{
1395 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1396 Subtarget->isPICStyleGOT());
1397 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1399 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1400 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1403 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1405 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1406 SelectionDAG &DAG) const {
1407 if (!Subtarget->is64Bit())
1408 // This doesn't have DebugLoc associated with it, but is not really the
1409 // same as a Register.
1410 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1414 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1415 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1417 const MCExpr *X86TargetLowering::
1418 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1419 MCContext &Ctx) const {
1420 // X86-64 uses RIP relative addressing based on the jump table label.
1421 if (Subtarget->isPICStyleRIPRel())
1422 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1424 // Otherwise, the reference is relative to the PIC base.
1425 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1428 // FIXME: Why this routine is here? Move to RegInfo!
1429 std::pair<const TargetRegisterClass*, uint8_t>
1430 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1431 const TargetRegisterClass *RRC = 0;
1433 switch (VT.getSimpleVT().SimpleTy) {
1435 return TargetLowering::findRepresentativeClass(VT);
1436 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1437 RRC = Subtarget->is64Bit() ?
1438 (const TargetRegisterClass*)&X86::GR64RegClass :
1439 (const TargetRegisterClass*)&X86::GR32RegClass;
1442 RRC = &X86::VR64RegClass;
1444 case MVT::f32: case MVT::f64:
1445 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1446 case MVT::v4f32: case MVT::v2f64:
1447 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1449 RRC = &X86::VR128RegClass;
1452 return std::make_pair(RRC, Cost);
1455 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1456 unsigned &Offset) const {
1457 if (!Subtarget->isTargetLinux())
1460 if (Subtarget->is64Bit()) {
1461 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1463 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1476 //===----------------------------------------------------------------------===//
1477 // Return Value Calling Convention Implementation
1478 //===----------------------------------------------------------------------===//
1480 #include "X86GenCallingConv.inc"
1483 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1484 MachineFunction &MF, bool isVarArg,
1485 const SmallVectorImpl<ISD::OutputArg> &Outs,
1486 LLVMContext &Context) const {
1487 SmallVector<CCValAssign, 16> RVLocs;
1488 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1490 return CCInfo.CheckReturn(Outs, RetCC_X86);
1494 X86TargetLowering::LowerReturn(SDValue Chain,
1495 CallingConv::ID CallConv, bool isVarArg,
1496 const SmallVectorImpl<ISD::OutputArg> &Outs,
1497 const SmallVectorImpl<SDValue> &OutVals,
1498 DebugLoc dl, SelectionDAG &DAG) const {
1499 MachineFunction &MF = DAG.getMachineFunction();
1500 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1502 SmallVector<CCValAssign, 16> RVLocs;
1503 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1504 RVLocs, *DAG.getContext());
1505 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1507 // Add the regs to the liveout set for the function.
1508 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1509 for (unsigned i = 0; i != RVLocs.size(); ++i)
1510 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1511 MRI.addLiveOut(RVLocs[i].getLocReg());
1515 SmallVector<SDValue, 6> RetOps;
1516 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1517 // Operand #1 = Bytes To Pop
1518 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1521 // Copy the result values into the output registers.
1522 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1523 CCValAssign &VA = RVLocs[i];
1524 assert(VA.isRegLoc() && "Can only return in registers!");
1525 SDValue ValToCopy = OutVals[i];
1526 EVT ValVT = ValToCopy.getValueType();
1528 // Promote values to the appropriate types
1529 if (VA.getLocInfo() == CCValAssign::SExt)
1530 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1531 else if (VA.getLocInfo() == CCValAssign::ZExt)
1532 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1533 else if (VA.getLocInfo() == CCValAssign::AExt)
1534 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1535 else if (VA.getLocInfo() == CCValAssign::BCvt)
1536 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1538 // If this is x86-64, and we disabled SSE, we can't return FP values,
1539 // or SSE or MMX vectors.
1540 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1541 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1542 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1543 report_fatal_error("SSE register return with SSE disabled");
1545 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1546 // llvm-gcc has never done it right and no one has noticed, so this
1547 // should be OK for now.
1548 if (ValVT == MVT::f64 &&
1549 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1550 report_fatal_error("SSE2 register return with SSE2 disabled");
1552 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1553 // the RET instruction and handled by the FP Stackifier.
1554 if (VA.getLocReg() == X86::ST0 ||
1555 VA.getLocReg() == X86::ST1) {
1556 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1557 // change the value to the FP stack register class.
1558 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1559 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1560 RetOps.push_back(ValToCopy);
1561 // Don't emit a copytoreg.
1565 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1566 // which is returned in RAX / RDX.
1567 if (Subtarget->is64Bit()) {
1568 if (ValVT == MVT::x86mmx) {
1569 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1570 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1571 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1573 // If we don't have SSE2 available, convert to v4f32 so the generated
1574 // register is legal.
1575 if (!Subtarget->hasSSE2())
1576 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1581 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1582 Flag = Chain.getValue(1);
1585 // The x86-64 ABI for returning structs by value requires that we copy
1586 // the sret argument into %rax for the return. We saved the argument into
1587 // a virtual register in the entry block, so now we copy the value out
1589 if (Subtarget->is64Bit() &&
1590 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1591 MachineFunction &MF = DAG.getMachineFunction();
1592 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1593 unsigned Reg = FuncInfo->getSRetReturnReg();
1595 "SRetReturnReg should have been set in LowerFormalArguments().");
1596 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1598 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1599 Flag = Chain.getValue(1);
1601 // RAX now acts like a return value.
1602 MRI.addLiveOut(X86::RAX);
1605 RetOps[0] = Chain; // Update chain.
1607 // Add the flag if we have it.
1609 RetOps.push_back(Flag);
1611 return DAG.getNode(X86ISD::RET_FLAG, dl,
1612 MVT::Other, &RetOps[0], RetOps.size());
1615 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1616 if (N->getNumValues() != 1)
1618 if (!N->hasNUsesOfValue(1, 0))
1621 SDValue TCChain = Chain;
1622 SDNode *Copy = *N->use_begin();
1623 if (Copy->getOpcode() == ISD::CopyToReg) {
1624 // If the copy has a glue operand, we conservatively assume it isn't safe to
1625 // perform a tail call.
1626 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1628 TCChain = Copy->getOperand(0);
1629 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1632 bool HasRet = false;
1633 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1635 if (UI->getOpcode() != X86ISD::RET_FLAG)
1648 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1649 ISD::NodeType ExtendKind) const {
1651 // TODO: Is this also valid on 32-bit?
1652 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1653 ReturnMVT = MVT::i8;
1655 ReturnMVT = MVT::i32;
1657 EVT MinVT = getRegisterType(Context, ReturnMVT);
1658 return VT.bitsLT(MinVT) ? MinVT : VT;
1661 /// LowerCallResult - Lower the result values of a call into the
1662 /// appropriate copies out of appropriate physical registers.
1665 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1666 CallingConv::ID CallConv, bool isVarArg,
1667 const SmallVectorImpl<ISD::InputArg> &Ins,
1668 DebugLoc dl, SelectionDAG &DAG,
1669 SmallVectorImpl<SDValue> &InVals) const {
1671 // Assign locations to each value returned by this call.
1672 SmallVector<CCValAssign, 16> RVLocs;
1673 bool Is64Bit = Subtarget->is64Bit();
1674 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1675 getTargetMachine(), RVLocs, *DAG.getContext());
1676 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1678 // Copy all of the result registers out of their specified physreg.
1679 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1680 CCValAssign &VA = RVLocs[i];
1681 EVT CopyVT = VA.getValVT();
1683 // If this is x86-64, and we disabled SSE, we can't return FP values
1684 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1685 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1686 report_fatal_error("SSE register return with SSE disabled");
1691 // If this is a call to a function that returns an fp value on the floating
1692 // point stack, we must guarantee the value is popped from the stack, so
1693 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1694 // if the return value is not used. We use the FpPOP_RETVAL instruction
1696 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1697 // If we prefer to use the value in xmm registers, copy it out as f80 and
1698 // use a truncate to move it from fp stack reg to xmm reg.
1699 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1700 SDValue Ops[] = { Chain, InFlag };
1701 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1702 MVT::Other, MVT::Glue, Ops, 2), 1);
1703 Val = Chain.getValue(0);
1705 // Round the f80 to the right size, which also moves it to the appropriate
1707 if (CopyVT != VA.getValVT())
1708 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1709 // This truncation won't change the value.
1710 DAG.getIntPtrConstant(1));
1712 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1713 CopyVT, InFlag).getValue(1);
1714 Val = Chain.getValue(0);
1716 InFlag = Chain.getValue(2);
1717 InVals.push_back(Val);
1724 //===----------------------------------------------------------------------===//
1725 // C & StdCall & Fast Calling Convention implementation
1726 //===----------------------------------------------------------------------===//
1727 // StdCall calling convention seems to be standard for many Windows' API
1728 // routines and around. It differs from C calling convention just a little:
1729 // callee should clean up the stack, not caller. Symbols should be also
1730 // decorated in some fancy way :) It doesn't support any vector arguments.
1731 // For info on fast calling convention see Fast Calling Convention (tail call)
1732 // implementation LowerX86_32FastCCCallTo.
1734 /// CallIsStructReturn - Determines whether a call uses struct return
1736 enum StructReturnType {
1741 static StructReturnType
1742 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1744 return NotStructReturn;
1746 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1747 if (!Flags.isSRet())
1748 return NotStructReturn;
1749 if (Flags.isInReg())
1750 return RegStructReturn;
1751 return StackStructReturn;
1754 /// ArgsAreStructReturn - Determines whether a function uses struct
1755 /// return semantics.
1756 static StructReturnType
1757 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1759 return NotStructReturn;
1761 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1762 if (!Flags.isSRet())
1763 return NotStructReturn;
1764 if (Flags.isInReg())
1765 return RegStructReturn;
1766 return StackStructReturn;
1769 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1770 /// by "Src" to address "Dst" with size and alignment information specified by
1771 /// the specific parameter attribute. The copy will be passed as a byval
1772 /// function parameter.
1774 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1775 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1777 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1779 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1780 /*isVolatile*/false, /*AlwaysInline=*/true,
1781 MachinePointerInfo(), MachinePointerInfo());
1784 /// IsTailCallConvention - Return true if the calling convention is one that
1785 /// supports tail call optimization.
1786 static bool IsTailCallConvention(CallingConv::ID CC) {
1787 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1790 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1791 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1795 CallingConv::ID CalleeCC = CS.getCallingConv();
1796 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1802 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1803 /// a tailcall target by changing its ABI.
1804 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1805 bool GuaranteedTailCallOpt) {
1806 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1810 X86TargetLowering::LowerMemArgument(SDValue Chain,
1811 CallingConv::ID CallConv,
1812 const SmallVectorImpl<ISD::InputArg> &Ins,
1813 DebugLoc dl, SelectionDAG &DAG,
1814 const CCValAssign &VA,
1815 MachineFrameInfo *MFI,
1817 // Create the nodes corresponding to a load from this parameter slot.
1818 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1819 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1820 getTargetMachine().Options.GuaranteedTailCallOpt);
1821 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1824 // If value is passed by pointer we have address passed instead of the value
1826 if (VA.getLocInfo() == CCValAssign::Indirect)
1827 ValVT = VA.getLocVT();
1829 ValVT = VA.getValVT();
1831 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1832 // changed with more analysis.
1833 // In case of tail call optimization mark all arguments mutable. Since they
1834 // could be overwritten by lowering of arguments in case of a tail call.
1835 if (Flags.isByVal()) {
1836 unsigned Bytes = Flags.getByValSize();
1837 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1838 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1839 return DAG.getFrameIndex(FI, getPointerTy());
1841 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1842 VA.getLocMemOffset(), isImmutable);
1843 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1844 return DAG.getLoad(ValVT, dl, Chain, FIN,
1845 MachinePointerInfo::getFixedStack(FI),
1846 false, false, false, 0);
1851 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1852 CallingConv::ID CallConv,
1854 const SmallVectorImpl<ISD::InputArg> &Ins,
1857 SmallVectorImpl<SDValue> &InVals)
1859 MachineFunction &MF = DAG.getMachineFunction();
1860 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1862 const Function* Fn = MF.getFunction();
1863 if (Fn->hasExternalLinkage() &&
1864 Subtarget->isTargetCygMing() &&
1865 Fn->getName() == "main")
1866 FuncInfo->setForceFramePointer(true);
1868 MachineFrameInfo *MFI = MF.getFrameInfo();
1869 bool Is64Bit = Subtarget->is64Bit();
1870 bool IsWindows = Subtarget->isTargetWindows();
1871 bool IsWin64 = Subtarget->isTargetWin64();
1873 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1874 "Var args not supported with calling convention fastcc or ghc");
1876 // Assign locations to all of the incoming arguments.
1877 SmallVector<CCValAssign, 16> ArgLocs;
1878 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1879 ArgLocs, *DAG.getContext());
1881 // Allocate shadow area for Win64
1883 CCInfo.AllocateStack(32, 8);
1886 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1888 unsigned LastVal = ~0U;
1890 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1891 CCValAssign &VA = ArgLocs[i];
1892 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1894 assert(VA.getValNo() != LastVal &&
1895 "Don't support value assigned to multiple locs yet");
1897 LastVal = VA.getValNo();
1899 if (VA.isRegLoc()) {
1900 EVT RegVT = VA.getLocVT();
1901 const TargetRegisterClass *RC;
1902 if (RegVT == MVT::i32)
1903 RC = &X86::GR32RegClass;
1904 else if (Is64Bit && RegVT == MVT::i64)
1905 RC = &X86::GR64RegClass;
1906 else if (RegVT == MVT::f32)
1907 RC = &X86::FR32RegClass;
1908 else if (RegVT == MVT::f64)
1909 RC = &X86::FR64RegClass;
1910 else if (RegVT.is256BitVector())
1911 RC = &X86::VR256RegClass;
1912 else if (RegVT.is128BitVector())
1913 RC = &X86::VR128RegClass;
1914 else if (RegVT == MVT::x86mmx)
1915 RC = &X86::VR64RegClass;
1917 llvm_unreachable("Unknown argument type!");
1919 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1920 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1922 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1923 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1925 if (VA.getLocInfo() == CCValAssign::SExt)
1926 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1927 DAG.getValueType(VA.getValVT()));
1928 else if (VA.getLocInfo() == CCValAssign::ZExt)
1929 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1930 DAG.getValueType(VA.getValVT()));
1931 else if (VA.getLocInfo() == CCValAssign::BCvt)
1932 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1934 if (VA.isExtInLoc()) {
1935 // Handle MMX values passed in XMM regs.
1936 if (RegVT.isVector()) {
1937 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1940 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1943 assert(VA.isMemLoc());
1944 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1947 // If value is passed via pointer - do a load.
1948 if (VA.getLocInfo() == CCValAssign::Indirect)
1949 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1950 MachinePointerInfo(), false, false, false, 0);
1952 InVals.push_back(ArgValue);
1955 // The x86-64 ABI for returning structs by value requires that we copy
1956 // the sret argument into %rax for the return. Save the argument into
1957 // a virtual register so that we can access it from the return points.
1958 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1959 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1960 unsigned Reg = FuncInfo->getSRetReturnReg();
1962 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1963 FuncInfo->setSRetReturnReg(Reg);
1965 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1966 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1969 unsigned StackSize = CCInfo.getNextStackOffset();
1970 // Align stack specially for tail calls.
1971 if (FuncIsMadeTailCallSafe(CallConv,
1972 MF.getTarget().Options.GuaranteedTailCallOpt))
1973 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1975 // If the function takes variable number of arguments, make a frame index for
1976 // the start of the first vararg value... for expansion of llvm.va_start.
1978 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1979 CallConv != CallingConv::X86_ThisCall)) {
1980 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1983 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1985 // FIXME: We should really autogenerate these arrays
1986 static const uint16_t GPR64ArgRegsWin64[] = {
1987 X86::RCX, X86::RDX, X86::R8, X86::R9
1989 static const uint16_t GPR64ArgRegs64Bit[] = {
1990 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1992 static const uint16_t XMMArgRegs64Bit[] = {
1993 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1994 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1996 const uint16_t *GPR64ArgRegs;
1997 unsigned NumXMMRegs = 0;
2000 // The XMM registers which might contain var arg parameters are shadowed
2001 // in their paired GPR. So we only need to save the GPR to their home
2003 TotalNumIntRegs = 4;
2004 GPR64ArgRegs = GPR64ArgRegsWin64;
2006 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2007 GPR64ArgRegs = GPR64ArgRegs64Bit;
2009 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2012 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2015 bool NoImplicitFloatOps = Fn->getFnAttributes().
2016 hasAttribute(Attributes::NoImplicitFloat);
2017 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2018 "SSE register cannot be used when SSE is disabled!");
2019 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2020 NoImplicitFloatOps) &&
2021 "SSE register cannot be used when SSE is disabled!");
2022 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2023 !Subtarget->hasSSE1())
2024 // Kernel mode asks for SSE to be disabled, so don't push them
2026 TotalNumXMMRegs = 0;
2029 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2030 // Get to the caller-allocated home save location. Add 8 to account
2031 // for the return address.
2032 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2033 FuncInfo->setRegSaveFrameIndex(
2034 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2035 // Fixup to set vararg frame on shadow area (4 x i64).
2037 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2039 // For X86-64, if there are vararg parameters that are passed via
2040 // registers, then we must store them to their spots on the stack so
2041 // they may be loaded by deferencing the result of va_next.
2042 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2043 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2044 FuncInfo->setRegSaveFrameIndex(
2045 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2049 // Store the integer parameter registers.
2050 SmallVector<SDValue, 8> MemOps;
2051 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2053 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2054 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2055 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2056 DAG.getIntPtrConstant(Offset));
2057 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2058 &X86::GR64RegClass);
2059 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2061 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2062 MachinePointerInfo::getFixedStack(
2063 FuncInfo->getRegSaveFrameIndex(), Offset),
2065 MemOps.push_back(Store);
2069 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2070 // Now store the XMM (fp + vector) parameter registers.
2071 SmallVector<SDValue, 11> SaveXMMOps;
2072 SaveXMMOps.push_back(Chain);
2074 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2075 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2076 SaveXMMOps.push_back(ALVal);
2078 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2079 FuncInfo->getRegSaveFrameIndex()));
2080 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2081 FuncInfo->getVarArgsFPOffset()));
2083 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2084 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2085 &X86::VR128RegClass);
2086 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2087 SaveXMMOps.push_back(Val);
2089 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2091 &SaveXMMOps[0], SaveXMMOps.size()));
2094 if (!MemOps.empty())
2095 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2096 &MemOps[0], MemOps.size());
2100 // Some CCs need callee pop.
2101 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2102 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2103 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2105 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2106 // If this is an sret function, the return should pop the hidden pointer.
2107 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2108 argsAreStructReturn(Ins) == StackStructReturn)
2109 FuncInfo->setBytesToPopOnReturn(4);
2113 // RegSaveFrameIndex is X86-64 only.
2114 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2115 if (CallConv == CallingConv::X86_FastCall ||
2116 CallConv == CallingConv::X86_ThisCall)
2117 // fastcc functions can't have varargs.
2118 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2121 FuncInfo->setArgumentStackSize(StackSize);
2127 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2128 SDValue StackPtr, SDValue Arg,
2129 DebugLoc dl, SelectionDAG &DAG,
2130 const CCValAssign &VA,
2131 ISD::ArgFlagsTy Flags) const {
2132 unsigned LocMemOffset = VA.getLocMemOffset();
2133 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2134 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2135 if (Flags.isByVal())
2136 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2138 return DAG.getStore(Chain, dl, Arg, PtrOff,
2139 MachinePointerInfo::getStack(LocMemOffset),
2143 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2144 /// optimization is performed and it is required.
2146 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2147 SDValue &OutRetAddr, SDValue Chain,
2148 bool IsTailCall, bool Is64Bit,
2149 int FPDiff, DebugLoc dl) const {
2150 // Adjust the Return address stack slot.
2151 EVT VT = getPointerTy();
2152 OutRetAddr = getReturnAddressFrameIndex(DAG);
2154 // Load the "old" Return address.
2155 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2156 false, false, false, 0);
2157 return SDValue(OutRetAddr.getNode(), 1);
2160 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2161 /// optimization is performed and it is required (FPDiff!=0).
2163 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2164 SDValue Chain, SDValue RetAddrFrIdx,
2165 bool Is64Bit, int FPDiff, DebugLoc dl) {
2166 // Store the return address to the appropriate stack slot.
2167 if (!FPDiff) return Chain;
2168 // Calculate the new stack slot for the return address.
2169 int SlotSize = Is64Bit ? 8 : 4;
2170 int NewReturnAddrFI =
2171 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2172 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2173 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2174 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2175 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2181 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2182 SmallVectorImpl<SDValue> &InVals) const {
2183 SelectionDAG &DAG = CLI.DAG;
2184 DebugLoc &dl = CLI.DL;
2185 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2186 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2187 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2188 SDValue Chain = CLI.Chain;
2189 SDValue Callee = CLI.Callee;
2190 CallingConv::ID CallConv = CLI.CallConv;
2191 bool &isTailCall = CLI.IsTailCall;
2192 bool isVarArg = CLI.IsVarArg;
2194 MachineFunction &MF = DAG.getMachineFunction();
2195 bool Is64Bit = Subtarget->is64Bit();
2196 bool IsWin64 = Subtarget->isTargetWin64();
2197 bool IsWindows = Subtarget->isTargetWindows();
2198 StructReturnType SR = callIsStructReturn(Outs);
2199 bool IsSibcall = false;
2201 if (MF.getTarget().Options.DisableTailCalls)
2205 // Check if it's really possible to do a tail call.
2206 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2207 isVarArg, SR != NotStructReturn,
2208 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2209 Outs, OutVals, Ins, DAG);
2211 // Sibcalls are automatically detected tailcalls which do not require
2213 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2220 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2221 "Var args not supported with calling convention fastcc or ghc");
2223 // Analyze operands of the call, assigning locations to each operand.
2224 SmallVector<CCValAssign, 16> ArgLocs;
2225 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2226 ArgLocs, *DAG.getContext());
2228 // Allocate shadow area for Win64
2230 CCInfo.AllocateStack(32, 8);
2233 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2235 // Get a count of how many bytes are to be pushed on the stack.
2236 unsigned NumBytes = CCInfo.getNextStackOffset();
2238 // This is a sibcall. The memory operands are available in caller's
2239 // own caller's stack.
2241 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2242 IsTailCallConvention(CallConv))
2243 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2246 if (isTailCall && !IsSibcall) {
2247 // Lower arguments at fp - stackoffset + fpdiff.
2248 unsigned NumBytesCallerPushed =
2249 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2250 FPDiff = NumBytesCallerPushed - NumBytes;
2252 // Set the delta of movement of the returnaddr stackslot.
2253 // But only set if delta is greater than previous delta.
2254 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2255 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2259 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2261 SDValue RetAddrFrIdx;
2262 // Load return address for tail calls.
2263 if (isTailCall && FPDiff)
2264 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2265 Is64Bit, FPDiff, dl);
2267 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2268 SmallVector<SDValue, 8> MemOpChains;
2271 // Walk the register/memloc assignments, inserting copies/loads. In the case
2272 // of tail call optimization arguments are handle later.
2273 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2274 CCValAssign &VA = ArgLocs[i];
2275 EVT RegVT = VA.getLocVT();
2276 SDValue Arg = OutVals[i];
2277 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2278 bool isByVal = Flags.isByVal();
2280 // Promote the value if needed.
2281 switch (VA.getLocInfo()) {
2282 default: llvm_unreachable("Unknown loc info!");
2283 case CCValAssign::Full: break;
2284 case CCValAssign::SExt:
2285 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2287 case CCValAssign::ZExt:
2288 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2290 case CCValAssign::AExt:
2291 if (RegVT.is128BitVector()) {
2292 // Special case: passing MMX values in XMM registers.
2293 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2294 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2295 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2297 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2299 case CCValAssign::BCvt:
2300 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2302 case CCValAssign::Indirect: {
2303 // Store the argument.
2304 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2305 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2306 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2307 MachinePointerInfo::getFixedStack(FI),
2314 if (VA.isRegLoc()) {
2315 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2316 if (isVarArg && IsWin64) {
2317 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2318 // shadow reg if callee is a varargs function.
2319 unsigned ShadowReg = 0;
2320 switch (VA.getLocReg()) {
2321 case X86::XMM0: ShadowReg = X86::RCX; break;
2322 case X86::XMM1: ShadowReg = X86::RDX; break;
2323 case X86::XMM2: ShadowReg = X86::R8; break;
2324 case X86::XMM3: ShadowReg = X86::R9; break;
2327 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2329 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2330 assert(VA.isMemLoc());
2331 if (StackPtr.getNode() == 0)
2332 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2333 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2334 dl, DAG, VA, Flags));
2338 if (!MemOpChains.empty())
2339 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2340 &MemOpChains[0], MemOpChains.size());
2342 if (Subtarget->isPICStyleGOT()) {
2343 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2346 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2347 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2349 // If we are tail calling and generating PIC/GOT style code load the
2350 // address of the callee into ECX. The value in ecx is used as target of
2351 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2352 // for tail calls on PIC/GOT architectures. Normally we would just put the
2353 // address of GOT into ebx and then call target@PLT. But for tail calls
2354 // ebx would be restored (since ebx is callee saved) before jumping to the
2357 // Note: The actual moving to ECX is done further down.
2358 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2359 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2360 !G->getGlobal()->hasProtectedVisibility())
2361 Callee = LowerGlobalAddress(Callee, DAG);
2362 else if (isa<ExternalSymbolSDNode>(Callee))
2363 Callee = LowerExternalSymbol(Callee, DAG);
2367 if (Is64Bit && isVarArg && !IsWin64) {
2368 // From AMD64 ABI document:
2369 // For calls that may call functions that use varargs or stdargs
2370 // (prototype-less calls or calls to functions containing ellipsis (...) in
2371 // the declaration) %al is used as hidden argument to specify the number
2372 // of SSE registers used. The contents of %al do not need to match exactly
2373 // the number of registers, but must be an ubound on the number of SSE
2374 // registers used and is in the range 0 - 8 inclusive.
2376 // Count the number of XMM registers allocated.
2377 static const uint16_t XMMArgRegs[] = {
2378 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2379 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2381 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2382 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2383 && "SSE registers cannot be used when SSE is disabled");
2385 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2386 DAG.getConstant(NumXMMRegs, MVT::i8)));
2389 // For tail calls lower the arguments to the 'real' stack slot.
2391 // Force all the incoming stack arguments to be loaded from the stack
2392 // before any new outgoing arguments are stored to the stack, because the
2393 // outgoing stack slots may alias the incoming argument stack slots, and
2394 // the alias isn't otherwise explicit. This is slightly more conservative
2395 // than necessary, because it means that each store effectively depends
2396 // on every argument instead of just those arguments it would clobber.
2397 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2399 SmallVector<SDValue, 8> MemOpChains2;
2402 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2403 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2404 CCValAssign &VA = ArgLocs[i];
2407 assert(VA.isMemLoc());
2408 SDValue Arg = OutVals[i];
2409 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2410 // Create frame index.
2411 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2412 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2413 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2414 FIN = DAG.getFrameIndex(FI, getPointerTy());
2416 if (Flags.isByVal()) {
2417 // Copy relative to framepointer.
2418 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2419 if (StackPtr.getNode() == 0)
2420 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2422 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2424 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2428 // Store relative to framepointer.
2429 MemOpChains2.push_back(
2430 DAG.getStore(ArgChain, dl, Arg, FIN,
2431 MachinePointerInfo::getFixedStack(FI),
2437 if (!MemOpChains2.empty())
2438 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2439 &MemOpChains2[0], MemOpChains2.size());
2441 // Store the return address to the appropriate stack slot.
2442 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2446 // Build a sequence of copy-to-reg nodes chained together with token chain
2447 // and flag operands which copy the outgoing args into registers.
2449 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2450 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2451 RegsToPass[i].second, InFlag);
2452 InFlag = Chain.getValue(1);
2455 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2456 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2457 // In the 64-bit large code model, we have to make all calls
2458 // through a register, since the call instruction's 32-bit
2459 // pc-relative offset may not be large enough to hold the whole
2461 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2462 // If the callee is a GlobalAddress node (quite common, every direct call
2463 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2466 // We should use extra load for direct calls to dllimported functions in
2468 const GlobalValue *GV = G->getGlobal();
2469 if (!GV->hasDLLImportLinkage()) {
2470 unsigned char OpFlags = 0;
2471 bool ExtraLoad = false;
2472 unsigned WrapperKind = ISD::DELETED_NODE;
2474 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2475 // external symbols most go through the PLT in PIC mode. If the symbol
2476 // has hidden or protected visibility, or if it is static or local, then
2477 // we don't need to use the PLT - we can directly call it.
2478 if (Subtarget->isTargetELF() &&
2479 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2480 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2481 OpFlags = X86II::MO_PLT;
2482 } else if (Subtarget->isPICStyleStubAny() &&
2483 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2484 (!Subtarget->getTargetTriple().isMacOSX() ||
2485 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2486 // PC-relative references to external symbols should go through $stub,
2487 // unless we're building with the leopard linker or later, which
2488 // automatically synthesizes these stubs.
2489 OpFlags = X86II::MO_DARWIN_STUB;
2490 } else if (Subtarget->isPICStyleRIPRel() &&
2491 isa<Function>(GV) &&
2492 cast<Function>(GV)->getFnAttributes().
2493 hasAttribute(Attributes::NonLazyBind)) {
2494 // If the function is marked as non-lazy, generate an indirect call
2495 // which loads from the GOT directly. This avoids runtime overhead
2496 // at the cost of eager binding (and one extra byte of encoding).
2497 OpFlags = X86II::MO_GOTPCREL;
2498 WrapperKind = X86ISD::WrapperRIP;
2502 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2503 G->getOffset(), OpFlags);
2505 // Add a wrapper if needed.
2506 if (WrapperKind != ISD::DELETED_NODE)
2507 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2508 // Add extra indirection if needed.
2510 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2511 MachinePointerInfo::getGOT(),
2512 false, false, false, 0);
2514 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2515 unsigned char OpFlags = 0;
2517 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2518 // external symbols should go through the PLT.
2519 if (Subtarget->isTargetELF() &&
2520 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2521 OpFlags = X86II::MO_PLT;
2522 } else if (Subtarget->isPICStyleStubAny() &&
2523 (!Subtarget->getTargetTriple().isMacOSX() ||
2524 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2525 // PC-relative references to external symbols should go through $stub,
2526 // unless we're building with the leopard linker or later, which
2527 // automatically synthesizes these stubs.
2528 OpFlags = X86II::MO_DARWIN_STUB;
2531 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2535 // Returns a chain & a flag for retval copy to use.
2536 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2537 SmallVector<SDValue, 8> Ops;
2539 if (!IsSibcall && isTailCall) {
2540 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2541 DAG.getIntPtrConstant(0, true), InFlag);
2542 InFlag = Chain.getValue(1);
2545 Ops.push_back(Chain);
2546 Ops.push_back(Callee);
2549 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2551 // Add argument registers to the end of the list so that they are known live
2553 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2554 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2555 RegsToPass[i].second.getValueType()));
2557 // Add a register mask operand representing the call-preserved registers.
2558 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2559 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2560 assert(Mask && "Missing call preserved mask for calling convention");
2561 Ops.push_back(DAG.getRegisterMask(Mask));
2563 if (InFlag.getNode())
2564 Ops.push_back(InFlag);
2568 //// If this is the first return lowered for this function, add the regs
2569 //// to the liveout set for the function.
2570 // This isn't right, although it's probably harmless on x86; liveouts
2571 // should be computed from returns not tail calls. Consider a void
2572 // function making a tail call to a function returning int.
2573 return DAG.getNode(X86ISD::TC_RETURN, dl,
2574 NodeTys, &Ops[0], Ops.size());
2577 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2578 InFlag = Chain.getValue(1);
2580 // Create the CALLSEQ_END node.
2581 unsigned NumBytesForCalleeToPush;
2582 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2583 getTargetMachine().Options.GuaranteedTailCallOpt))
2584 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2585 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2586 SR == StackStructReturn)
2587 // If this is a call to a struct-return function, the callee
2588 // pops the hidden struct pointer, so we have to push it back.
2589 // This is common for Darwin/X86, Linux & Mingw32 targets.
2590 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2591 NumBytesForCalleeToPush = 4;
2593 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2595 // Returns a flag for retval copy to use.
2597 Chain = DAG.getCALLSEQ_END(Chain,
2598 DAG.getIntPtrConstant(NumBytes, true),
2599 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2602 InFlag = Chain.getValue(1);
2605 // Handle result values, copying them out of physregs into vregs that we
2607 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2608 Ins, dl, DAG, InVals);
2612 //===----------------------------------------------------------------------===//
2613 // Fast Calling Convention (tail call) implementation
2614 //===----------------------------------------------------------------------===//
2616 // Like std call, callee cleans arguments, convention except that ECX is
2617 // reserved for storing the tail called function address. Only 2 registers are
2618 // free for argument passing (inreg). Tail call optimization is performed
2620 // * tailcallopt is enabled
2621 // * caller/callee are fastcc
2622 // On X86_64 architecture with GOT-style position independent code only local
2623 // (within module) calls are supported at the moment.
2624 // To keep the stack aligned according to platform abi the function
2625 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2626 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2627 // If a tail called function callee has more arguments than the caller the
2628 // caller needs to make sure that there is room to move the RETADDR to. This is
2629 // achieved by reserving an area the size of the argument delta right after the
2630 // original REtADDR, but before the saved framepointer or the spilled registers
2631 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2643 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2644 /// for a 16 byte align requirement.
2646 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2647 SelectionDAG& DAG) const {
2648 MachineFunction &MF = DAG.getMachineFunction();
2649 const TargetMachine &TM = MF.getTarget();
2650 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2651 unsigned StackAlignment = TFI.getStackAlignment();
2652 uint64_t AlignMask = StackAlignment - 1;
2653 int64_t Offset = StackSize;
2654 uint64_t SlotSize = TD->getPointerSize();
2655 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2656 // Number smaller than 12 so just add the difference.
2657 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2659 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2660 Offset = ((~AlignMask) & Offset) + StackAlignment +
2661 (StackAlignment-SlotSize);
2666 /// MatchingStackOffset - Return true if the given stack call argument is
2667 /// already available in the same position (relatively) of the caller's
2668 /// incoming argument stack.
2670 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2671 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2672 const X86InstrInfo *TII) {
2673 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2675 if (Arg.getOpcode() == ISD::CopyFromReg) {
2676 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2677 if (!TargetRegisterInfo::isVirtualRegister(VR))
2679 MachineInstr *Def = MRI->getVRegDef(VR);
2682 if (!Flags.isByVal()) {
2683 if (!TII->isLoadFromStackSlot(Def, FI))
2686 unsigned Opcode = Def->getOpcode();
2687 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2688 Def->getOperand(1).isFI()) {
2689 FI = Def->getOperand(1).getIndex();
2690 Bytes = Flags.getByValSize();
2694 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2695 if (Flags.isByVal())
2696 // ByVal argument is passed in as a pointer but it's now being
2697 // dereferenced. e.g.
2698 // define @foo(%struct.X* %A) {
2699 // tail call @bar(%struct.X* byval %A)
2702 SDValue Ptr = Ld->getBasePtr();
2703 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2706 FI = FINode->getIndex();
2707 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2708 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2709 FI = FINode->getIndex();
2710 Bytes = Flags.getByValSize();
2714 assert(FI != INT_MAX);
2715 if (!MFI->isFixedObjectIndex(FI))
2717 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2720 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2721 /// for tail call optimization. Targets which want to do tail call
2722 /// optimization should implement this function.
2724 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2725 CallingConv::ID CalleeCC,
2727 bool isCalleeStructRet,
2728 bool isCallerStructRet,
2730 const SmallVectorImpl<ISD::OutputArg> &Outs,
2731 const SmallVectorImpl<SDValue> &OutVals,
2732 const SmallVectorImpl<ISD::InputArg> &Ins,
2733 SelectionDAG& DAG) const {
2734 if (!IsTailCallConvention(CalleeCC) &&
2735 CalleeCC != CallingConv::C)
2738 // If -tailcallopt is specified, make fastcc functions tail-callable.
2739 const MachineFunction &MF = DAG.getMachineFunction();
2740 const Function *CallerF = DAG.getMachineFunction().getFunction();
2742 // If the function return type is x86_fp80 and the callee return type is not,
2743 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2744 // perform a tailcall optimization here.
2745 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2748 CallingConv::ID CallerCC = CallerF->getCallingConv();
2749 bool CCMatch = CallerCC == CalleeCC;
2751 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2752 if (IsTailCallConvention(CalleeCC) && CCMatch)
2757 // Look for obvious safe cases to perform tail call optimization that do not
2758 // require ABI changes. This is what gcc calls sibcall.
2760 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2761 // emit a special epilogue.
2762 if (RegInfo->needsStackRealignment(MF))
2765 // Also avoid sibcall optimization if either caller or callee uses struct
2766 // return semantics.
2767 if (isCalleeStructRet || isCallerStructRet)
2770 // An stdcall caller is expected to clean up its arguments; the callee
2771 // isn't going to do that.
2772 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2775 // Do not sibcall optimize vararg calls unless all arguments are passed via
2777 if (isVarArg && !Outs.empty()) {
2779 // Optimizing for varargs on Win64 is unlikely to be safe without
2780 // additional testing.
2781 if (Subtarget->isTargetWin64())
2784 SmallVector<CCValAssign, 16> ArgLocs;
2785 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2786 getTargetMachine(), ArgLocs, *DAG.getContext());
2788 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2789 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2790 if (!ArgLocs[i].isRegLoc())
2794 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2795 // stack. Therefore, if it's not used by the call it is not safe to optimize
2796 // this into a sibcall.
2797 bool Unused = false;
2798 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2805 SmallVector<CCValAssign, 16> RVLocs;
2806 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2807 getTargetMachine(), RVLocs, *DAG.getContext());
2808 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2809 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2810 CCValAssign &VA = RVLocs[i];
2811 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2816 // If the calling conventions do not match, then we'd better make sure the
2817 // results are returned in the same way as what the caller expects.
2819 SmallVector<CCValAssign, 16> RVLocs1;
2820 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2821 getTargetMachine(), RVLocs1, *DAG.getContext());
2822 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2824 SmallVector<CCValAssign, 16> RVLocs2;
2825 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2826 getTargetMachine(), RVLocs2, *DAG.getContext());
2827 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2829 if (RVLocs1.size() != RVLocs2.size())
2831 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2832 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2834 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2836 if (RVLocs1[i].isRegLoc()) {
2837 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2840 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2846 // If the callee takes no arguments then go on to check the results of the
2848 if (!Outs.empty()) {
2849 // Check if stack adjustment is needed. For now, do not do this if any
2850 // argument is passed on the stack.
2851 SmallVector<CCValAssign, 16> ArgLocs;
2852 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2853 getTargetMachine(), ArgLocs, *DAG.getContext());
2855 // Allocate shadow area for Win64
2856 if (Subtarget->isTargetWin64()) {
2857 CCInfo.AllocateStack(32, 8);
2860 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2861 if (CCInfo.getNextStackOffset()) {
2862 MachineFunction &MF = DAG.getMachineFunction();
2863 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2866 // Check if the arguments are already laid out in the right way as
2867 // the caller's fixed stack objects.
2868 MachineFrameInfo *MFI = MF.getFrameInfo();
2869 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2870 const X86InstrInfo *TII =
2871 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2872 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2873 CCValAssign &VA = ArgLocs[i];
2874 SDValue Arg = OutVals[i];
2875 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2876 if (VA.getLocInfo() == CCValAssign::Indirect)
2878 if (!VA.isRegLoc()) {
2879 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2886 // If the tailcall address may be in a register, then make sure it's
2887 // possible to register allocate for it. In 32-bit, the call address can
2888 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2889 // callee-saved registers are restored. These happen to be the same
2890 // registers used to pass 'inreg' arguments so watch out for those.
2891 if (!Subtarget->is64Bit() &&
2892 !isa<GlobalAddressSDNode>(Callee) &&
2893 !isa<ExternalSymbolSDNode>(Callee)) {
2894 unsigned NumInRegs = 0;
2895 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2896 CCValAssign &VA = ArgLocs[i];
2899 unsigned Reg = VA.getLocReg();
2902 case X86::EAX: case X86::EDX: case X86::ECX:
2903 if (++NumInRegs == 3)
2915 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2916 const TargetLibraryInfo *libInfo) const {
2917 return X86::createFastISel(funcInfo, libInfo);
2921 //===----------------------------------------------------------------------===//
2922 // Other Lowering Hooks
2923 //===----------------------------------------------------------------------===//
2925 static bool MayFoldLoad(SDValue Op) {
2926 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2929 static bool MayFoldIntoStore(SDValue Op) {
2930 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2933 static bool isTargetShuffle(unsigned Opcode) {
2935 default: return false;
2936 case X86ISD::PSHUFD:
2937 case X86ISD::PSHUFHW:
2938 case X86ISD::PSHUFLW:
2940 case X86ISD::PALIGN:
2941 case X86ISD::MOVLHPS:
2942 case X86ISD::MOVLHPD:
2943 case X86ISD::MOVHLPS:
2944 case X86ISD::MOVLPS:
2945 case X86ISD::MOVLPD:
2946 case X86ISD::MOVSHDUP:
2947 case X86ISD::MOVSLDUP:
2948 case X86ISD::MOVDDUP:
2951 case X86ISD::UNPCKL:
2952 case X86ISD::UNPCKH:
2953 case X86ISD::VPERMILP:
2954 case X86ISD::VPERM2X128:
2955 case X86ISD::VPERMI:
2960 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2961 SDValue V1, SelectionDAG &DAG) {
2963 default: llvm_unreachable("Unknown x86 shuffle node");
2964 case X86ISD::MOVSHDUP:
2965 case X86ISD::MOVSLDUP:
2966 case X86ISD::MOVDDUP:
2967 return DAG.getNode(Opc, dl, VT, V1);
2971 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2972 SDValue V1, unsigned TargetMask,
2973 SelectionDAG &DAG) {
2975 default: llvm_unreachable("Unknown x86 shuffle node");
2976 case X86ISD::PSHUFD:
2977 case X86ISD::PSHUFHW:
2978 case X86ISD::PSHUFLW:
2979 case X86ISD::VPERMILP:
2980 case X86ISD::VPERMI:
2981 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2985 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2986 SDValue V1, SDValue V2, unsigned TargetMask,
2987 SelectionDAG &DAG) {
2989 default: llvm_unreachable("Unknown x86 shuffle node");
2990 case X86ISD::PALIGN:
2992 case X86ISD::VPERM2X128:
2993 return DAG.getNode(Opc, dl, VT, V1, V2,
2994 DAG.getConstant(TargetMask, MVT::i8));
2998 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2999 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3001 default: llvm_unreachable("Unknown x86 shuffle node");
3002 case X86ISD::MOVLHPS:
3003 case X86ISD::MOVLHPD:
3004 case X86ISD::MOVHLPS:
3005 case X86ISD::MOVLPS:
3006 case X86ISD::MOVLPD:
3009 case X86ISD::UNPCKL:
3010 case X86ISD::UNPCKH:
3011 return DAG.getNode(Opc, dl, VT, V1, V2);
3015 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3016 MachineFunction &MF = DAG.getMachineFunction();
3017 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3018 int ReturnAddrIndex = FuncInfo->getRAIndex();
3020 if (ReturnAddrIndex == 0) {
3021 // Set up a frame object for the return address.
3022 uint64_t SlotSize = TD->getPointerSize();
3023 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3025 FuncInfo->setRAIndex(ReturnAddrIndex);
3028 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3032 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3033 bool hasSymbolicDisplacement) {
3034 // Offset should fit into 32 bit immediate field.
3035 if (!isInt<32>(Offset))
3038 // If we don't have a symbolic displacement - we don't have any extra
3040 if (!hasSymbolicDisplacement)
3043 // FIXME: Some tweaks might be needed for medium code model.
3044 if (M != CodeModel::Small && M != CodeModel::Kernel)
3047 // For small code model we assume that latest object is 16MB before end of 31
3048 // bits boundary. We may also accept pretty large negative constants knowing
3049 // that all objects are in the positive half of address space.
3050 if (M == CodeModel::Small && Offset < 16*1024*1024)
3053 // For kernel code model we know that all object resist in the negative half
3054 // of 32bits address space. We may not accept negative offsets, since they may
3055 // be just off and we may accept pretty large positive ones.
3056 if (M == CodeModel::Kernel && Offset > 0)
3062 /// isCalleePop - Determines whether the callee is required to pop its
3063 /// own arguments. Callee pop is necessary to support tail calls.
3064 bool X86::isCalleePop(CallingConv::ID CallingConv,
3065 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3069 switch (CallingConv) {
3072 case CallingConv::X86_StdCall:
3074 case CallingConv::X86_FastCall:
3076 case CallingConv::X86_ThisCall:
3078 case CallingConv::Fast:
3080 case CallingConv::GHC:
3085 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3086 /// specific condition code, returning the condition code and the LHS/RHS of the
3087 /// comparison to make.
3088 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3089 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3091 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3092 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3093 // X > -1 -> X == 0, jump !sign.
3094 RHS = DAG.getConstant(0, RHS.getValueType());
3095 return X86::COND_NS;
3097 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3098 // X < 0 -> X == 0, jump on sign.
3101 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3103 RHS = DAG.getConstant(0, RHS.getValueType());
3104 return X86::COND_LE;
3108 switch (SetCCOpcode) {
3109 default: llvm_unreachable("Invalid integer condition!");
3110 case ISD::SETEQ: return X86::COND_E;
3111 case ISD::SETGT: return X86::COND_G;
3112 case ISD::SETGE: return X86::COND_GE;
3113 case ISD::SETLT: return X86::COND_L;
3114 case ISD::SETLE: return X86::COND_LE;
3115 case ISD::SETNE: return X86::COND_NE;
3116 case ISD::SETULT: return X86::COND_B;
3117 case ISD::SETUGT: return X86::COND_A;
3118 case ISD::SETULE: return X86::COND_BE;
3119 case ISD::SETUGE: return X86::COND_AE;
3123 // First determine if it is required or is profitable to flip the operands.
3125 // If LHS is a foldable load, but RHS is not, flip the condition.
3126 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3127 !ISD::isNON_EXTLoad(RHS.getNode())) {
3128 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3129 std::swap(LHS, RHS);
3132 switch (SetCCOpcode) {
3138 std::swap(LHS, RHS);
3142 // On a floating point condition, the flags are set as follows:
3144 // 0 | 0 | 0 | X > Y
3145 // 0 | 0 | 1 | X < Y
3146 // 1 | 0 | 0 | X == Y
3147 // 1 | 1 | 1 | unordered
3148 switch (SetCCOpcode) {
3149 default: llvm_unreachable("Condcode should be pre-legalized away");
3151 case ISD::SETEQ: return X86::COND_E;
3152 case ISD::SETOLT: // flipped
3154 case ISD::SETGT: return X86::COND_A;
3155 case ISD::SETOLE: // flipped
3157 case ISD::SETGE: return X86::COND_AE;
3158 case ISD::SETUGT: // flipped
3160 case ISD::SETLT: return X86::COND_B;
3161 case ISD::SETUGE: // flipped
3163 case ISD::SETLE: return X86::COND_BE;
3165 case ISD::SETNE: return X86::COND_NE;
3166 case ISD::SETUO: return X86::COND_P;
3167 case ISD::SETO: return X86::COND_NP;
3169 case ISD::SETUNE: return X86::COND_INVALID;
3173 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3174 /// code. Current x86 isa includes the following FP cmov instructions:
3175 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3176 static bool hasFPCMov(unsigned X86CC) {
3192 /// isFPImmLegal - Returns true if the target can instruction select the
3193 /// specified FP immediate natively. If false, the legalizer will
3194 /// materialize the FP immediate as a load from a constant pool.
3195 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3196 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3197 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3203 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3204 /// the specified range (L, H].
3205 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3206 return (Val < 0) || (Val >= Low && Val < Hi);
3209 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3210 /// specified value.
3211 static bool isUndefOrEqual(int Val, int CmpVal) {
3212 if (Val < 0 || Val == CmpVal)
3217 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3218 /// from position Pos and ending in Pos+Size, falls within the specified
3219 /// sequential range (L, L+Pos]. or is undef.
3220 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3221 unsigned Pos, unsigned Size, int Low) {
3222 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3223 if (!isUndefOrEqual(Mask[i], Low))
3228 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3229 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3230 /// the second operand.
3231 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3232 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3233 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3234 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3235 return (Mask[0] < 2 && Mask[1] < 2);
3239 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3240 /// is suitable for input to PSHUFHW.
3241 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3242 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3245 // Lower quadword copied in order or undef.
3246 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3249 // Upper quadword shuffled.
3250 for (unsigned i = 4; i != 8; ++i)
3251 if (!isUndefOrInRange(Mask[i], 4, 8))
3254 if (VT == MVT::v16i16) {
3255 // Lower quadword copied in order or undef.
3256 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3259 // Upper quadword shuffled.
3260 for (unsigned i = 12; i != 16; ++i)
3261 if (!isUndefOrInRange(Mask[i], 12, 16))
3268 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3269 /// is suitable for input to PSHUFLW.
3270 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3271 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3274 // Upper quadword copied in order.
3275 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3278 // Lower quadword shuffled.
3279 for (unsigned i = 0; i != 4; ++i)
3280 if (!isUndefOrInRange(Mask[i], 0, 4))
3283 if (VT == MVT::v16i16) {
3284 // Upper quadword copied in order.
3285 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3288 // Lower quadword shuffled.
3289 for (unsigned i = 8; i != 12; ++i)
3290 if (!isUndefOrInRange(Mask[i], 8, 12))
3297 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3298 /// is suitable for input to PALIGNR.
3299 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3300 const X86Subtarget *Subtarget) {
3301 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3302 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3305 unsigned NumElts = VT.getVectorNumElements();
3306 unsigned NumLanes = VT.getSizeInBits()/128;
3307 unsigned NumLaneElts = NumElts/NumLanes;
3309 // Do not handle 64-bit element shuffles with palignr.
3310 if (NumLaneElts == 2)
3313 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3315 for (i = 0; i != NumLaneElts; ++i) {
3320 // Lane is all undef, go to next lane
3321 if (i == NumLaneElts)
3324 int Start = Mask[i+l];
3326 // Make sure its in this lane in one of the sources
3327 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3328 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3331 // If not lane 0, then we must match lane 0
3332 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3335 // Correct second source to be contiguous with first source
3336 if (Start >= (int)NumElts)
3337 Start -= NumElts - NumLaneElts;
3339 // Make sure we're shifting in the right direction.
3340 if (Start <= (int)(i+l))
3345 // Check the rest of the elements to see if they are consecutive.
3346 for (++i; i != NumLaneElts; ++i) {
3347 int Idx = Mask[i+l];
3349 // Make sure its in this lane
3350 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3351 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3354 // If not lane 0, then we must match lane 0
3355 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3358 if (Idx >= (int)NumElts)
3359 Idx -= NumElts - NumLaneElts;
3361 if (!isUndefOrEqual(Idx, Start+i))
3370 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3371 /// the two vector operands have swapped position.
3372 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3373 unsigned NumElems) {
3374 for (unsigned i = 0; i != NumElems; ++i) {
3378 else if (idx < (int)NumElems)
3379 Mask[i] = idx + NumElems;
3381 Mask[i] = idx - NumElems;
3385 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3386 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3387 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3388 /// reverse of what x86 shuffles want.
3389 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3390 bool Commuted = false) {
3391 if (!HasAVX && VT.getSizeInBits() == 256)
3394 unsigned NumElems = VT.getVectorNumElements();
3395 unsigned NumLanes = VT.getSizeInBits()/128;
3396 unsigned NumLaneElems = NumElems/NumLanes;
3398 if (NumLaneElems != 2 && NumLaneElems != 4)
3401 // VSHUFPSY divides the resulting vector into 4 chunks.
3402 // The sources are also splitted into 4 chunks, and each destination
3403 // chunk must come from a different source chunk.
3405 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3406 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3408 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3409 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3411 // VSHUFPDY divides the resulting vector into 4 chunks.
3412 // The sources are also splitted into 4 chunks, and each destination
3413 // chunk must come from a different source chunk.
3415 // SRC1 => X3 X2 X1 X0
3416 // SRC2 => Y3 Y2 Y1 Y0
3418 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3420 unsigned HalfLaneElems = NumLaneElems/2;
3421 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3422 for (unsigned i = 0; i != NumLaneElems; ++i) {
3423 int Idx = Mask[i+l];
3424 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3425 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3427 // For VSHUFPSY, the mask of the second half must be the same as the
3428 // first but with the appropriate offsets. This works in the same way as
3429 // VPERMILPS works with masks.
3430 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3432 if (!isUndefOrEqual(Idx, Mask[i]+l))
3440 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3441 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3442 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3443 if (!VT.is128BitVector())
3446 unsigned NumElems = VT.getVectorNumElements();
3451 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3452 return isUndefOrEqual(Mask[0], 6) &&
3453 isUndefOrEqual(Mask[1], 7) &&
3454 isUndefOrEqual(Mask[2], 2) &&
3455 isUndefOrEqual(Mask[3], 3);
3458 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3459 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3461 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3462 if (!VT.is128BitVector())
3465 unsigned NumElems = VT.getVectorNumElements();
3470 return isUndefOrEqual(Mask[0], 2) &&
3471 isUndefOrEqual(Mask[1], 3) &&
3472 isUndefOrEqual(Mask[2], 2) &&
3473 isUndefOrEqual(Mask[3], 3);
3476 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3477 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3478 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3479 if (!VT.is128BitVector())
3482 unsigned NumElems = VT.getVectorNumElements();
3484 if (NumElems != 2 && NumElems != 4)
3487 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3488 if (!isUndefOrEqual(Mask[i], i + NumElems))
3491 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3492 if (!isUndefOrEqual(Mask[i], i))
3498 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3499 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3500 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3501 if (!VT.is128BitVector())
3504 unsigned NumElems = VT.getVectorNumElements();
3506 if (NumElems != 2 && NumElems != 4)
3509 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3510 if (!isUndefOrEqual(Mask[i], i))
3513 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3514 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3521 // Some special combinations that can be optimized.
3524 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3525 SelectionDAG &DAG) {
3526 EVT VT = SVOp->getValueType(0);
3527 DebugLoc dl = SVOp->getDebugLoc();
3529 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3532 ArrayRef<int> Mask = SVOp->getMask();
3534 // These are the special masks that may be optimized.
3535 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3536 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3537 bool MatchEvenMask = true;
3538 bool MatchOddMask = true;
3539 for (int i=0; i<8; ++i) {
3540 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3541 MatchEvenMask = false;
3542 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3543 MatchOddMask = false;
3546 if (!MatchEvenMask && !MatchOddMask)
3549 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3551 SDValue Op0 = SVOp->getOperand(0);
3552 SDValue Op1 = SVOp->getOperand(1);
3554 if (MatchEvenMask) {
3555 // Shift the second operand right to 32 bits.
3556 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3557 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3559 // Shift the first operand left to 32 bits.
3560 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3561 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3563 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3564 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3567 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3568 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3569 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3570 bool HasAVX2, bool V2IsSplat = false) {
3571 unsigned NumElts = VT.getVectorNumElements();
3573 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3574 "Unsupported vector type for unpckh");
3576 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3577 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3580 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3581 // independently on 128-bit lanes.
3582 unsigned NumLanes = VT.getSizeInBits()/128;
3583 unsigned NumLaneElts = NumElts/NumLanes;
3585 for (unsigned l = 0; l != NumLanes; ++l) {
3586 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3587 i != (l+1)*NumLaneElts;
3590 int BitI1 = Mask[i+1];
3591 if (!isUndefOrEqual(BitI, j))
3594 if (!isUndefOrEqual(BitI1, NumElts))
3597 if (!isUndefOrEqual(BitI1, j + NumElts))
3606 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3607 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3608 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3609 bool HasAVX2, bool V2IsSplat = false) {
3610 unsigned NumElts = VT.getVectorNumElements();
3612 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3613 "Unsupported vector type for unpckh");
3615 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3616 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3619 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3620 // independently on 128-bit lanes.
3621 unsigned NumLanes = VT.getSizeInBits()/128;
3622 unsigned NumLaneElts = NumElts/NumLanes;
3624 for (unsigned l = 0; l != NumLanes; ++l) {
3625 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3626 i != (l+1)*NumLaneElts; i += 2, ++j) {
3628 int BitI1 = Mask[i+1];
3629 if (!isUndefOrEqual(BitI, j))
3632 if (isUndefOrEqual(BitI1, NumElts))
3635 if (!isUndefOrEqual(BitI1, j+NumElts))
3643 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3644 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3646 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3648 unsigned NumElts = VT.getVectorNumElements();
3650 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3651 "Unsupported vector type for unpckh");
3653 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3654 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3657 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3658 // FIXME: Need a better way to get rid of this, there's no latency difference
3659 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3660 // the former later. We should also remove the "_undef" special mask.
3661 if (NumElts == 4 && VT.getSizeInBits() == 256)
3664 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3665 // independently on 128-bit lanes.
3666 unsigned NumLanes = VT.getSizeInBits()/128;
3667 unsigned NumLaneElts = NumElts/NumLanes;
3669 for (unsigned l = 0; l != NumLanes; ++l) {
3670 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3671 i != (l+1)*NumLaneElts;
3674 int BitI1 = Mask[i+1];
3676 if (!isUndefOrEqual(BitI, j))
3678 if (!isUndefOrEqual(BitI1, j))
3686 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3687 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3689 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3690 unsigned NumElts = VT.getVectorNumElements();
3692 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3693 "Unsupported vector type for unpckh");
3695 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3696 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3699 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3700 // independently on 128-bit lanes.
3701 unsigned NumLanes = VT.getSizeInBits()/128;
3702 unsigned NumLaneElts = NumElts/NumLanes;
3704 for (unsigned l = 0; l != NumLanes; ++l) {
3705 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3706 i != (l+1)*NumLaneElts; i += 2, ++j) {
3708 int BitI1 = Mask[i+1];
3709 if (!isUndefOrEqual(BitI, j))
3711 if (!isUndefOrEqual(BitI1, j))
3718 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3719 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3720 /// MOVSD, and MOVD, i.e. setting the lowest element.
3721 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3722 if (VT.getVectorElementType().getSizeInBits() < 32)
3724 if (!VT.is128BitVector())
3727 unsigned NumElts = VT.getVectorNumElements();
3729 if (!isUndefOrEqual(Mask[0], NumElts))
3732 for (unsigned i = 1; i != NumElts; ++i)
3733 if (!isUndefOrEqual(Mask[i], i))
3739 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3740 /// as permutations between 128-bit chunks or halves. As an example: this
3742 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3743 /// The first half comes from the second half of V1 and the second half from the
3744 /// the second half of V2.
3745 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3746 if (!HasAVX || !VT.is256BitVector())
3749 // The shuffle result is divided into half A and half B. In total the two
3750 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3751 // B must come from C, D, E or F.
3752 unsigned HalfSize = VT.getVectorNumElements()/2;
3753 bool MatchA = false, MatchB = false;
3755 // Check if A comes from one of C, D, E, F.
3756 for (unsigned Half = 0; Half != 4; ++Half) {
3757 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3763 // Check if B comes from one of C, D, E, F.
3764 for (unsigned Half = 0; Half != 4; ++Half) {
3765 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3771 return MatchA && MatchB;
3774 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3775 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3776 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3777 EVT VT = SVOp->getValueType(0);
3779 unsigned HalfSize = VT.getVectorNumElements()/2;
3781 unsigned FstHalf = 0, SndHalf = 0;
3782 for (unsigned i = 0; i < HalfSize; ++i) {
3783 if (SVOp->getMaskElt(i) > 0) {
3784 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3788 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3789 if (SVOp->getMaskElt(i) > 0) {
3790 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3795 return (FstHalf | (SndHalf << 4));
3798 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3799 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3800 /// Note that VPERMIL mask matching is different depending whether theunderlying
3801 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3802 /// to the same elements of the low, but to the higher half of the source.
3803 /// In VPERMILPD the two lanes could be shuffled independently of each other
3804 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3805 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3809 unsigned NumElts = VT.getVectorNumElements();
3810 // Only match 256-bit with 32/64-bit types
3811 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3814 unsigned NumLanes = VT.getSizeInBits()/128;
3815 unsigned LaneSize = NumElts/NumLanes;
3816 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3817 for (unsigned i = 0; i != LaneSize; ++i) {
3818 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3820 if (NumElts != 8 || l == 0)
3822 // VPERMILPS handling
3825 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3833 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3834 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3835 /// element of vector 2 and the other elements to come from vector 1 in order.
3836 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3837 bool V2IsSplat = false, bool V2IsUndef = false) {
3838 if (!VT.is128BitVector())
3841 unsigned NumOps = VT.getVectorNumElements();
3842 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3845 if (!isUndefOrEqual(Mask[0], 0))
3848 for (unsigned i = 1; i != NumOps; ++i)
3849 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3850 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3851 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3857 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3858 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3859 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3860 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3861 const X86Subtarget *Subtarget) {
3862 if (!Subtarget->hasSSE3())
3865 unsigned NumElems = VT.getVectorNumElements();
3867 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3868 (VT.getSizeInBits() == 256 && NumElems != 8))
3871 // "i+1" is the value the indexed mask element must have
3872 for (unsigned i = 0; i != NumElems; i += 2)
3873 if (!isUndefOrEqual(Mask[i], i+1) ||
3874 !isUndefOrEqual(Mask[i+1], i+1))
3880 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3881 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3882 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3883 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3884 const X86Subtarget *Subtarget) {
3885 if (!Subtarget->hasSSE3())
3888 unsigned NumElems = VT.getVectorNumElements();
3890 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3891 (VT.getSizeInBits() == 256 && NumElems != 8))
3894 // "i" is the value the indexed mask element must have
3895 for (unsigned i = 0; i != NumElems; i += 2)
3896 if (!isUndefOrEqual(Mask[i], i) ||
3897 !isUndefOrEqual(Mask[i+1], i))
3903 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to 256-bit
3905 /// version of MOVDDUP.
3906 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3907 if (!HasAVX || !VT.is256BitVector())
3910 unsigned NumElts = VT.getVectorNumElements();
3914 for (unsigned i = 0; i != NumElts/2; ++i)
3915 if (!isUndefOrEqual(Mask[i], 0))
3917 for (unsigned i = NumElts/2; i != NumElts; ++i)
3918 if (!isUndefOrEqual(Mask[i], NumElts/2))
3923 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to 128-bit
3925 /// version of MOVDDUP.
3926 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3927 if (!VT.is128BitVector())
3930 unsigned e = VT.getVectorNumElements() / 2;
3931 for (unsigned i = 0; i != e; ++i)
3932 if (!isUndefOrEqual(Mask[i], i))
3934 for (unsigned i = 0; i != e; ++i)
3935 if (!isUndefOrEqual(Mask[e+i], i))
3940 /// isVEXTRACTF128Index - Return true if the specified
3941 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3942 /// suitable for input to VEXTRACTF128.
3943 bool X86::isVEXTRACTF128Index(SDNode *N) {
3944 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3947 // The index should be aligned on a 128-bit boundary.
3949 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3951 unsigned VL = N->getValueType(0).getVectorNumElements();
3952 unsigned VBits = N->getValueType(0).getSizeInBits();
3953 unsigned ElSize = VBits / VL;
3954 bool Result = (Index * ElSize) % 128 == 0;
3959 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3960 /// operand specifies a subvector insert that is suitable for input to
3962 bool X86::isVINSERTF128Index(SDNode *N) {
3963 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3966 // The index should be aligned on a 128-bit boundary.
3968 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3970 unsigned VL = N->getValueType(0).getVectorNumElements();
3971 unsigned VBits = N->getValueType(0).getSizeInBits();
3972 unsigned ElSize = VBits / VL;
3973 bool Result = (Index * ElSize) % 128 == 0;
3978 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3979 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3980 /// Handles 128-bit and 256-bit.
3981 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3982 EVT VT = N->getValueType(0);
3984 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3985 "Unsupported vector type for PSHUF/SHUFP");
3987 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3988 // independently on 128-bit lanes.
3989 unsigned NumElts = VT.getVectorNumElements();
3990 unsigned NumLanes = VT.getSizeInBits()/128;
3991 unsigned NumLaneElts = NumElts/NumLanes;
3993 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3994 "Only supports 2 or 4 elements per lane");
3996 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3998 for (unsigned i = 0; i != NumElts; ++i) {
3999 int Elt = N->getMaskElt(i);
4000 if (Elt < 0) continue;
4001 Elt &= NumLaneElts - 1;
4002 unsigned ShAmt = (i << Shift) % 8;
4003 Mask |= Elt << ShAmt;
4009 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4010 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4011 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4012 EVT VT = N->getValueType(0);
4014 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4015 "Unsupported vector type for PSHUFHW");
4017 unsigned NumElts = VT.getVectorNumElements();
4020 for (unsigned l = 0; l != NumElts; l += 8) {
4021 // 8 nodes per lane, but we only care about the last 4.
4022 for (unsigned i = 0; i < 4; ++i) {
4023 int Elt = N->getMaskElt(l+i+4);
4024 if (Elt < 0) continue;
4025 Elt &= 0x3; // only 2-bits.
4026 Mask |= Elt << (i * 2);
4033 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4034 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4035 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4036 EVT VT = N->getValueType(0);
4038 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4039 "Unsupported vector type for PSHUFHW");
4041 unsigned NumElts = VT.getVectorNumElements();
4044 for (unsigned l = 0; l != NumElts; l += 8) {
4045 // 8 nodes per lane, but we only care about the first 4.
4046 for (unsigned i = 0; i < 4; ++i) {
4047 int Elt = N->getMaskElt(l+i);
4048 if (Elt < 0) continue;
4049 Elt &= 0x3; // only 2-bits
4050 Mask |= Elt << (i * 2);
4057 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4058 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4059 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4060 EVT VT = SVOp->getValueType(0);
4061 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4063 unsigned NumElts = VT.getVectorNumElements();
4064 unsigned NumLanes = VT.getSizeInBits()/128;
4065 unsigned NumLaneElts = NumElts/NumLanes;
4069 for (i = 0; i != NumElts; ++i) {
4070 Val = SVOp->getMaskElt(i);
4074 if (Val >= (int)NumElts)
4075 Val -= NumElts - NumLaneElts;
4077 assert(Val - i > 0 && "PALIGNR imm should be positive");
4078 return (Val - i) * EltSize;
4081 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4082 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4084 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4085 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4086 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4089 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4091 EVT VecVT = N->getOperand(0).getValueType();
4092 EVT ElVT = VecVT.getVectorElementType();
4094 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4095 return Index / NumElemsPerChunk;
4098 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4099 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4101 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4102 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4103 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4106 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4108 EVT VecVT = N->getValueType(0);
4109 EVT ElVT = VecVT.getVectorElementType();
4111 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4112 return Index / NumElemsPerChunk;
4115 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4116 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4117 /// Handles 256-bit.
4118 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4119 EVT VT = N->getValueType(0);
4121 unsigned NumElts = VT.getVectorNumElements();
4123 assert((VT.is256BitVector() && NumElts == 4) &&
4124 "Unsupported vector type for VPERMQ/VPERMPD");
4127 for (unsigned i = 0; i != NumElts; ++i) {
4128 int Elt = N->getMaskElt(i);
4131 Mask |= Elt << (i*2);
4136 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4138 bool X86::isZeroNode(SDValue Elt) {
4139 return ((isa<ConstantSDNode>(Elt) &&
4140 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4141 (isa<ConstantFPSDNode>(Elt) &&
4142 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4145 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4146 /// their permute mask.
4147 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4148 SelectionDAG &DAG) {
4149 EVT VT = SVOp->getValueType(0);
4150 unsigned NumElems = VT.getVectorNumElements();
4151 SmallVector<int, 8> MaskVec;
4153 for (unsigned i = 0; i != NumElems; ++i) {
4154 int Idx = SVOp->getMaskElt(i);
4156 if (Idx < (int)NumElems)
4161 MaskVec.push_back(Idx);
4163 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4164 SVOp->getOperand(0), &MaskVec[0]);
4167 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4168 /// match movhlps. The lower half elements should come from upper half of
4169 /// V1 (and in order), and the upper half elements should come from the upper
4170 /// half of V2 (and in order).
4171 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4172 if (!VT.is128BitVector())
4174 if (VT.getVectorNumElements() != 4)
4176 for (unsigned i = 0, e = 2; i != e; ++i)
4177 if (!isUndefOrEqual(Mask[i], i+2))
4179 for (unsigned i = 2; i != 4; ++i)
4180 if (!isUndefOrEqual(Mask[i], i+4))
4185 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4186 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4188 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4189 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4191 N = N->getOperand(0).getNode();
4192 if (!ISD::isNON_EXTLoad(N))
4195 *LD = cast<LoadSDNode>(N);
4199 // Test whether the given value is a vector value which will be legalized
4201 static bool WillBeConstantPoolLoad(SDNode *N) {
4202 if (N->getOpcode() != ISD::BUILD_VECTOR)
4205 // Check for any non-constant elements.
4206 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4207 switch (N->getOperand(i).getNode()->getOpcode()) {
4209 case ISD::ConstantFP:
4216 // Vectors of all-zeros and all-ones are materialized with special
4217 // instructions rather than being loaded.
4218 return !ISD::isBuildVectorAllZeros(N) &&
4219 !ISD::isBuildVectorAllOnes(N);
4222 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4223 /// match movlp{s|d}. The lower half elements should come from lower half of
4224 /// V1 (and in order), and the upper half elements should come from the upper
4225 /// half of V2 (and in order). And since V1 will become the source of the
4226 /// MOVLP, it must be either a vector load or a scalar load to vector.
4227 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4228 ArrayRef<int> Mask, EVT VT) {
4229 if (!VT.is128BitVector())
4232 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4234 // Is V2 is a vector load, don't do this transformation. We will try to use
4235 // load folding shufps op.
4236 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4239 unsigned NumElems = VT.getVectorNumElements();
4241 if (NumElems != 2 && NumElems != 4)
4243 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4244 if (!isUndefOrEqual(Mask[i], i))
4246 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4247 if (!isUndefOrEqual(Mask[i], i+NumElems))
4252 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4254 static bool isSplatVector(SDNode *N) {
4255 if (N->getOpcode() != ISD::BUILD_VECTOR)
4258 SDValue SplatValue = N->getOperand(0);
4259 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4260 if (N->getOperand(i) != SplatValue)
4265 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4266 /// to an zero vector.
4267 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4268 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4269 SDValue V1 = N->getOperand(0);
4270 SDValue V2 = N->getOperand(1);
4271 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4272 for (unsigned i = 0; i != NumElems; ++i) {
4273 int Idx = N->getMaskElt(i);
4274 if (Idx >= (int)NumElems) {
4275 unsigned Opc = V2.getOpcode();
4276 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4278 if (Opc != ISD::BUILD_VECTOR ||
4279 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4281 } else if (Idx >= 0) {
4282 unsigned Opc = V1.getOpcode();
4283 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4285 if (Opc != ISD::BUILD_VECTOR ||
4286 !X86::isZeroNode(V1.getOperand(Idx)))
4293 /// getZeroVector - Returns a vector of specified type with all zero elements.
4295 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4296 SelectionDAG &DAG, DebugLoc dl) {
4297 assert(VT.isVector() && "Expected a vector type");
4298 unsigned Size = VT.getSizeInBits();
4300 // Always build SSE zero vectors as <4 x i32> bitcasted
4301 // to their dest type. This ensures they get CSE'd.
4303 if (Size == 128) { // SSE
4304 if (Subtarget->hasSSE2()) { // SSE2
4305 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4306 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4308 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4309 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4311 } else if (Size == 256) { // AVX
4312 if (Subtarget->hasAVX2()) { // AVX2
4313 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4314 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4315 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4317 // 256-bit logic and arithmetic instructions in AVX are all
4318 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4319 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4320 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4321 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4324 llvm_unreachable("Unexpected vector type");
4326 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4329 /// getOnesVector - Returns a vector of specified type with all bits set.
4330 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4331 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4332 /// Then bitcast to their original type, ensuring they get CSE'd.
4333 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4335 assert(VT.isVector() && "Expected a vector type");
4336 unsigned Size = VT.getSizeInBits();
4338 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4341 if (HasAVX2) { // AVX2
4342 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4343 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4345 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4346 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4348 } else if (Size == 128) {
4349 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4351 llvm_unreachable("Unexpected vector type");
4353 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4356 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4357 /// that point to V2 points to its first element.
4358 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4359 for (unsigned i = 0; i != NumElems; ++i) {
4360 if (Mask[i] > (int)NumElems) {
4366 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4367 /// operation of specified width.
4368 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4370 unsigned NumElems = VT.getVectorNumElements();
4371 SmallVector<int, 8> Mask;
4372 Mask.push_back(NumElems);
4373 for (unsigned i = 1; i != NumElems; ++i)
4375 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4378 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4379 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4381 unsigned NumElems = VT.getVectorNumElements();
4382 SmallVector<int, 8> Mask;
4383 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4385 Mask.push_back(i + NumElems);
4387 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4390 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4391 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4393 unsigned NumElems = VT.getVectorNumElements();
4394 SmallVector<int, 8> Mask;
4395 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4396 Mask.push_back(i + Half);
4397 Mask.push_back(i + NumElems + Half);
4399 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4402 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4403 // a generic shuffle instruction because the target has no such instructions.
4404 // Generate shuffles which repeat i16 and i8 several times until they can be
4405 // represented by v4f32 and then be manipulated by target suported shuffles.
4406 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4407 EVT VT = V.getValueType();
4408 int NumElems = VT.getVectorNumElements();
4409 DebugLoc dl = V.getDebugLoc();
4411 while (NumElems > 4) {
4412 if (EltNo < NumElems/2) {
4413 V = getUnpackl(DAG, dl, VT, V, V);
4415 V = getUnpackh(DAG, dl, VT, V, V);
4416 EltNo -= NumElems/2;
4423 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4424 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4425 EVT VT = V.getValueType();
4426 DebugLoc dl = V.getDebugLoc();
4427 unsigned Size = VT.getSizeInBits();
4430 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4431 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4432 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4434 } else if (Size == 256) {
4435 // To use VPERMILPS to splat scalars, the second half of indicies must
4436 // refer to the higher part, which is a duplication of the lower one,
4437 // because VPERMILPS can only handle in-lane permutations.
4438 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4439 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4441 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4442 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4445 llvm_unreachable("Vector size not supported");
4447 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4450 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4451 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4452 EVT SrcVT = SV->getValueType(0);
4453 SDValue V1 = SV->getOperand(0);
4454 DebugLoc dl = SV->getDebugLoc();
4456 int EltNo = SV->getSplatIndex();
4457 int NumElems = SrcVT.getVectorNumElements();
4458 unsigned Size = SrcVT.getSizeInBits();
4460 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4461 "Unknown how to promote splat for type");
4463 // Extract the 128-bit part containing the splat element and update
4464 // the splat element index when it refers to the higher register.
4466 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4467 if (EltNo >= NumElems/2)
4468 EltNo -= NumElems/2;
4471 // All i16 and i8 vector types can't be used directly by a generic shuffle
4472 // instruction because the target has no such instruction. Generate shuffles
4473 // which repeat i16 and i8 several times until they fit in i32, and then can
4474 // be manipulated by target suported shuffles.
4475 EVT EltVT = SrcVT.getVectorElementType();
4476 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4477 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4479 // Recreate the 256-bit vector and place the same 128-bit vector
4480 // into the low and high part. This is necessary because we want
4481 // to use VPERM* to shuffle the vectors
4483 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4486 return getLegalSplat(DAG, V1, EltNo);
4489 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4490 /// vector of zero or undef vector. This produces a shuffle where the low
4491 /// element of V2 is swizzled into the zero/undef vector, landing at element
4492 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4493 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4495 const X86Subtarget *Subtarget,
4496 SelectionDAG &DAG) {
4497 EVT VT = V2.getValueType();
4499 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4500 unsigned NumElems = VT.getVectorNumElements();
4501 SmallVector<int, 16> MaskVec;
4502 for (unsigned i = 0; i != NumElems; ++i)
4503 // If this is the insertion idx, put the low elt of V2 here.
4504 MaskVec.push_back(i == Idx ? NumElems : i);
4505 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4508 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4509 /// target specific opcode. Returns true if the Mask could be calculated.
4510 /// Sets IsUnary to true if only uses one source.
4511 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4512 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4513 unsigned NumElems = VT.getVectorNumElements();
4517 switch(N->getOpcode()) {
4519 ImmN = N->getOperand(N->getNumOperands()-1);
4520 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4522 case X86ISD::UNPCKH:
4523 DecodeUNPCKHMask(VT, Mask);
4525 case X86ISD::UNPCKL:
4526 DecodeUNPCKLMask(VT, Mask);
4528 case X86ISD::MOVHLPS:
4529 DecodeMOVHLPSMask(NumElems, Mask);
4531 case X86ISD::MOVLHPS:
4532 DecodeMOVLHPSMask(NumElems, Mask);
4534 case X86ISD::PSHUFD:
4535 case X86ISD::VPERMILP:
4536 ImmN = N->getOperand(N->getNumOperands()-1);
4537 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4540 case X86ISD::PSHUFHW:
4541 ImmN = N->getOperand(N->getNumOperands()-1);
4542 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4545 case X86ISD::PSHUFLW:
4546 ImmN = N->getOperand(N->getNumOperands()-1);
4547 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4550 case X86ISD::VPERMI:
4551 ImmN = N->getOperand(N->getNumOperands()-1);
4552 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4556 case X86ISD::MOVSD: {
4557 // The index 0 always comes from the first element of the second source,
4558 // this is why MOVSS and MOVSD are used in the first place. The other
4559 // elements come from the other positions of the first source vector
4560 Mask.push_back(NumElems);
4561 for (unsigned i = 1; i != NumElems; ++i) {
4566 case X86ISD::VPERM2X128:
4567 ImmN = N->getOperand(N->getNumOperands()-1);
4568 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4569 if (Mask.empty()) return false;
4571 case X86ISD::MOVDDUP:
4572 case X86ISD::MOVLHPD:
4573 case X86ISD::MOVLPD:
4574 case X86ISD::MOVLPS:
4575 case X86ISD::MOVSHDUP:
4576 case X86ISD::MOVSLDUP:
4577 case X86ISD::PALIGN:
4578 // Not yet implemented
4580 default: llvm_unreachable("unknown target shuffle node");
4586 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4587 /// element of the result of the vector shuffle.
4588 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4591 return SDValue(); // Limit search depth.
4593 SDValue V = SDValue(N, 0);
4594 EVT VT = V.getValueType();
4595 unsigned Opcode = V.getOpcode();
4597 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4598 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4599 int Elt = SV->getMaskElt(Index);
4602 return DAG.getUNDEF(VT.getVectorElementType());
4604 unsigned NumElems = VT.getVectorNumElements();
4605 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4606 : SV->getOperand(1);
4607 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4610 // Recurse into target specific vector shuffles to find scalars.
4611 if (isTargetShuffle(Opcode)) {
4612 MVT ShufVT = V.getValueType().getSimpleVT();
4613 unsigned NumElems = ShufVT.getVectorNumElements();
4614 SmallVector<int, 16> ShuffleMask;
4618 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4621 int Elt = ShuffleMask[Index];
4623 return DAG.getUNDEF(ShufVT.getVectorElementType());
4625 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4627 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4631 // Actual nodes that may contain scalar elements
4632 if (Opcode == ISD::BITCAST) {
4633 V = V.getOperand(0);
4634 EVT SrcVT = V.getValueType();
4635 unsigned NumElems = VT.getVectorNumElements();
4637 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4641 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4642 return (Index == 0) ? V.getOperand(0)
4643 : DAG.getUNDEF(VT.getVectorElementType());
4645 if (V.getOpcode() == ISD::BUILD_VECTOR)
4646 return V.getOperand(Index);
4651 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4652 /// shuffle operation which come from a consecutively from a zero. The
4653 /// search can start in two different directions, from left or right.
4655 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4656 bool ZerosFromLeft, SelectionDAG &DAG) {
4658 for (i = 0; i != NumElems; ++i) {
4659 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4660 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4661 if (!(Elt.getNode() &&
4662 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4669 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4670 /// correspond consecutively to elements from one of the vector operands,
4671 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4673 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4674 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4675 unsigned NumElems, unsigned &OpNum) {
4676 bool SeenV1 = false;
4677 bool SeenV2 = false;
4679 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4680 int Idx = SVOp->getMaskElt(i);
4681 // Ignore undef indicies
4685 if (Idx < (int)NumElems)
4690 // Only accept consecutive elements from the same vector
4691 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4695 OpNum = SeenV1 ? 0 : 1;
4699 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4700 /// logical left shift of a vector.
4701 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4702 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4703 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4704 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4705 false /* check zeros from right */, DAG);
4711 // Considering the elements in the mask that are not consecutive zeros,
4712 // check if they consecutively come from only one of the source vectors.
4714 // V1 = {X, A, B, C} 0
4716 // vector_shuffle V1, V2 <1, 2, 3, X>
4718 if (!isShuffleMaskConsecutive(SVOp,
4719 0, // Mask Start Index
4720 NumElems-NumZeros, // Mask End Index(exclusive)
4721 NumZeros, // Where to start looking in the src vector
4722 NumElems, // Number of elements in vector
4723 OpSrc)) // Which source operand ?
4728 ShVal = SVOp->getOperand(OpSrc);
4732 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4733 /// logical left shift of a vector.
4734 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4735 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4736 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4737 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4738 true /* check zeros from left */, DAG);
4744 // Considering the elements in the mask that are not consecutive zeros,
4745 // check if they consecutively come from only one of the source vectors.
4747 // 0 { A, B, X, X } = V2
4749 // vector_shuffle V1, V2 <X, X, 4, 5>
4751 if (!isShuffleMaskConsecutive(SVOp,
4752 NumZeros, // Mask Start Index
4753 NumElems, // Mask End Index(exclusive)
4754 0, // Where to start looking in the src vector
4755 NumElems, // Number of elements in vector
4756 OpSrc)) // Which source operand ?
4761 ShVal = SVOp->getOperand(OpSrc);
4765 /// isVectorShift - Returns true if the shuffle can be implemented as a
4766 /// logical left or right shift of a vector.
4767 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4768 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4769 // Although the logic below support any bitwidth size, there are no
4770 // shift instructions which handle more than 128-bit vectors.
4771 if (!SVOp->getValueType(0).is128BitVector())
4774 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4775 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4781 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4783 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4784 unsigned NumNonZero, unsigned NumZero,
4786 const X86Subtarget* Subtarget,
4787 const TargetLowering &TLI) {
4791 DebugLoc dl = Op.getDebugLoc();
4794 for (unsigned i = 0; i < 16; ++i) {
4795 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4796 if (ThisIsNonZero && First) {
4798 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4800 V = DAG.getUNDEF(MVT::v8i16);
4805 SDValue ThisElt(0, 0), LastElt(0, 0);
4806 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4807 if (LastIsNonZero) {
4808 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4809 MVT::i16, Op.getOperand(i-1));
4811 if (ThisIsNonZero) {
4812 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4813 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4814 ThisElt, DAG.getConstant(8, MVT::i8));
4816 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4820 if (ThisElt.getNode())
4821 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4822 DAG.getIntPtrConstant(i/2));
4826 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4829 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4831 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4832 unsigned NumNonZero, unsigned NumZero,
4834 const X86Subtarget* Subtarget,
4835 const TargetLowering &TLI) {
4839 DebugLoc dl = Op.getDebugLoc();
4842 for (unsigned i = 0; i < 8; ++i) {
4843 bool isNonZero = (NonZeros & (1 << i)) != 0;
4847 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4849 V = DAG.getUNDEF(MVT::v8i16);
4852 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4853 MVT::v8i16, V, Op.getOperand(i),
4854 DAG.getIntPtrConstant(i));
4861 /// getVShift - Return a vector logical shift node.
4863 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4864 unsigned NumBits, SelectionDAG &DAG,
4865 const TargetLowering &TLI, DebugLoc dl) {
4866 assert(VT.is128BitVector() && "Unknown type for VShift");
4867 EVT ShVT = MVT::v2i64;
4868 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4869 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4870 return DAG.getNode(ISD::BITCAST, dl, VT,
4871 DAG.getNode(Opc, dl, ShVT, SrcOp,
4872 DAG.getConstant(NumBits,
4873 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4877 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4878 SelectionDAG &DAG) const {
4880 // Check if the scalar load can be widened into a vector load. And if
4881 // the address is "base + cst" see if the cst can be "absorbed" into
4882 // the shuffle mask.
4883 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4884 SDValue Ptr = LD->getBasePtr();
4885 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4887 EVT PVT = LD->getValueType(0);
4888 if (PVT != MVT::i32 && PVT != MVT::f32)
4893 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4894 FI = FINode->getIndex();
4896 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4897 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4898 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4899 Offset = Ptr.getConstantOperandVal(1);
4900 Ptr = Ptr.getOperand(0);
4905 // FIXME: 256-bit vector instructions don't require a strict alignment,
4906 // improve this code to support it better.
4907 unsigned RequiredAlign = VT.getSizeInBits()/8;
4908 SDValue Chain = LD->getChain();
4909 // Make sure the stack object alignment is at least 16 or 32.
4910 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4911 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4912 if (MFI->isFixedObjectIndex(FI)) {
4913 // Can't change the alignment. FIXME: It's possible to compute
4914 // the exact stack offset and reference FI + adjust offset instead.
4915 // If someone *really* cares about this. That's the way to implement it.
4918 MFI->setObjectAlignment(FI, RequiredAlign);
4922 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4923 // Ptr + (Offset & ~15).
4926 if ((Offset % RequiredAlign) & 3)
4928 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4930 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4931 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4933 int EltNo = (Offset - StartOffset) >> 2;
4934 unsigned NumElems = VT.getVectorNumElements();
4936 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4937 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4938 LD->getPointerInfo().getWithOffset(StartOffset),
4939 false, false, false, 0);
4941 SmallVector<int, 8> Mask;
4942 for (unsigned i = 0; i != NumElems; ++i)
4943 Mask.push_back(EltNo);
4945 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4951 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4952 /// vector of type 'VT', see if the elements can be replaced by a single large
4953 /// load which has the same value as a build_vector whose operands are 'elts'.
4955 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4957 /// FIXME: we'd also like to handle the case where the last elements are zero
4958 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4959 /// There's even a handy isZeroNode for that purpose.
4960 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4961 DebugLoc &DL, SelectionDAG &DAG) {
4962 EVT EltVT = VT.getVectorElementType();
4963 unsigned NumElems = Elts.size();
4965 LoadSDNode *LDBase = NULL;
4966 unsigned LastLoadedElt = -1U;
4968 // For each element in the initializer, see if we've found a load or an undef.
4969 // If we don't find an initial load element, or later load elements are
4970 // non-consecutive, bail out.
4971 for (unsigned i = 0; i < NumElems; ++i) {
4972 SDValue Elt = Elts[i];
4974 if (!Elt.getNode() ||
4975 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4978 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4980 LDBase = cast<LoadSDNode>(Elt.getNode());
4984 if (Elt.getOpcode() == ISD::UNDEF)
4987 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4988 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4993 // If we have found an entire vector of loads and undefs, then return a large
4994 // load of the entire vector width starting at the base pointer. If we found
4995 // consecutive loads for the low half, generate a vzext_load node.
4996 if (LastLoadedElt == NumElems - 1) {
4997 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4998 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4999 LDBase->getPointerInfo(),
5000 LDBase->isVolatile(), LDBase->isNonTemporal(),
5001 LDBase->isInvariant(), 0);
5002 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5003 LDBase->getPointerInfo(),
5004 LDBase->isVolatile(), LDBase->isNonTemporal(),
5005 LDBase->isInvariant(), LDBase->getAlignment());
5007 if (NumElems == 4 && LastLoadedElt == 1 &&
5008 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5009 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5010 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5012 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5013 LDBase->getPointerInfo(),
5014 LDBase->getAlignment(),
5015 false/*isVolatile*/, true/*ReadMem*/,
5018 // Make sure the newly-created LOAD is in the same position as LDBase in
5019 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5020 // update uses of LDBase's output chain to use the TokenFactor.
5021 if (LDBase->hasAnyUseOfValue(1)) {
5022 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5023 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5024 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5025 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5026 SDValue(ResNode.getNode(), 1));
5029 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5034 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5035 /// to generate a splat value for the following cases:
5036 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5037 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5038 /// a scalar load, or a constant.
5039 /// The VBROADCAST node is returned when a pattern is found,
5040 /// or SDValue() otherwise.
5042 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5043 if (!Subtarget->hasAVX())
5046 EVT VT = Op.getValueType();
5047 DebugLoc dl = Op.getDebugLoc();
5049 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5050 "Unsupported vector type for broadcast.");
5055 switch (Op.getOpcode()) {
5057 // Unknown pattern found.
5060 case ISD::BUILD_VECTOR: {
5061 // The BUILD_VECTOR node must be a splat.
5062 if (!isSplatVector(Op.getNode()))
5065 Ld = Op.getOperand(0);
5066 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5067 Ld.getOpcode() == ISD::ConstantFP);
5069 // The suspected load node has several users. Make sure that all
5070 // of its users are from the BUILD_VECTOR node.
5071 // Constants may have multiple users.
5072 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5077 case ISD::VECTOR_SHUFFLE: {
5078 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5080 // Shuffles must have a splat mask where the first element is
5082 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5085 SDValue Sc = Op.getOperand(0);
5086 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5087 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5089 if (!Subtarget->hasAVX2())
5092 // Use the register form of the broadcast instruction available on AVX2.
5093 if (VT.is256BitVector())
5094 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5095 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5098 Ld = Sc.getOperand(0);
5099 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5100 Ld.getOpcode() == ISD::ConstantFP);
5102 // The scalar_to_vector node and the suspected
5103 // load node must have exactly one user.
5104 // Constants may have multiple users.
5105 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5111 bool Is256 = VT.is256BitVector();
5113 // Handle the broadcasting a single constant scalar from the constant pool
5114 // into a vector. On Sandybridge it is still better to load a constant vector
5115 // from the constant pool and not to broadcast it from a scalar.
5116 if (ConstSplatVal && Subtarget->hasAVX2()) {
5117 EVT CVT = Ld.getValueType();
5118 assert(!CVT.isVector() && "Must not broadcast a vector type");
5119 unsigned ScalarSize = CVT.getSizeInBits();
5121 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5122 const Constant *C = 0;
5123 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5124 C = CI->getConstantIntValue();
5125 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5126 C = CF->getConstantFPValue();
5128 assert(C && "Invalid constant type");
5130 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5131 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5132 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5133 MachinePointerInfo::getConstantPool(),
5134 false, false, false, Alignment);
5136 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5140 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5141 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5143 // Handle AVX2 in-register broadcasts.
5144 if (!IsLoad && Subtarget->hasAVX2() &&
5145 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5146 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5148 // The scalar source must be a normal load.
5152 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5153 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5155 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5156 // double since there is no vbroadcastsd xmm
5157 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5158 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5159 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5162 // Unsupported broadcast.
5167 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5168 DebugLoc dl = Op.getDebugLoc();
5170 EVT VT = Op.getValueType();
5171 EVT ExtVT = VT.getVectorElementType();
5172 unsigned NumElems = Op.getNumOperands();
5174 // Vectors containing all zeros can be matched by pxor and xorps later
5175 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5176 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5177 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5178 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5181 return getZeroVector(VT, Subtarget, DAG, dl);
5184 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5185 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5186 // vpcmpeqd on 256-bit vectors.
5187 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5188 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5191 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5194 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5195 if (Broadcast.getNode())
5198 unsigned EVTBits = ExtVT.getSizeInBits();
5200 unsigned NumZero = 0;
5201 unsigned NumNonZero = 0;
5202 unsigned NonZeros = 0;
5203 bool IsAllConstants = true;
5204 SmallSet<SDValue, 8> Values;
5205 for (unsigned i = 0; i < NumElems; ++i) {
5206 SDValue Elt = Op.getOperand(i);
5207 if (Elt.getOpcode() == ISD::UNDEF)
5210 if (Elt.getOpcode() != ISD::Constant &&
5211 Elt.getOpcode() != ISD::ConstantFP)
5212 IsAllConstants = false;
5213 if (X86::isZeroNode(Elt))
5216 NonZeros |= (1 << i);
5221 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5222 if (NumNonZero == 0)
5223 return DAG.getUNDEF(VT);
5225 // Special case for single non-zero, non-undef, element.
5226 if (NumNonZero == 1) {
5227 unsigned Idx = CountTrailingZeros_32(NonZeros);
5228 SDValue Item = Op.getOperand(Idx);
5230 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5231 // the value are obviously zero, truncate the value to i32 and do the
5232 // insertion that way. Only do this if the value is non-constant or if the
5233 // value is a constant being inserted into element 0. It is cheaper to do
5234 // a constant pool load than it is to do a movd + shuffle.
5235 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5236 (!IsAllConstants || Idx == 0)) {
5237 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5239 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5240 EVT VecVT = MVT::v4i32;
5241 unsigned VecElts = 4;
5243 // Truncate the value (which may itself be a constant) to i32, and
5244 // convert it to a vector with movd (S2V+shuffle to zero extend).
5245 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5246 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5247 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5249 // Now we have our 32-bit value zero extended in the low element of
5250 // a vector. If Idx != 0, swizzle it into place.
5252 SmallVector<int, 4> Mask;
5253 Mask.push_back(Idx);
5254 for (unsigned i = 1; i != VecElts; ++i)
5256 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5259 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5263 // If we have a constant or non-constant insertion into the low element of
5264 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5265 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5266 // depending on what the source datatype is.
5269 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5271 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5272 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5273 if (VT.is256BitVector()) {
5274 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5275 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5276 Item, DAG.getIntPtrConstant(0));
5278 assert(VT.is128BitVector() && "Expected an SSE value type!");
5279 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5280 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5281 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5284 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5285 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5286 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5287 if (VT.is256BitVector()) {
5288 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5289 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5291 assert(VT.is128BitVector() && "Expected an SSE value type!");
5292 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5294 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5298 // Is it a vector logical left shift?
5299 if (NumElems == 2 && Idx == 1 &&
5300 X86::isZeroNode(Op.getOperand(0)) &&
5301 !X86::isZeroNode(Op.getOperand(1))) {
5302 unsigned NumBits = VT.getSizeInBits();
5303 return getVShift(true, VT,
5304 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5305 VT, Op.getOperand(1)),
5306 NumBits/2, DAG, *this, dl);
5309 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5312 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5313 // is a non-constant being inserted into an element other than the low one,
5314 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5315 // movd/movss) to move this into the low element, then shuffle it into
5317 if (EVTBits == 32) {
5318 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5320 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5321 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5322 SmallVector<int, 8> MaskVec;
5323 for (unsigned i = 0; i != NumElems; ++i)
5324 MaskVec.push_back(i == Idx ? 0 : 1);
5325 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5329 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5330 if (Values.size() == 1) {
5331 if (EVTBits == 32) {
5332 // Instead of a shuffle like this:
5333 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5334 // Check if it's possible to issue this instead.
5335 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5336 unsigned Idx = CountTrailingZeros_32(NonZeros);
5337 SDValue Item = Op.getOperand(Idx);
5338 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5339 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5344 // A vector full of immediates; various special cases are already
5345 // handled, so this is best done with a single constant-pool load.
5349 // For AVX-length vectors, build the individual 128-bit pieces and use
5350 // shuffles to put them in place.
5351 if (VT.is256BitVector()) {
5352 SmallVector<SDValue, 32> V;
5353 for (unsigned i = 0; i != NumElems; ++i)
5354 V.push_back(Op.getOperand(i));
5356 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5358 // Build both the lower and upper subvector.
5359 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5360 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5363 // Recreate the wider vector with the lower and upper part.
5364 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5367 // Let legalizer expand 2-wide build_vectors.
5368 if (EVTBits == 64) {
5369 if (NumNonZero == 1) {
5370 // One half is zero or undef.
5371 unsigned Idx = CountTrailingZeros_32(NonZeros);
5372 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5373 Op.getOperand(Idx));
5374 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5379 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5380 if (EVTBits == 8 && NumElems == 16) {
5381 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5383 if (V.getNode()) return V;
5386 if (EVTBits == 16 && NumElems == 8) {
5387 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5389 if (V.getNode()) return V;
5392 // If element VT is == 32 bits, turn it into a number of shuffles.
5393 SmallVector<SDValue, 8> V(NumElems);
5394 if (NumElems == 4 && NumZero > 0) {
5395 for (unsigned i = 0; i < 4; ++i) {
5396 bool isZero = !(NonZeros & (1 << i));
5398 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5400 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5403 for (unsigned i = 0; i < 2; ++i) {
5404 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5407 V[i] = V[i*2]; // Must be a zero vector.
5410 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5413 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5416 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5421 bool Reverse1 = (NonZeros & 0x3) == 2;
5422 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5426 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5427 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5429 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5432 if (Values.size() > 1 && VT.is128BitVector()) {
5433 // Check for a build vector of consecutive loads.
5434 for (unsigned i = 0; i < NumElems; ++i)
5435 V[i] = Op.getOperand(i);
5437 // Check for elements which are consecutive loads.
5438 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5442 // For SSE 4.1, use insertps to put the high elements into the low element.
5443 if (getSubtarget()->hasSSE41()) {
5445 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5446 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5448 Result = DAG.getUNDEF(VT);
5450 for (unsigned i = 1; i < NumElems; ++i) {
5451 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5452 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5453 Op.getOperand(i), DAG.getIntPtrConstant(i));
5458 // Otherwise, expand into a number of unpckl*, start by extending each of
5459 // our (non-undef) elements to the full vector width with the element in the
5460 // bottom slot of the vector (which generates no code for SSE).
5461 for (unsigned i = 0; i < NumElems; ++i) {
5462 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5463 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5465 V[i] = DAG.getUNDEF(VT);
5468 // Next, we iteratively mix elements, e.g. for v4f32:
5469 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5470 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5471 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5472 unsigned EltStride = NumElems >> 1;
5473 while (EltStride != 0) {
5474 for (unsigned i = 0; i < EltStride; ++i) {
5475 // If V[i+EltStride] is undef and this is the first round of mixing,
5476 // then it is safe to just drop this shuffle: V[i] is already in the
5477 // right place, the one element (since it's the first round) being
5478 // inserted as undef can be dropped. This isn't safe for successive
5479 // rounds because they will permute elements within both vectors.
5480 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5481 EltStride == NumElems/2)
5484 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5493 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5494 // to create 256-bit vectors from two other 128-bit ones.
5495 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5496 DebugLoc dl = Op.getDebugLoc();
5497 EVT ResVT = Op.getValueType();
5499 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5501 SDValue V1 = Op.getOperand(0);
5502 SDValue V2 = Op.getOperand(1);
5503 unsigned NumElems = ResVT.getVectorNumElements();
5505 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5508 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5509 assert(Op.getNumOperands() == 2);
5511 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5512 // from two other 128-bit ones.
5513 return LowerAVXCONCAT_VECTORS(Op, DAG);
5516 // Try to lower a shuffle node into a simple blend instruction.
5518 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5519 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5520 SDValue V1 = SVOp->getOperand(0);
5521 SDValue V2 = SVOp->getOperand(1);
5522 DebugLoc dl = SVOp->getDebugLoc();
5523 MVT VT = SVOp->getValueType(0).getSimpleVT();
5524 unsigned NumElems = VT.getVectorNumElements();
5526 if (!Subtarget->hasSSE41())
5532 switch (VT.SimpleTy) {
5533 default: return SDValue();
5535 ISDNo = X86ISD::BLENDPW;
5540 ISDNo = X86ISD::BLENDPS;
5545 ISDNo = X86ISD::BLENDPD;
5550 if (!Subtarget->hasAVX())
5552 ISDNo = X86ISD::BLENDPS;
5557 if (!Subtarget->hasAVX())
5559 ISDNo = X86ISD::BLENDPD;
5563 assert(ISDNo && "Invalid Op Number");
5565 unsigned MaskVals = 0;
5567 for (unsigned i = 0; i != NumElems; ++i) {
5568 int EltIdx = SVOp->getMaskElt(i);
5569 if (EltIdx == (int)i || EltIdx < 0)
5571 else if (EltIdx == (int)(i + NumElems))
5572 continue; // Bit is set to zero;
5577 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5578 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5579 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5580 DAG.getConstant(MaskVals, MVT::i32));
5581 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5584 // v8i16 shuffles - Prefer shuffles in the following order:
5585 // 1. [all] pshuflw, pshufhw, optional move
5586 // 2. [ssse3] 1 x pshufb
5587 // 3. [ssse3] 2 x pshufb + 1 x por
5588 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5590 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5591 SelectionDAG &DAG) {
5592 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5593 SDValue V1 = SVOp->getOperand(0);
5594 SDValue V2 = SVOp->getOperand(1);
5595 DebugLoc dl = SVOp->getDebugLoc();
5596 SmallVector<int, 8> MaskVals;
5598 // Determine if more than 1 of the words in each of the low and high quadwords
5599 // of the result come from the same quadword of one of the two inputs. Undef
5600 // mask values count as coming from any quadword, for better codegen.
5601 unsigned LoQuad[] = { 0, 0, 0, 0 };
5602 unsigned HiQuad[] = { 0, 0, 0, 0 };
5603 std::bitset<4> InputQuads;
5604 for (unsigned i = 0; i < 8; ++i) {
5605 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5606 int EltIdx = SVOp->getMaskElt(i);
5607 MaskVals.push_back(EltIdx);
5616 InputQuads.set(EltIdx / 4);
5619 int BestLoQuad = -1;
5620 unsigned MaxQuad = 1;
5621 for (unsigned i = 0; i < 4; ++i) {
5622 if (LoQuad[i] > MaxQuad) {
5624 MaxQuad = LoQuad[i];
5628 int BestHiQuad = -1;
5630 for (unsigned i = 0; i < 4; ++i) {
5631 if (HiQuad[i] > MaxQuad) {
5633 MaxQuad = HiQuad[i];
5637 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5638 // of the two input vectors, shuffle them into one input vector so only a
5639 // single pshufb instruction is necessary. If There are more than 2 input
5640 // quads, disable the next transformation since it does not help SSSE3.
5641 bool V1Used = InputQuads[0] || InputQuads[1];
5642 bool V2Used = InputQuads[2] || InputQuads[3];
5643 if (Subtarget->hasSSSE3()) {
5644 if (InputQuads.count() == 2 && V1Used && V2Used) {
5645 BestLoQuad = InputQuads[0] ? 0 : 1;
5646 BestHiQuad = InputQuads[2] ? 2 : 3;
5648 if (InputQuads.count() > 2) {
5654 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5655 // the shuffle mask. If a quad is scored as -1, that means that it contains
5656 // words from all 4 input quadwords.
5658 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5660 BestLoQuad < 0 ? 0 : BestLoQuad,
5661 BestHiQuad < 0 ? 1 : BestHiQuad
5663 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5664 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5665 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5666 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5668 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5669 // source words for the shuffle, to aid later transformations.
5670 bool AllWordsInNewV = true;
5671 bool InOrder[2] = { true, true };
5672 for (unsigned i = 0; i != 8; ++i) {
5673 int idx = MaskVals[i];
5675 InOrder[i/4] = false;
5676 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5678 AllWordsInNewV = false;
5682 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5683 if (AllWordsInNewV) {
5684 for (int i = 0; i != 8; ++i) {
5685 int idx = MaskVals[i];
5688 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5689 if ((idx != i) && idx < 4)
5691 if ((idx != i) && idx > 3)
5700 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5701 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5702 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5703 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5704 unsigned TargetMask = 0;
5705 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5706 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5707 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5708 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5709 getShufflePSHUFLWImmediate(SVOp);
5710 V1 = NewV.getOperand(0);
5711 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5715 // If we have SSSE3, and all words of the result are from 1 input vector,
5716 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5717 // is present, fall back to case 4.
5718 if (Subtarget->hasSSSE3()) {
5719 SmallVector<SDValue,16> pshufbMask;
5721 // If we have elements from both input vectors, set the high bit of the
5722 // shuffle mask element to zero out elements that come from V2 in the V1
5723 // mask, and elements that come from V1 in the V2 mask, so that the two
5724 // results can be OR'd together.
5725 bool TwoInputs = V1Used && V2Used;
5726 for (unsigned i = 0; i != 8; ++i) {
5727 int EltIdx = MaskVals[i] * 2;
5728 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5729 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5730 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5731 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5733 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5734 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5735 DAG.getNode(ISD::BUILD_VECTOR, dl,
5736 MVT::v16i8, &pshufbMask[0], 16));
5738 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5740 // Calculate the shuffle mask for the second input, shuffle it, and
5741 // OR it with the first shuffled input.
5743 for (unsigned i = 0; i != 8; ++i) {
5744 int EltIdx = MaskVals[i] * 2;
5745 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5746 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5747 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5748 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5750 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5751 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5752 DAG.getNode(ISD::BUILD_VECTOR, dl,
5753 MVT::v16i8, &pshufbMask[0], 16));
5754 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5755 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5758 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5759 // and update MaskVals with new element order.
5760 std::bitset<8> InOrder;
5761 if (BestLoQuad >= 0) {
5762 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5763 for (int i = 0; i != 4; ++i) {
5764 int idx = MaskVals[i];
5767 } else if ((idx / 4) == BestLoQuad) {
5772 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5775 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5776 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5777 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5779 getShufflePSHUFLWImmediate(SVOp), DAG);
5783 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5784 // and update MaskVals with the new element order.
5785 if (BestHiQuad >= 0) {
5786 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5787 for (unsigned i = 4; i != 8; ++i) {
5788 int idx = MaskVals[i];
5791 } else if ((idx / 4) == BestHiQuad) {
5792 MaskV[i] = (idx & 3) + 4;
5796 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5799 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5800 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5801 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5803 getShufflePSHUFHWImmediate(SVOp), DAG);
5807 // In case BestHi & BestLo were both -1, which means each quadword has a word
5808 // from each of the four input quadwords, calculate the InOrder bitvector now
5809 // before falling through to the insert/extract cleanup.
5810 if (BestLoQuad == -1 && BestHiQuad == -1) {
5812 for (int i = 0; i != 8; ++i)
5813 if (MaskVals[i] < 0 || MaskVals[i] == i)
5817 // The other elements are put in the right place using pextrw and pinsrw.
5818 for (unsigned i = 0; i != 8; ++i) {
5821 int EltIdx = MaskVals[i];
5824 SDValue ExtOp = (EltIdx < 8) ?
5825 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5826 DAG.getIntPtrConstant(EltIdx)) :
5827 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5828 DAG.getIntPtrConstant(EltIdx - 8));
5829 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5830 DAG.getIntPtrConstant(i));
5835 // v16i8 shuffles - Prefer shuffles in the following order:
5836 // 1. [ssse3] 1 x pshufb
5837 // 2. [ssse3] 2 x pshufb + 1 x por
5838 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5840 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5842 const X86TargetLowering &TLI) {
5843 SDValue V1 = SVOp->getOperand(0);
5844 SDValue V2 = SVOp->getOperand(1);
5845 DebugLoc dl = SVOp->getDebugLoc();
5846 ArrayRef<int> MaskVals = SVOp->getMask();
5848 // If we have SSSE3, case 1 is generated when all result bytes come from
5849 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5850 // present, fall back to case 3.
5852 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5853 if (TLI.getSubtarget()->hasSSSE3()) {
5854 SmallVector<SDValue,16> pshufbMask;
5856 // If all result elements are from one input vector, then only translate
5857 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5859 // Otherwise, we have elements from both input vectors, and must zero out
5860 // elements that come from V2 in the first mask, and V1 in the second mask
5861 // so that we can OR them together.
5862 for (unsigned i = 0; i != 16; ++i) {
5863 int EltIdx = MaskVals[i];
5864 if (EltIdx < 0 || EltIdx >= 16)
5866 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5868 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5869 DAG.getNode(ISD::BUILD_VECTOR, dl,
5870 MVT::v16i8, &pshufbMask[0], 16));
5872 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5873 // the 2nd operand if it's undefined or zero.
5874 if (V2.getOpcode() == ISD::UNDEF ||
5875 ISD::isBuildVectorAllZeros(V2.getNode()))
5878 // Calculate the shuffle mask for the second input, shuffle it, and
5879 // OR it with the first shuffled input.
5881 for (unsigned i = 0; i != 16; ++i) {
5882 int EltIdx = MaskVals[i];
5883 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5884 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5886 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5887 DAG.getNode(ISD::BUILD_VECTOR, dl,
5888 MVT::v16i8, &pshufbMask[0], 16));
5889 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5892 // No SSSE3 - Calculate in place words and then fix all out of place words
5893 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5894 // the 16 different words that comprise the two doublequadword input vectors.
5895 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5896 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5898 for (int i = 0; i != 8; ++i) {
5899 int Elt0 = MaskVals[i*2];
5900 int Elt1 = MaskVals[i*2+1];
5902 // This word of the result is all undef, skip it.
5903 if (Elt0 < 0 && Elt1 < 0)
5906 // This word of the result is already in the correct place, skip it.
5907 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5910 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5911 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5914 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5915 // using a single extract together, load it and store it.
5916 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5917 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5918 DAG.getIntPtrConstant(Elt1 / 2));
5919 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5920 DAG.getIntPtrConstant(i));
5924 // If Elt1 is defined, extract it from the appropriate source. If the
5925 // source byte is not also odd, shift the extracted word left 8 bits
5926 // otherwise clear the bottom 8 bits if we need to do an or.
5928 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5929 DAG.getIntPtrConstant(Elt1 / 2));
5930 if ((Elt1 & 1) == 0)
5931 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5933 TLI.getShiftAmountTy(InsElt.getValueType())));
5935 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5936 DAG.getConstant(0xFF00, MVT::i16));
5938 // If Elt0 is defined, extract it from the appropriate source. If the
5939 // source byte is not also even, shift the extracted word right 8 bits. If
5940 // Elt1 was also defined, OR the extracted values together before
5941 // inserting them in the result.
5943 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5944 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5945 if ((Elt0 & 1) != 0)
5946 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5948 TLI.getShiftAmountTy(InsElt0.getValueType())));
5950 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5951 DAG.getConstant(0x00FF, MVT::i16));
5952 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5955 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5956 DAG.getIntPtrConstant(i));
5958 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5961 // v32i8 shuffles - Translate to VPSHUFB if possible.
5963 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
5964 const X86Subtarget *Subtarget,
5965 SelectionDAG &DAG) {
5966 EVT VT = SVOp->getValueType(0);
5967 SDValue V1 = SVOp->getOperand(0);
5968 SDValue V2 = SVOp->getOperand(1);
5969 DebugLoc dl = SVOp->getDebugLoc();
5970 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
5972 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5973 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
5974 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
5976 // VPSHUFB may be generated if
5977 // (1) one of input vector is undefined or zeroinitializer.
5978 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
5979 // And (2) the mask indexes don't cross the 128-bit lane.
5980 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
5981 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
5984 if (V1IsAllZero && !V2IsAllZero) {
5985 CommuteVectorShuffleMask(MaskVals, 32);
5988 SmallVector<SDValue, 32> pshufbMask;
5989 for (unsigned i = 0; i != 32; i++) {
5990 int EltIdx = MaskVals[i];
5991 if (EltIdx < 0 || EltIdx >= 32)
5994 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
5995 // Cross lane is not allowed.
5999 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6001 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6002 DAG.getNode(ISD::BUILD_VECTOR, dl,
6003 MVT::v32i8, &pshufbMask[0], 32));
6006 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6007 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6008 /// done when every pair / quad of shuffle mask elements point to elements in
6009 /// the right sequence. e.g.
6010 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6012 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6013 SelectionDAG &DAG, DebugLoc dl) {
6014 MVT VT = SVOp->getValueType(0).getSimpleVT();
6015 unsigned NumElems = VT.getVectorNumElements();
6018 switch (VT.SimpleTy) {
6019 default: llvm_unreachable("Unexpected!");
6020 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6021 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6022 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6023 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6024 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6025 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6028 SmallVector<int, 8> MaskVec;
6029 for (unsigned i = 0; i != NumElems; i += Scale) {
6031 for (unsigned j = 0; j != Scale; ++j) {
6032 int EltIdx = SVOp->getMaskElt(i+j);
6036 StartIdx = (EltIdx / Scale);
6037 if (EltIdx != (int)(StartIdx*Scale + j))
6040 MaskVec.push_back(StartIdx);
6043 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6044 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6045 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6048 /// getVZextMovL - Return a zero-extending vector move low node.
6050 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6051 SDValue SrcOp, SelectionDAG &DAG,
6052 const X86Subtarget *Subtarget, DebugLoc dl) {
6053 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6054 LoadSDNode *LD = NULL;
6055 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6056 LD = dyn_cast<LoadSDNode>(SrcOp);
6058 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6060 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6061 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6062 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6063 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6064 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6066 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6067 return DAG.getNode(ISD::BITCAST, dl, VT,
6068 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6069 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6077 return DAG.getNode(ISD::BITCAST, dl, VT,
6078 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6079 DAG.getNode(ISD::BITCAST, dl,
6083 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6084 /// which could not be matched by any known target speficic shuffle
6086 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6088 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6089 if (NewOp.getNode())
6092 EVT VT = SVOp->getValueType(0);
6094 unsigned NumElems = VT.getVectorNumElements();
6095 unsigned NumLaneElems = NumElems / 2;
6097 DebugLoc dl = SVOp->getDebugLoc();
6098 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6099 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6102 SmallVector<int, 16> Mask;
6103 for (unsigned l = 0; l < 2; ++l) {
6104 // Build a shuffle mask for the output, discovering on the fly which
6105 // input vectors to use as shuffle operands (recorded in InputUsed).
6106 // If building a suitable shuffle vector proves too hard, then bail
6107 // out with UseBuildVector set.
6108 bool UseBuildVector = false;
6109 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6110 unsigned LaneStart = l * NumLaneElems;
6111 for (unsigned i = 0; i != NumLaneElems; ++i) {
6112 // The mask element. This indexes into the input.
6113 int Idx = SVOp->getMaskElt(i+LaneStart);
6115 // the mask element does not index into any input vector.
6120 // The input vector this mask element indexes into.
6121 int Input = Idx / NumLaneElems;
6123 // Turn the index into an offset from the start of the input vector.
6124 Idx -= Input * NumLaneElems;
6126 // Find or create a shuffle vector operand to hold this input.
6128 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6129 if (InputUsed[OpNo] == Input)
6130 // This input vector is already an operand.
6132 if (InputUsed[OpNo] < 0) {
6133 // Create a new operand for this input vector.
6134 InputUsed[OpNo] = Input;
6139 if (OpNo >= array_lengthof(InputUsed)) {
6140 // More than two input vectors used! Give up on trying to create a
6141 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6142 UseBuildVector = true;
6146 // Add the mask index for the new shuffle vector.
6147 Mask.push_back(Idx + OpNo * NumLaneElems);
6150 if (UseBuildVector) {
6151 SmallVector<SDValue, 16> SVOps;
6152 for (unsigned i = 0; i != NumLaneElems; ++i) {
6153 // The mask element. This indexes into the input.
6154 int Idx = SVOp->getMaskElt(i+LaneStart);
6156 SVOps.push_back(DAG.getUNDEF(EltVT));
6160 // The input vector this mask element indexes into.
6161 int Input = Idx / NumElems;
6163 // Turn the index into an offset from the start of the input vector.
6164 Idx -= Input * NumElems;
6166 // Extract the vector element by hand.
6167 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6168 SVOp->getOperand(Input),
6169 DAG.getIntPtrConstant(Idx)));
6172 // Construct the output using a BUILD_VECTOR.
6173 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6175 } else if (InputUsed[0] < 0) {
6176 // No input vectors were used! The result is undefined.
6177 Output[l] = DAG.getUNDEF(NVT);
6179 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6180 (InputUsed[0] % 2) * NumLaneElems,
6182 // If only one input was used, use an undefined vector for the other.
6183 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6184 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6185 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6186 // At least one input vector was used. Create a new shuffle vector.
6187 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6193 // Concatenate the result back
6194 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6197 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6198 /// 4 elements, and match them with several different shuffle types.
6200 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6201 SDValue V1 = SVOp->getOperand(0);
6202 SDValue V2 = SVOp->getOperand(1);
6203 DebugLoc dl = SVOp->getDebugLoc();
6204 EVT VT = SVOp->getValueType(0);
6206 assert(VT.is128BitVector() && "Unsupported vector size");
6208 std::pair<int, int> Locs[4];
6209 int Mask1[] = { -1, -1, -1, -1 };
6210 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6214 for (unsigned i = 0; i != 4; ++i) {
6215 int Idx = PermMask[i];
6217 Locs[i] = std::make_pair(-1, -1);
6219 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6221 Locs[i] = std::make_pair(0, NumLo);
6225 Locs[i] = std::make_pair(1, NumHi);
6227 Mask1[2+NumHi] = Idx;
6233 if (NumLo <= 2 && NumHi <= 2) {
6234 // If no more than two elements come from either vector. This can be
6235 // implemented with two shuffles. First shuffle gather the elements.
6236 // The second shuffle, which takes the first shuffle as both of its
6237 // vector operands, put the elements into the right order.
6238 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6240 int Mask2[] = { -1, -1, -1, -1 };
6242 for (unsigned i = 0; i != 4; ++i)
6243 if (Locs[i].first != -1) {
6244 unsigned Idx = (i < 2) ? 0 : 4;
6245 Idx += Locs[i].first * 2 + Locs[i].second;
6249 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6252 if (NumLo == 3 || NumHi == 3) {
6253 // Otherwise, we must have three elements from one vector, call it X, and
6254 // one element from the other, call it Y. First, use a shufps to build an
6255 // intermediate vector with the one element from Y and the element from X
6256 // that will be in the same half in the final destination (the indexes don't
6257 // matter). Then, use a shufps to build the final vector, taking the half
6258 // containing the element from Y from the intermediate, and the other half
6261 // Normalize it so the 3 elements come from V1.
6262 CommuteVectorShuffleMask(PermMask, 4);
6266 // Find the element from V2.
6268 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6269 int Val = PermMask[HiIndex];
6276 Mask1[0] = PermMask[HiIndex];
6278 Mask1[2] = PermMask[HiIndex^1];
6280 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6283 Mask1[0] = PermMask[0];
6284 Mask1[1] = PermMask[1];
6285 Mask1[2] = HiIndex & 1 ? 6 : 4;
6286 Mask1[3] = HiIndex & 1 ? 4 : 6;
6287 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6290 Mask1[0] = HiIndex & 1 ? 2 : 0;
6291 Mask1[1] = HiIndex & 1 ? 0 : 2;
6292 Mask1[2] = PermMask[2];
6293 Mask1[3] = PermMask[3];
6298 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6301 // Break it into (shuffle shuffle_hi, shuffle_lo).
6302 int LoMask[] = { -1, -1, -1, -1 };
6303 int HiMask[] = { -1, -1, -1, -1 };
6305 int *MaskPtr = LoMask;
6306 unsigned MaskIdx = 0;
6309 for (unsigned i = 0; i != 4; ++i) {
6316 int Idx = PermMask[i];
6318 Locs[i] = std::make_pair(-1, -1);
6319 } else if (Idx < 4) {
6320 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6321 MaskPtr[LoIdx] = Idx;
6324 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6325 MaskPtr[HiIdx] = Idx;
6330 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6331 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6332 int MaskOps[] = { -1, -1, -1, -1 };
6333 for (unsigned i = 0; i != 4; ++i)
6334 if (Locs[i].first != -1)
6335 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6336 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6339 static bool MayFoldVectorLoad(SDValue V) {
6340 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6341 V = V.getOperand(0);
6342 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6343 V = V.getOperand(0);
6344 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6345 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6346 // BUILD_VECTOR (load), undef
6347 V = V.getOperand(0);
6353 // FIXME: the version above should always be used. Since there's
6354 // a bug where several vector shuffles can't be folded because the
6355 // DAG is not updated during lowering and a node claims to have two
6356 // uses while it only has one, use this version, and let isel match
6357 // another instruction if the load really happens to have more than
6358 // one use. Remove this version after this bug get fixed.
6359 // rdar://8434668, PR8156
6360 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6361 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6362 V = V.getOperand(0);
6363 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6364 V = V.getOperand(0);
6365 if (ISD::isNormalLoad(V.getNode()))
6371 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6372 EVT VT = Op.getValueType();
6374 // Canonizalize to v2f64.
6375 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6376 return DAG.getNode(ISD::BITCAST, dl, VT,
6377 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6382 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6384 SDValue V1 = Op.getOperand(0);
6385 SDValue V2 = Op.getOperand(1);
6386 EVT VT = Op.getValueType();
6388 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6390 if (HasSSE2 && VT == MVT::v2f64)
6391 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6393 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6394 return DAG.getNode(ISD::BITCAST, dl, VT,
6395 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6396 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6397 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6401 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6402 SDValue V1 = Op.getOperand(0);
6403 SDValue V2 = Op.getOperand(1);
6404 EVT VT = Op.getValueType();
6406 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6407 "unsupported shuffle type");
6409 if (V2.getOpcode() == ISD::UNDEF)
6413 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6417 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6418 SDValue V1 = Op.getOperand(0);
6419 SDValue V2 = Op.getOperand(1);
6420 EVT VT = Op.getValueType();
6421 unsigned NumElems = VT.getVectorNumElements();
6423 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6424 // operand of these instructions is only memory, so check if there's a
6425 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6427 bool CanFoldLoad = false;
6429 // Trivial case, when V2 comes from a load.
6430 if (MayFoldVectorLoad(V2))
6433 // When V1 is a load, it can be folded later into a store in isel, example:
6434 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6436 // (MOVLPSmr addr:$src1, VR128:$src2)
6437 // So, recognize this potential and also use MOVLPS or MOVLPD
6438 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6441 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6443 if (HasSSE2 && NumElems == 2)
6444 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6447 // If we don't care about the second element, proceed to use movss.
6448 if (SVOp->getMaskElt(1) != -1)
6449 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6452 // movl and movlp will both match v2i64, but v2i64 is never matched by
6453 // movl earlier because we make it strict to avoid messing with the movlp load
6454 // folding logic (see the code above getMOVLP call). Match it here then,
6455 // this is horrible, but will stay like this until we move all shuffle
6456 // matching to x86 specific nodes. Note that for the 1st condition all
6457 // types are matched with movsd.
6459 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6460 // as to remove this logic from here, as much as possible
6461 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6462 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6463 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6466 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6468 // Invert the operand order and use SHUFPS to match it.
6469 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6470 getShuffleSHUFImmediate(SVOp), DAG);
6474 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6475 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6476 EVT VT = Op.getValueType();
6477 DebugLoc dl = Op.getDebugLoc();
6478 SDValue V1 = Op.getOperand(0);
6479 SDValue V2 = Op.getOperand(1);
6481 if (isZeroShuffle(SVOp))
6482 return getZeroVector(VT, Subtarget, DAG, dl);
6484 // Handle splat operations
6485 if (SVOp->isSplat()) {
6486 unsigned NumElem = VT.getVectorNumElements();
6487 int Size = VT.getSizeInBits();
6489 // Use vbroadcast whenever the splat comes from a foldable load
6490 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6491 if (Broadcast.getNode())
6494 // Handle splats by matching through known shuffle masks
6495 if ((Size == 128 && NumElem <= 4) ||
6496 (Size == 256 && NumElem < 8))
6499 // All remaning splats are promoted to target supported vector shuffles.
6500 return PromoteSplat(SVOp, DAG);
6503 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6505 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6506 VT == MVT::v16i16 || VT == MVT::v32i8) {
6507 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6508 if (NewOp.getNode())
6509 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6510 } else if ((VT == MVT::v4i32 ||
6511 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6512 // FIXME: Figure out a cleaner way to do this.
6513 // Try to make use of movq to zero out the top part.
6514 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6515 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6516 if (NewOp.getNode()) {
6517 EVT NewVT = NewOp.getValueType();
6518 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6519 NewVT, true, false))
6520 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6521 DAG, Subtarget, dl);
6523 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6524 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6525 if (NewOp.getNode()) {
6526 EVT NewVT = NewOp.getValueType();
6527 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6528 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6529 DAG, Subtarget, dl);
6537 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6538 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6539 SDValue V1 = Op.getOperand(0);
6540 SDValue V2 = Op.getOperand(1);
6541 EVT VT = Op.getValueType();
6542 DebugLoc dl = Op.getDebugLoc();
6543 unsigned NumElems = VT.getVectorNumElements();
6544 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6545 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6546 bool V1IsSplat = false;
6547 bool V2IsSplat = false;
6548 bool HasSSE2 = Subtarget->hasSSE2();
6549 bool HasAVX = Subtarget->hasAVX();
6550 bool HasAVX2 = Subtarget->hasAVX2();
6551 MachineFunction &MF = DAG.getMachineFunction();
6552 bool OptForSize = MF.getFunction()->getFnAttributes().
6553 hasAttribute(Attributes::OptimizeForSize);
6555 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6557 if (V1IsUndef && V2IsUndef)
6558 return DAG.getUNDEF(VT);
6560 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6562 // Vector shuffle lowering takes 3 steps:
6564 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6565 // narrowing and commutation of operands should be handled.
6566 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6568 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6569 // so the shuffle can be broken into other shuffles and the legalizer can
6570 // try the lowering again.
6572 // The general idea is that no vector_shuffle operation should be left to
6573 // be matched during isel, all of them must be converted to a target specific
6576 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6577 // narrowing and commutation of operands should be handled. The actual code
6578 // doesn't include all of those, work in progress...
6579 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6580 if (NewOp.getNode())
6583 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6585 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6586 // unpckh_undef). Only use pshufd if speed is more important than size.
6587 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6588 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6589 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6590 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6592 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6593 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6594 return getMOVDDup(Op, dl, V1, DAG);
6596 if (isMOVHLPS_v_undef_Mask(M, VT))
6597 return getMOVHighToLow(Op, dl, DAG);
6599 // Use to match splats
6600 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6601 (VT == MVT::v2f64 || VT == MVT::v2i64))
6602 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6604 if (isPSHUFDMask(M, VT)) {
6605 // The actual implementation will match the mask in the if above and then
6606 // during isel it can match several different instructions, not only pshufd
6607 // as its name says, sad but true, emulate the behavior for now...
6608 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6609 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6611 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6613 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6614 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6616 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6617 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6619 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6623 // Check if this can be converted into a logical shift.
6624 bool isLeft = false;
6627 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6628 if (isShift && ShVal.hasOneUse()) {
6629 // If the shifted value has multiple uses, it may be cheaper to use
6630 // v_set0 + movlhps or movhlps, etc.
6631 EVT EltVT = VT.getVectorElementType();
6632 ShAmt *= EltVT.getSizeInBits();
6633 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6636 if (isMOVLMask(M, VT)) {
6637 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6638 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6639 if (!isMOVLPMask(M, VT)) {
6640 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6641 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6643 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6644 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6648 // FIXME: fold these into legal mask.
6649 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6650 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6652 if (isMOVHLPSMask(M, VT))
6653 return getMOVHighToLow(Op, dl, DAG);
6655 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6656 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6658 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6659 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6661 if (isMOVLPMask(M, VT))
6662 return getMOVLP(Op, dl, DAG, HasSSE2);
6664 if (ShouldXformToMOVHLPS(M, VT) ||
6665 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6666 return CommuteVectorShuffle(SVOp, DAG);
6669 // No better options. Use a vshldq / vsrldq.
6670 EVT EltVT = VT.getVectorElementType();
6671 ShAmt *= EltVT.getSizeInBits();
6672 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6675 bool Commuted = false;
6676 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6677 // 1,1,1,1 -> v8i16 though.
6678 V1IsSplat = isSplatVector(V1.getNode());
6679 V2IsSplat = isSplatVector(V2.getNode());
6681 // Canonicalize the splat or undef, if present, to be on the RHS.
6682 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6683 CommuteVectorShuffleMask(M, NumElems);
6685 std::swap(V1IsSplat, V2IsSplat);
6689 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6690 // Shuffling low element of v1 into undef, just return v1.
6693 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6694 // the instruction selector will not match, so get a canonical MOVL with
6695 // swapped operands to undo the commute.
6696 return getMOVL(DAG, dl, VT, V2, V1);
6699 if (isUNPCKLMask(M, VT, HasAVX2))
6700 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6702 if (isUNPCKHMask(M, VT, HasAVX2))
6703 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6706 // Normalize mask so all entries that point to V2 points to its first
6707 // element then try to match unpck{h|l} again. If match, return a
6708 // new vector_shuffle with the corrected mask.p
6709 SmallVector<int, 8> NewMask(M.begin(), M.end());
6710 NormalizeMask(NewMask, NumElems);
6711 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6712 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6713 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6714 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6718 // Commute is back and try unpck* again.
6719 // FIXME: this seems wrong.
6720 CommuteVectorShuffleMask(M, NumElems);
6722 std::swap(V1IsSplat, V2IsSplat);
6725 if (isUNPCKLMask(M, VT, HasAVX2))
6726 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6728 if (isUNPCKHMask(M, VT, HasAVX2))
6729 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6732 // Normalize the node to match x86 shuffle ops if needed
6733 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6734 return CommuteVectorShuffle(SVOp, DAG);
6736 // The checks below are all present in isShuffleMaskLegal, but they are
6737 // inlined here right now to enable us to directly emit target specific
6738 // nodes, and remove one by one until they don't return Op anymore.
6740 if (isPALIGNRMask(M, VT, Subtarget))
6741 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6742 getShufflePALIGNRImmediate(SVOp),
6745 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6746 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6747 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6748 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6751 if (isPSHUFHWMask(M, VT, HasAVX2))
6752 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6753 getShufflePSHUFHWImmediate(SVOp),
6756 if (isPSHUFLWMask(M, VT, HasAVX2))
6757 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6758 getShufflePSHUFLWImmediate(SVOp),
6761 if (isSHUFPMask(M, VT, HasAVX))
6762 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6763 getShuffleSHUFImmediate(SVOp), DAG);
6765 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6766 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6767 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6768 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6770 //===--------------------------------------------------------------------===//
6771 // Generate target specific nodes for 128 or 256-bit shuffles only
6772 // supported in the AVX instruction set.
6775 // Handle VMOVDDUPY permutations
6776 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6777 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6779 // Handle VPERMILPS/D* permutations
6780 if (isVPERMILPMask(M, VT, HasAVX)) {
6781 if (HasAVX2 && VT == MVT::v8i32)
6782 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6783 getShuffleSHUFImmediate(SVOp), DAG);
6784 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6785 getShuffleSHUFImmediate(SVOp), DAG);
6788 // Handle VPERM2F128/VPERM2I128 permutations
6789 if (isVPERM2X128Mask(M, VT, HasAVX))
6790 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6791 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6793 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6794 if (BlendOp.getNode())
6797 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6798 SmallVector<SDValue, 8> permclMask;
6799 for (unsigned i = 0; i != 8; ++i) {
6800 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6802 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6804 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6805 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6806 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6809 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6810 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6811 getShuffleCLImmediate(SVOp), DAG);
6814 //===--------------------------------------------------------------------===//
6815 // Since no target specific shuffle was selected for this generic one,
6816 // lower it into other known shuffles. FIXME: this isn't true yet, but
6817 // this is the plan.
6820 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6821 if (VT == MVT::v8i16) {
6822 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6823 if (NewOp.getNode())
6827 if (VT == MVT::v16i8) {
6828 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6829 if (NewOp.getNode())
6833 if (VT == MVT::v32i8) {
6834 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6835 if (NewOp.getNode())
6839 // Handle all 128-bit wide vectors with 4 elements, and match them with
6840 // several different shuffle types.
6841 if (NumElems == 4 && VT.is128BitVector())
6842 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6844 // Handle general 256-bit shuffles
6845 if (VT.is256BitVector())
6846 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6852 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6853 SelectionDAG &DAG) const {
6854 EVT VT = Op.getValueType();
6855 DebugLoc dl = Op.getDebugLoc();
6857 if (!Op.getOperand(0).getValueType().is128BitVector())
6860 if (VT.getSizeInBits() == 8) {
6861 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6862 Op.getOperand(0), Op.getOperand(1));
6863 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6864 DAG.getValueType(VT));
6865 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6868 if (VT.getSizeInBits() == 16) {
6869 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6870 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6872 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6873 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6874 DAG.getNode(ISD::BITCAST, dl,
6878 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6879 Op.getOperand(0), Op.getOperand(1));
6880 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6881 DAG.getValueType(VT));
6882 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6885 if (VT == MVT::f32) {
6886 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6887 // the result back to FR32 register. It's only worth matching if the
6888 // result has a single use which is a store or a bitcast to i32. And in
6889 // the case of a store, it's not worth it if the index is a constant 0,
6890 // because a MOVSSmr can be used instead, which is smaller and faster.
6891 if (!Op.hasOneUse())
6893 SDNode *User = *Op.getNode()->use_begin();
6894 if ((User->getOpcode() != ISD::STORE ||
6895 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6896 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6897 (User->getOpcode() != ISD::BITCAST ||
6898 User->getValueType(0) != MVT::i32))
6900 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6901 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6904 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6907 if (VT == MVT::i32 || VT == MVT::i64) {
6908 // ExtractPS/pextrq works with constant index.
6909 if (isa<ConstantSDNode>(Op.getOperand(1)))
6917 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6918 SelectionDAG &DAG) const {
6919 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6922 SDValue Vec = Op.getOperand(0);
6923 EVT VecVT = Vec.getValueType();
6925 // If this is a 256-bit vector result, first extract the 128-bit vector and
6926 // then extract the element from the 128-bit vector.
6927 if (VecVT.is256BitVector()) {
6928 DebugLoc dl = Op.getNode()->getDebugLoc();
6929 unsigned NumElems = VecVT.getVectorNumElements();
6930 SDValue Idx = Op.getOperand(1);
6931 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6933 // Get the 128-bit vector.
6934 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6936 if (IdxVal >= NumElems/2)
6937 IdxVal -= NumElems/2;
6938 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6939 DAG.getConstant(IdxVal, MVT::i32));
6942 assert(VecVT.is128BitVector() && "Unexpected vector length");
6944 if (Subtarget->hasSSE41()) {
6945 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6950 EVT VT = Op.getValueType();
6951 DebugLoc dl = Op.getDebugLoc();
6952 // TODO: handle v16i8.
6953 if (VT.getSizeInBits() == 16) {
6954 SDValue Vec = Op.getOperand(0);
6955 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6957 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6958 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6959 DAG.getNode(ISD::BITCAST, dl,
6962 // Transform it so it match pextrw which produces a 32-bit result.
6963 EVT EltVT = MVT::i32;
6964 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6965 Op.getOperand(0), Op.getOperand(1));
6966 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6967 DAG.getValueType(VT));
6968 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6971 if (VT.getSizeInBits() == 32) {
6972 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6976 // SHUFPS the element to the lowest double word, then movss.
6977 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6978 EVT VVT = Op.getOperand(0).getValueType();
6979 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6980 DAG.getUNDEF(VVT), Mask);
6981 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6982 DAG.getIntPtrConstant(0));
6985 if (VT.getSizeInBits() == 64) {
6986 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6987 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6988 // to match extract_elt for f64.
6989 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6993 // UNPCKHPD the element to the lowest double word, then movsd.
6994 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6995 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6996 int Mask[2] = { 1, -1 };
6997 EVT VVT = Op.getOperand(0).getValueType();
6998 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6999 DAG.getUNDEF(VVT), Mask);
7000 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7001 DAG.getIntPtrConstant(0));
7008 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7009 SelectionDAG &DAG) const {
7010 EVT VT = Op.getValueType();
7011 EVT EltVT = VT.getVectorElementType();
7012 DebugLoc dl = Op.getDebugLoc();
7014 SDValue N0 = Op.getOperand(0);
7015 SDValue N1 = Op.getOperand(1);
7016 SDValue N2 = Op.getOperand(2);
7018 if (!VT.is128BitVector())
7021 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7022 isa<ConstantSDNode>(N2)) {
7024 if (VT == MVT::v8i16)
7025 Opc = X86ISD::PINSRW;
7026 else if (VT == MVT::v16i8)
7027 Opc = X86ISD::PINSRB;
7029 Opc = X86ISD::PINSRB;
7031 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7033 if (N1.getValueType() != MVT::i32)
7034 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7035 if (N2.getValueType() != MVT::i32)
7036 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7037 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7040 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7041 // Bits [7:6] of the constant are the source select. This will always be
7042 // zero here. The DAG Combiner may combine an extract_elt index into these
7043 // bits. For example (insert (extract, 3), 2) could be matched by putting
7044 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7045 // Bits [5:4] of the constant are the destination select. This is the
7046 // value of the incoming immediate.
7047 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7048 // combine either bitwise AND or insert of float 0.0 to set these bits.
7049 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7050 // Create this as a scalar to vector..
7051 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7052 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7055 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7056 // PINSR* works with constant index.
7063 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7064 EVT VT = Op.getValueType();
7065 EVT EltVT = VT.getVectorElementType();
7067 DebugLoc dl = Op.getDebugLoc();
7068 SDValue N0 = Op.getOperand(0);
7069 SDValue N1 = Op.getOperand(1);
7070 SDValue N2 = Op.getOperand(2);
7072 // If this is a 256-bit vector result, first extract the 128-bit vector,
7073 // insert the element into the extracted half and then place it back.
7074 if (VT.is256BitVector()) {
7075 if (!isa<ConstantSDNode>(N2))
7078 // Get the desired 128-bit vector half.
7079 unsigned NumElems = VT.getVectorNumElements();
7080 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7081 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7083 // Insert the element into the desired half.
7084 bool Upper = IdxVal >= NumElems/2;
7085 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7086 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7088 // Insert the changed part back to the 256-bit vector
7089 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7092 if (Subtarget->hasSSE41())
7093 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7095 if (EltVT == MVT::i8)
7098 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7099 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7100 // as its second argument.
7101 if (N1.getValueType() != MVT::i32)
7102 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7103 if (N2.getValueType() != MVT::i32)
7104 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7105 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7110 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7111 LLVMContext *Context = DAG.getContext();
7112 DebugLoc dl = Op.getDebugLoc();
7113 EVT OpVT = Op.getValueType();
7115 // If this is a 256-bit vector result, first insert into a 128-bit
7116 // vector and then insert into the 256-bit vector.
7117 if (!OpVT.is128BitVector()) {
7118 // Insert into a 128-bit vector.
7119 EVT VT128 = EVT::getVectorVT(*Context,
7120 OpVT.getVectorElementType(),
7121 OpVT.getVectorNumElements() / 2);
7123 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7125 // Insert the 128-bit vector.
7126 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7129 if (OpVT == MVT::v1i64 &&
7130 Op.getOperand(0).getValueType() == MVT::i64)
7131 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7133 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7134 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7135 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7136 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7139 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7140 // a simple subregister reference or explicit instructions to grab
7141 // upper bits of a vector.
7142 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7143 SelectionDAG &DAG) {
7144 if (Subtarget->hasAVX()) {
7145 DebugLoc dl = Op.getNode()->getDebugLoc();
7146 SDValue Vec = Op.getNode()->getOperand(0);
7147 SDValue Idx = Op.getNode()->getOperand(1);
7149 if (Op.getNode()->getValueType(0).is128BitVector() &&
7150 Vec.getNode()->getValueType(0).is256BitVector() &&
7151 isa<ConstantSDNode>(Idx)) {
7152 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7153 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7159 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7160 // simple superregister reference or explicit instructions to insert
7161 // the upper bits of a vector.
7162 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7163 SelectionDAG &DAG) {
7164 if (Subtarget->hasAVX()) {
7165 DebugLoc dl = Op.getNode()->getDebugLoc();
7166 SDValue Vec = Op.getNode()->getOperand(0);
7167 SDValue SubVec = Op.getNode()->getOperand(1);
7168 SDValue Idx = Op.getNode()->getOperand(2);
7170 if (Op.getNode()->getValueType(0).is256BitVector() &&
7171 SubVec.getNode()->getValueType(0).is128BitVector() &&
7172 isa<ConstantSDNode>(Idx)) {
7173 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7174 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7180 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7181 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7182 // one of the above mentioned nodes. It has to be wrapped because otherwise
7183 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7184 // be used to form addressing mode. These wrapped nodes will be selected
7187 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7188 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7190 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7192 unsigned char OpFlag = 0;
7193 unsigned WrapperKind = X86ISD::Wrapper;
7194 CodeModel::Model M = getTargetMachine().getCodeModel();
7196 if (Subtarget->isPICStyleRIPRel() &&
7197 (M == CodeModel::Small || M == CodeModel::Kernel))
7198 WrapperKind = X86ISD::WrapperRIP;
7199 else if (Subtarget->isPICStyleGOT())
7200 OpFlag = X86II::MO_GOTOFF;
7201 else if (Subtarget->isPICStyleStubPIC())
7202 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7204 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7206 CP->getOffset(), OpFlag);
7207 DebugLoc DL = CP->getDebugLoc();
7208 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7209 // With PIC, the address is actually $g + Offset.
7211 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7212 DAG.getNode(X86ISD::GlobalBaseReg,
7213 DebugLoc(), getPointerTy()),
7220 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7221 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7223 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7225 unsigned char OpFlag = 0;
7226 unsigned WrapperKind = X86ISD::Wrapper;
7227 CodeModel::Model M = getTargetMachine().getCodeModel();
7229 if (Subtarget->isPICStyleRIPRel() &&
7230 (M == CodeModel::Small || M == CodeModel::Kernel))
7231 WrapperKind = X86ISD::WrapperRIP;
7232 else if (Subtarget->isPICStyleGOT())
7233 OpFlag = X86II::MO_GOTOFF;
7234 else if (Subtarget->isPICStyleStubPIC())
7235 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7237 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7239 DebugLoc DL = JT->getDebugLoc();
7240 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7242 // With PIC, the address is actually $g + Offset.
7244 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7245 DAG.getNode(X86ISD::GlobalBaseReg,
7246 DebugLoc(), getPointerTy()),
7253 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7254 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7256 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7258 unsigned char OpFlag = 0;
7259 unsigned WrapperKind = X86ISD::Wrapper;
7260 CodeModel::Model M = getTargetMachine().getCodeModel();
7262 if (Subtarget->isPICStyleRIPRel() &&
7263 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7264 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7265 OpFlag = X86II::MO_GOTPCREL;
7266 WrapperKind = X86ISD::WrapperRIP;
7267 } else if (Subtarget->isPICStyleGOT()) {
7268 OpFlag = X86II::MO_GOT;
7269 } else if (Subtarget->isPICStyleStubPIC()) {
7270 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7271 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7272 OpFlag = X86II::MO_DARWIN_NONLAZY;
7275 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7277 DebugLoc DL = Op.getDebugLoc();
7278 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7281 // With PIC, the address is actually $g + Offset.
7282 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7283 !Subtarget->is64Bit()) {
7284 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7285 DAG.getNode(X86ISD::GlobalBaseReg,
7286 DebugLoc(), getPointerTy()),
7290 // For symbols that require a load from a stub to get the address, emit the
7292 if (isGlobalStubReference(OpFlag))
7293 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7294 MachinePointerInfo::getGOT(), false, false, false, 0);
7300 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7301 // Create the TargetBlockAddressAddress node.
7302 unsigned char OpFlags =
7303 Subtarget->ClassifyBlockAddressReference();
7304 CodeModel::Model M = getTargetMachine().getCodeModel();
7305 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7306 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7307 DebugLoc dl = Op.getDebugLoc();
7308 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7311 if (Subtarget->isPICStyleRIPRel() &&
7312 (M == CodeModel::Small || M == CodeModel::Kernel))
7313 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7315 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7317 // With PIC, the address is actually $g + Offset.
7318 if (isGlobalRelativeToPICBase(OpFlags)) {
7319 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7320 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7328 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7330 SelectionDAG &DAG) const {
7331 // Create the TargetGlobalAddress node, folding in the constant
7332 // offset if it is legal.
7333 unsigned char OpFlags =
7334 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7335 CodeModel::Model M = getTargetMachine().getCodeModel();
7337 if (OpFlags == X86II::MO_NO_FLAG &&
7338 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7339 // A direct static reference to a global.
7340 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7343 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7346 if (Subtarget->isPICStyleRIPRel() &&
7347 (M == CodeModel::Small || M == CodeModel::Kernel))
7348 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7350 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7352 // With PIC, the address is actually $g + Offset.
7353 if (isGlobalRelativeToPICBase(OpFlags)) {
7354 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7355 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7359 // For globals that require a load from a stub to get the address, emit the
7361 if (isGlobalStubReference(OpFlags))
7362 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7363 MachinePointerInfo::getGOT(), false, false, false, 0);
7365 // If there was a non-zero offset that we didn't fold, create an explicit
7368 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7369 DAG.getConstant(Offset, getPointerTy()));
7375 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7376 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7377 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7378 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7382 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7383 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7384 unsigned char OperandFlags, bool LocalDynamic = false) {
7385 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7386 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7387 DebugLoc dl = GA->getDebugLoc();
7388 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7389 GA->getValueType(0),
7393 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7397 SDValue Ops[] = { Chain, TGA, *InFlag };
7398 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7400 SDValue Ops[] = { Chain, TGA };
7401 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7404 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7405 MFI->setAdjustsStack(true);
7407 SDValue Flag = Chain.getValue(1);
7408 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7411 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7413 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7416 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7417 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7418 DAG.getNode(X86ISD::GlobalBaseReg,
7419 DebugLoc(), PtrVT), InFlag);
7420 InFlag = Chain.getValue(1);
7422 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7425 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7427 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7429 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7430 X86::RAX, X86II::MO_TLSGD);
7433 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7437 DebugLoc dl = GA->getDebugLoc();
7439 // Get the start address of the TLS block for this module.
7440 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7441 .getInfo<X86MachineFunctionInfo>();
7442 MFI->incNumLocalDynamicTLSAccesses();
7446 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7447 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7450 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7451 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7452 InFlag = Chain.getValue(1);
7453 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7454 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7457 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7461 unsigned char OperandFlags = X86II::MO_DTPOFF;
7462 unsigned WrapperKind = X86ISD::Wrapper;
7463 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7464 GA->getValueType(0),
7465 GA->getOffset(), OperandFlags);
7466 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7468 // Add x@dtpoff with the base.
7469 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7472 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7473 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7474 const EVT PtrVT, TLSModel::Model model,
7475 bool is64Bit, bool isPIC) {
7476 DebugLoc dl = GA->getDebugLoc();
7478 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7479 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7480 is64Bit ? 257 : 256));
7482 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7483 DAG.getIntPtrConstant(0),
7484 MachinePointerInfo(Ptr),
7485 false, false, false, 0);
7487 unsigned char OperandFlags = 0;
7488 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7490 unsigned WrapperKind = X86ISD::Wrapper;
7491 if (model == TLSModel::LocalExec) {
7492 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7493 } else if (model == TLSModel::InitialExec) {
7495 OperandFlags = X86II::MO_GOTTPOFF;
7496 WrapperKind = X86ISD::WrapperRIP;
7498 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7501 llvm_unreachable("Unexpected model");
7504 // emit "addl x@ntpoff,%eax" (local exec)
7505 // or "addl x@indntpoff,%eax" (initial exec)
7506 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7507 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7508 GA->getValueType(0),
7509 GA->getOffset(), OperandFlags);
7510 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7512 if (model == TLSModel::InitialExec) {
7513 if (isPIC && !is64Bit) {
7514 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7515 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7519 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7520 MachinePointerInfo::getGOT(), false, false, false,
7524 // The address of the thread local variable is the add of the thread
7525 // pointer with the offset of the variable.
7526 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7530 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7532 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7533 const GlobalValue *GV = GA->getGlobal();
7535 if (Subtarget->isTargetELF()) {
7536 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7539 case TLSModel::GeneralDynamic:
7540 if (Subtarget->is64Bit())
7541 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7542 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7543 case TLSModel::LocalDynamic:
7544 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7545 Subtarget->is64Bit());
7546 case TLSModel::InitialExec:
7547 case TLSModel::LocalExec:
7548 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7549 Subtarget->is64Bit(),
7550 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7552 llvm_unreachable("Unknown TLS model.");
7555 if (Subtarget->isTargetDarwin()) {
7556 // Darwin only has one model of TLS. Lower to that.
7557 unsigned char OpFlag = 0;
7558 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7559 X86ISD::WrapperRIP : X86ISD::Wrapper;
7561 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7563 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7564 !Subtarget->is64Bit();
7566 OpFlag = X86II::MO_TLVP_PIC_BASE;
7568 OpFlag = X86II::MO_TLVP;
7569 DebugLoc DL = Op.getDebugLoc();
7570 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7571 GA->getValueType(0),
7572 GA->getOffset(), OpFlag);
7573 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7575 // With PIC32, the address is actually $g + Offset.
7577 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7578 DAG.getNode(X86ISD::GlobalBaseReg,
7579 DebugLoc(), getPointerTy()),
7582 // Lowering the machine isd will make sure everything is in the right
7584 SDValue Chain = DAG.getEntryNode();
7585 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7586 SDValue Args[] = { Chain, Offset };
7587 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7589 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7590 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7591 MFI->setAdjustsStack(true);
7593 // And our return value (tls address) is in the standard call return value
7595 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7596 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7600 if (Subtarget->isTargetWindows()) {
7601 // Just use the implicit TLS architecture
7602 // Need to generate someting similar to:
7603 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7605 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7606 // mov rcx, qword [rdx+rcx*8]
7607 // mov eax, .tls$:tlsvar
7608 // [rax+rcx] contains the address
7609 // Windows 64bit: gs:0x58
7610 // Windows 32bit: fs:__tls_array
7612 // If GV is an alias then use the aliasee for determining
7613 // thread-localness.
7614 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7615 GV = GA->resolveAliasedGlobal(false);
7616 DebugLoc dl = GA->getDebugLoc();
7617 SDValue Chain = DAG.getEntryNode();
7619 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7620 // %gs:0x58 (64-bit).
7621 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7622 ? Type::getInt8PtrTy(*DAG.getContext(),
7624 : Type::getInt32PtrTy(*DAG.getContext(),
7627 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7628 Subtarget->is64Bit()
7629 ? DAG.getIntPtrConstant(0x58)
7630 : DAG.getExternalSymbol("_tls_array",
7632 MachinePointerInfo(Ptr),
7633 false, false, false, 0);
7635 // Load the _tls_index variable
7636 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7637 if (Subtarget->is64Bit())
7638 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7639 IDX, MachinePointerInfo(), MVT::i32,
7642 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7643 false, false, false, 0);
7645 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7647 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7649 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7650 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7651 false, false, false, 0);
7653 // Get the offset of start of .tls section
7654 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7655 GA->getValueType(0),
7656 GA->getOffset(), X86II::MO_SECREL);
7657 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7659 // The address of the thread local variable is the add of the thread
7660 // pointer with the offset of the variable.
7661 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7664 llvm_unreachable("TLS not implemented for this target.");
7668 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7669 /// and take a 2 x i32 value to shift plus a shift amount.
7670 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7671 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7672 EVT VT = Op.getValueType();
7673 unsigned VTBits = VT.getSizeInBits();
7674 DebugLoc dl = Op.getDebugLoc();
7675 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7676 SDValue ShOpLo = Op.getOperand(0);
7677 SDValue ShOpHi = Op.getOperand(1);
7678 SDValue ShAmt = Op.getOperand(2);
7679 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7680 DAG.getConstant(VTBits - 1, MVT::i8))
7681 : DAG.getConstant(0, VT);
7684 if (Op.getOpcode() == ISD::SHL_PARTS) {
7685 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7686 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7688 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7689 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7692 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7693 DAG.getConstant(VTBits, MVT::i8));
7694 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7695 AndNode, DAG.getConstant(0, MVT::i8));
7698 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7699 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7700 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7702 if (Op.getOpcode() == ISD::SHL_PARTS) {
7703 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7704 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7706 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7707 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7710 SDValue Ops[2] = { Lo, Hi };
7711 return DAG.getMergeValues(Ops, 2, dl);
7714 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7715 SelectionDAG &DAG) const {
7716 EVT SrcVT = Op.getOperand(0).getValueType();
7718 if (SrcVT.isVector())
7721 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7722 "Unknown SINT_TO_FP to lower!");
7724 // These are really Legal; return the operand so the caller accepts it as
7726 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7728 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7729 Subtarget->is64Bit()) {
7733 DebugLoc dl = Op.getDebugLoc();
7734 unsigned Size = SrcVT.getSizeInBits()/8;
7735 MachineFunction &MF = DAG.getMachineFunction();
7736 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7737 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7738 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7740 MachinePointerInfo::getFixedStack(SSFI),
7742 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7745 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7747 SelectionDAG &DAG) const {
7749 DebugLoc DL = Op.getDebugLoc();
7751 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7753 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7755 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7757 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7759 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7760 MachineMemOperand *MMO;
7762 int SSFI = FI->getIndex();
7764 DAG.getMachineFunction()
7765 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7766 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7768 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7769 StackSlot = StackSlot.getOperand(1);
7771 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7772 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7774 Tys, Ops, array_lengthof(Ops),
7778 Chain = Result.getValue(1);
7779 SDValue InFlag = Result.getValue(2);
7781 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7782 // shouldn't be necessary except that RFP cannot be live across
7783 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7784 MachineFunction &MF = DAG.getMachineFunction();
7785 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7786 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7787 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7788 Tys = DAG.getVTList(MVT::Other);
7790 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7792 MachineMemOperand *MMO =
7793 DAG.getMachineFunction()
7794 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7795 MachineMemOperand::MOStore, SSFISize, SSFISize);
7797 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7798 Ops, array_lengthof(Ops),
7799 Op.getValueType(), MMO);
7800 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7801 MachinePointerInfo::getFixedStack(SSFI),
7802 false, false, false, 0);
7808 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7809 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7810 SelectionDAG &DAG) const {
7811 // This algorithm is not obvious. Here it is what we're trying to output:
7814 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7815 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7819 pshufd $0x4e, %xmm0, %xmm1
7824 DebugLoc dl = Op.getDebugLoc();
7825 LLVMContext *Context = DAG.getContext();
7827 // Build some magic constants.
7828 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7829 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7830 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7832 SmallVector<Constant*,2> CV1;
7834 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7836 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7837 Constant *C1 = ConstantVector::get(CV1);
7838 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7840 // Load the 64-bit value into an XMM register.
7841 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7843 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7844 MachinePointerInfo::getConstantPool(),
7845 false, false, false, 16);
7846 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7847 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7850 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7851 MachinePointerInfo::getConstantPool(),
7852 false, false, false, 16);
7853 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7854 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7857 if (Subtarget->hasSSE3()) {
7858 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7859 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7861 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7862 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7864 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7865 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7869 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7870 DAG.getIntPtrConstant(0));
7873 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7874 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7875 SelectionDAG &DAG) const {
7876 DebugLoc dl = Op.getDebugLoc();
7877 // FP constant to bias correct the final result.
7878 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7881 // Load the 32-bit value into an XMM register.
7882 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7885 // Zero out the upper parts of the register.
7886 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7888 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7889 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7890 DAG.getIntPtrConstant(0));
7892 // Or the load with the bias.
7893 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7894 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7895 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7897 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7898 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7899 MVT::v2f64, Bias)));
7900 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7901 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7902 DAG.getIntPtrConstant(0));
7904 // Subtract the bias.
7905 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7907 // Handle final rounding.
7908 EVT DestVT = Op.getValueType();
7910 if (DestVT.bitsLT(MVT::f64))
7911 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7912 DAG.getIntPtrConstant(0));
7913 if (DestVT.bitsGT(MVT::f64))
7914 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7916 // Handle final rounding.
7920 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7921 SelectionDAG &DAG) const {
7922 SDValue N0 = Op.getOperand(0);
7923 DebugLoc dl = Op.getDebugLoc();
7925 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7926 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7927 // the optimization here.
7928 if (DAG.SignBitIsZero(N0))
7929 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7931 EVT SrcVT = N0.getValueType();
7932 EVT DstVT = Op.getValueType();
7933 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7934 return LowerUINT_TO_FP_i64(Op, DAG);
7935 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7936 return LowerUINT_TO_FP_i32(Op, DAG);
7937 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7940 // Make a 64-bit buffer, and use it to build an FILD.
7941 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7942 if (SrcVT == MVT::i32) {
7943 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7944 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7945 getPointerTy(), StackSlot, WordOff);
7946 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7947 StackSlot, MachinePointerInfo(),
7949 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7950 OffsetSlot, MachinePointerInfo(),
7952 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7956 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7957 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7958 StackSlot, MachinePointerInfo(),
7960 // For i64 source, we need to add the appropriate power of 2 if the input
7961 // was negative. This is the same as the optimization in
7962 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7963 // we must be careful to do the computation in x87 extended precision, not
7964 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7965 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7966 MachineMemOperand *MMO =
7967 DAG.getMachineFunction()
7968 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7969 MachineMemOperand::MOLoad, 8, 8);
7971 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7972 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7973 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7976 APInt FF(32, 0x5F800000ULL);
7978 // Check whether the sign bit is set.
7979 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7980 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7983 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7984 SDValue FudgePtr = DAG.getConstantPool(
7985 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7988 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7989 SDValue Zero = DAG.getIntPtrConstant(0);
7990 SDValue Four = DAG.getIntPtrConstant(4);
7991 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7993 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7995 // Load the value out, extending it from f32 to f80.
7996 // FIXME: Avoid the extend by constructing the right constant pool?
7997 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7998 FudgePtr, MachinePointerInfo::getConstantPool(),
7999 MVT::f32, false, false, 4);
8000 // Extend everything to 80 bits to force it to be done on x87.
8001 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8002 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8005 std::pair<SDValue,SDValue> X86TargetLowering::
8006 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8007 DebugLoc DL = Op.getDebugLoc();
8009 EVT DstTy = Op.getValueType();
8011 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8012 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8016 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8017 DstTy.getSimpleVT() >= MVT::i16 &&
8018 "Unknown FP_TO_INT to lower!");
8020 // These are really Legal.
8021 if (DstTy == MVT::i32 &&
8022 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8023 return std::make_pair(SDValue(), SDValue());
8024 if (Subtarget->is64Bit() &&
8025 DstTy == MVT::i64 &&
8026 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8027 return std::make_pair(SDValue(), SDValue());
8029 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8030 // stack slot, or into the FTOL runtime function.
8031 MachineFunction &MF = DAG.getMachineFunction();
8032 unsigned MemSize = DstTy.getSizeInBits()/8;
8033 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8034 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8037 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8038 Opc = X86ISD::WIN_FTOL;
8040 switch (DstTy.getSimpleVT().SimpleTy) {
8041 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8042 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8043 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8044 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8047 SDValue Chain = DAG.getEntryNode();
8048 SDValue Value = Op.getOperand(0);
8049 EVT TheVT = Op.getOperand(0).getValueType();
8050 // FIXME This causes a redundant load/store if the SSE-class value is already
8051 // in memory, such as if it is on the callstack.
8052 if (isScalarFPTypeInSSEReg(TheVT)) {
8053 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8054 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8055 MachinePointerInfo::getFixedStack(SSFI),
8057 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8059 Chain, StackSlot, DAG.getValueType(TheVT)
8062 MachineMemOperand *MMO =
8063 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8064 MachineMemOperand::MOLoad, MemSize, MemSize);
8065 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8067 Chain = Value.getValue(1);
8068 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8069 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8072 MachineMemOperand *MMO =
8073 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8074 MachineMemOperand::MOStore, MemSize, MemSize);
8076 if (Opc != X86ISD::WIN_FTOL) {
8077 // Build the FP_TO_INT*_IN_MEM
8078 SDValue Ops[] = { Chain, Value, StackSlot };
8079 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8080 Ops, 3, DstTy, MMO);
8081 return std::make_pair(FIST, StackSlot);
8083 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8084 DAG.getVTList(MVT::Other, MVT::Glue),
8086 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8087 MVT::i32, ftol.getValue(1));
8088 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8089 MVT::i32, eax.getValue(2));
8090 SDValue Ops[] = { eax, edx };
8091 SDValue pair = IsReplace
8092 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8093 : DAG.getMergeValues(Ops, 2, DL);
8094 return std::make_pair(pair, SDValue());
8098 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8099 SelectionDAG &DAG) const {
8100 if (Op.getValueType().isVector())
8103 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8104 /*IsSigned=*/ true, /*IsReplace=*/ false);
8105 SDValue FIST = Vals.first, StackSlot = Vals.second;
8106 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8107 if (FIST.getNode() == 0) return Op;
8109 if (StackSlot.getNode())
8111 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8112 FIST, StackSlot, MachinePointerInfo(),
8113 false, false, false, 0);
8115 // The node is the result.
8119 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8120 SelectionDAG &DAG) const {
8121 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8122 /*IsSigned=*/ false, /*IsReplace=*/ false);
8123 SDValue FIST = Vals.first, StackSlot = Vals.second;
8124 assert(FIST.getNode() && "Unexpected failure");
8126 if (StackSlot.getNode())
8128 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8129 FIST, StackSlot, MachinePointerInfo(),
8130 false, false, false, 0);
8132 // The node is the result.
8136 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8137 SelectionDAG &DAG) const {
8138 DebugLoc DL = Op.getDebugLoc();
8139 EVT VT = Op.getValueType();
8140 SDValue In = Op.getOperand(0);
8141 EVT SVT = In.getValueType();
8143 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8145 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8146 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8147 In, DAG.getUNDEF(SVT)));
8150 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8151 LLVMContext *Context = DAG.getContext();
8152 DebugLoc dl = Op.getDebugLoc();
8153 EVT VT = Op.getValueType();
8155 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8156 if (VT.isVector()) {
8157 EltVT = VT.getVectorElementType();
8158 NumElts = VT.getVectorNumElements();
8161 if (EltVT == MVT::f64)
8162 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8164 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8165 C = ConstantVector::getSplat(NumElts, C);
8166 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8167 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8168 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8169 MachinePointerInfo::getConstantPool(),
8170 false, false, false, Alignment);
8171 if (VT.isVector()) {
8172 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8173 return DAG.getNode(ISD::BITCAST, dl, VT,
8174 DAG.getNode(ISD::AND, dl, ANDVT,
8175 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8177 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8179 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8182 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8183 LLVMContext *Context = DAG.getContext();
8184 DebugLoc dl = Op.getDebugLoc();
8185 EVT VT = Op.getValueType();
8187 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8188 if (VT.isVector()) {
8189 EltVT = VT.getVectorElementType();
8190 NumElts = VT.getVectorNumElements();
8193 if (EltVT == MVT::f64)
8194 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8196 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8197 C = ConstantVector::getSplat(NumElts, C);
8198 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8199 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8200 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8201 MachinePointerInfo::getConstantPool(),
8202 false, false, false, Alignment);
8203 if (VT.isVector()) {
8204 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8205 return DAG.getNode(ISD::BITCAST, dl, VT,
8206 DAG.getNode(ISD::XOR, dl, XORVT,
8207 DAG.getNode(ISD::BITCAST, dl, XORVT,
8209 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8212 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8215 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8216 LLVMContext *Context = DAG.getContext();
8217 SDValue Op0 = Op.getOperand(0);
8218 SDValue Op1 = Op.getOperand(1);
8219 DebugLoc dl = Op.getDebugLoc();
8220 EVT VT = Op.getValueType();
8221 EVT SrcVT = Op1.getValueType();
8223 // If second operand is smaller, extend it first.
8224 if (SrcVT.bitsLT(VT)) {
8225 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8228 // And if it is bigger, shrink it first.
8229 if (SrcVT.bitsGT(VT)) {
8230 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8234 // At this point the operands and the result should have the same
8235 // type, and that won't be f80 since that is not custom lowered.
8237 // First get the sign bit of second operand.
8238 SmallVector<Constant*,4> CV;
8239 if (SrcVT == MVT::f64) {
8240 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8241 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8243 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8244 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8245 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8246 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8248 Constant *C = ConstantVector::get(CV);
8249 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8250 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8251 MachinePointerInfo::getConstantPool(),
8252 false, false, false, 16);
8253 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8255 // Shift sign bit right or left if the two operands have different types.
8256 if (SrcVT.bitsGT(VT)) {
8257 // Op0 is MVT::f32, Op1 is MVT::f64.
8258 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8259 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8260 DAG.getConstant(32, MVT::i32));
8261 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8262 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8263 DAG.getIntPtrConstant(0));
8266 // Clear first operand sign bit.
8268 if (VT == MVT::f64) {
8269 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8270 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8272 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8273 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8274 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8275 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8277 C = ConstantVector::get(CV);
8278 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8279 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8280 MachinePointerInfo::getConstantPool(),
8281 false, false, false, 16);
8282 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8284 // Or the value with the sign bit.
8285 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8288 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8289 SDValue N0 = Op.getOperand(0);
8290 DebugLoc dl = Op.getDebugLoc();
8291 EVT VT = Op.getValueType();
8293 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8294 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8295 DAG.getConstant(1, VT));
8296 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8299 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8301 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8302 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8304 if (!Subtarget->hasSSE41())
8307 if (!Op->hasOneUse())
8310 SDNode *N = Op.getNode();
8311 DebugLoc DL = N->getDebugLoc();
8313 SmallVector<SDValue, 8> Opnds;
8314 DenseMap<SDValue, unsigned> VecInMap;
8315 EVT VT = MVT::Other;
8317 // Recognize a special case where a vector is casted into wide integer to
8319 Opnds.push_back(N->getOperand(0));
8320 Opnds.push_back(N->getOperand(1));
8322 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8323 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8324 // BFS traverse all OR'd operands.
8325 if (I->getOpcode() == ISD::OR) {
8326 Opnds.push_back(I->getOperand(0));
8327 Opnds.push_back(I->getOperand(1));
8328 // Re-evaluate the number of nodes to be traversed.
8329 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8333 // Quit if a non-EXTRACT_VECTOR_ELT
8334 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8337 // Quit if without a constant index.
8338 SDValue Idx = I->getOperand(1);
8339 if (!isa<ConstantSDNode>(Idx))
8342 SDValue ExtractedFromVec = I->getOperand(0);
8343 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8344 if (M == VecInMap.end()) {
8345 VT = ExtractedFromVec.getValueType();
8346 // Quit if not 128/256-bit vector.
8347 if (!VT.is128BitVector() && !VT.is256BitVector())
8349 // Quit if not the same type.
8350 if (VecInMap.begin() != VecInMap.end() &&
8351 VT != VecInMap.begin()->first.getValueType())
8353 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8355 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8358 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8359 "Not extracted from 128-/256-bit vector.");
8361 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8362 SmallVector<SDValue, 8> VecIns;
8364 for (DenseMap<SDValue, unsigned>::const_iterator
8365 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8366 // Quit if not all elements are used.
8367 if (I->second != FullMask)
8369 VecIns.push_back(I->first);
8372 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8374 // Cast all vectors into TestVT for PTEST.
8375 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8376 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8378 // If more than one full vectors are evaluated, OR them first before PTEST.
8379 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8380 // Each iteration will OR 2 nodes and append the result until there is only
8381 // 1 node left, i.e. the final OR'd value of all vectors.
8382 SDValue LHS = VecIns[Slot];
8383 SDValue RHS = VecIns[Slot + 1];
8384 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8387 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8388 VecIns.back(), VecIns.back());
8391 /// Emit nodes that will be selected as "test Op0,Op0", or something
8393 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8394 SelectionDAG &DAG) const {
8395 DebugLoc dl = Op.getDebugLoc();
8397 // CF and OF aren't always set the way we want. Determine which
8398 // of these we need.
8399 bool NeedCF = false;
8400 bool NeedOF = false;
8403 case X86::COND_A: case X86::COND_AE:
8404 case X86::COND_B: case X86::COND_BE:
8407 case X86::COND_G: case X86::COND_GE:
8408 case X86::COND_L: case X86::COND_LE:
8409 case X86::COND_O: case X86::COND_NO:
8414 // See if we can use the EFLAGS value from the operand instead of
8415 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8416 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8417 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8418 // Emit a CMP with 0, which is the TEST pattern.
8419 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8420 DAG.getConstant(0, Op.getValueType()));
8422 unsigned Opcode = 0;
8423 unsigned NumOperands = 0;
8425 // Truncate operations may prevent the merge of the SETCC instruction
8426 // and the arithmetic intruction before it. Attempt to truncate the operands
8427 // of the arithmetic instruction and use a reduced bit-width instruction.
8428 bool NeedTruncation = false;
8429 SDValue ArithOp = Op;
8430 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8431 SDValue Arith = Op->getOperand(0);
8432 // Both the trunc and the arithmetic op need to have one user each.
8433 if (Arith->hasOneUse())
8434 switch (Arith.getOpcode()) {
8441 NeedTruncation = true;
8447 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8448 // which may be the result of a CAST. We use the variable 'Op', which is the
8449 // non-casted variable when we check for possible users.
8450 switch (ArithOp.getOpcode()) {
8452 // Due to an isel shortcoming, be conservative if this add is likely to be
8453 // selected as part of a load-modify-store instruction. When the root node
8454 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8455 // uses of other nodes in the match, such as the ADD in this case. This
8456 // leads to the ADD being left around and reselected, with the result being
8457 // two adds in the output. Alas, even if none our users are stores, that
8458 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8459 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8460 // climbing the DAG back to the root, and it doesn't seem to be worth the
8462 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8463 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8464 if (UI->getOpcode() != ISD::CopyToReg &&
8465 UI->getOpcode() != ISD::SETCC &&
8466 UI->getOpcode() != ISD::STORE)
8469 if (ConstantSDNode *C =
8470 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8471 // An add of one will be selected as an INC.
8472 if (C->getAPIntValue() == 1) {
8473 Opcode = X86ISD::INC;
8478 // An add of negative one (subtract of one) will be selected as a DEC.
8479 if (C->getAPIntValue().isAllOnesValue()) {
8480 Opcode = X86ISD::DEC;
8486 // Otherwise use a regular EFLAGS-setting add.
8487 Opcode = X86ISD::ADD;
8491 // If the primary and result isn't used, don't bother using X86ISD::AND,
8492 // because a TEST instruction will be better.
8493 bool NonFlagUse = false;
8494 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8495 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8497 unsigned UOpNo = UI.getOperandNo();
8498 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8499 // Look pass truncate.
8500 UOpNo = User->use_begin().getOperandNo();
8501 User = *User->use_begin();
8504 if (User->getOpcode() != ISD::BRCOND &&
8505 User->getOpcode() != ISD::SETCC &&
8506 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8519 // Due to the ISEL shortcoming noted above, be conservative if this op is
8520 // likely to be selected as part of a load-modify-store instruction.
8521 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8522 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8523 if (UI->getOpcode() == ISD::STORE)
8526 // Otherwise use a regular EFLAGS-setting instruction.
8527 switch (ArithOp.getOpcode()) {
8528 default: llvm_unreachable("unexpected operator!");
8529 case ISD::SUB: Opcode = X86ISD::SUB; break;
8530 case ISD::XOR: Opcode = X86ISD::XOR; break;
8531 case ISD::AND: Opcode = X86ISD::AND; break;
8533 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8534 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8535 if (EFLAGS.getNode())
8538 Opcode = X86ISD::OR;
8552 return SDValue(Op.getNode(), 1);
8558 // If we found that truncation is beneficial, perform the truncation and
8560 if (NeedTruncation) {
8561 EVT VT = Op.getValueType();
8562 SDValue WideVal = Op->getOperand(0);
8563 EVT WideVT = WideVal.getValueType();
8564 unsigned ConvertedOp = 0;
8565 // Use a target machine opcode to prevent further DAGCombine
8566 // optimizations that may separate the arithmetic operations
8567 // from the setcc node.
8568 switch (WideVal.getOpcode()) {
8570 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8571 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8572 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8573 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8574 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8579 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8580 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8581 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8582 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8588 // Emit a CMP with 0, which is the TEST pattern.
8589 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8590 DAG.getConstant(0, Op.getValueType()));
8592 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8593 SmallVector<SDValue, 4> Ops;
8594 for (unsigned i = 0; i != NumOperands; ++i)
8595 Ops.push_back(Op.getOperand(i));
8597 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8598 DAG.ReplaceAllUsesWith(Op, New);
8599 return SDValue(New.getNode(), 1);
8602 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8604 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8605 SelectionDAG &DAG) const {
8606 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8607 if (C->getAPIntValue() == 0)
8608 return EmitTest(Op0, X86CC, DAG);
8610 DebugLoc dl = Op0.getDebugLoc();
8611 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8612 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8613 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8614 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8615 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8617 return SDValue(Sub.getNode(), 1);
8619 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8622 /// Convert a comparison if required by the subtarget.
8623 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8624 SelectionDAG &DAG) const {
8625 // If the subtarget does not support the FUCOMI instruction, floating-point
8626 // comparisons have to be converted.
8627 if (Subtarget->hasCMov() ||
8628 Cmp.getOpcode() != X86ISD::CMP ||
8629 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8630 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8633 // The instruction selector will select an FUCOM instruction instead of
8634 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8635 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8636 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8637 DebugLoc dl = Cmp.getDebugLoc();
8638 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8639 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8640 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8641 DAG.getConstant(8, MVT::i8));
8642 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8643 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8646 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8647 /// if it's possible.
8648 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8649 DebugLoc dl, SelectionDAG &DAG) const {
8650 SDValue Op0 = And.getOperand(0);
8651 SDValue Op1 = And.getOperand(1);
8652 if (Op0.getOpcode() == ISD::TRUNCATE)
8653 Op0 = Op0.getOperand(0);
8654 if (Op1.getOpcode() == ISD::TRUNCATE)
8655 Op1 = Op1.getOperand(0);
8658 if (Op1.getOpcode() == ISD::SHL)
8659 std::swap(Op0, Op1);
8660 if (Op0.getOpcode() == ISD::SHL) {
8661 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8662 if (And00C->getZExtValue() == 1) {
8663 // If we looked past a truncate, check that it's only truncating away
8665 unsigned BitWidth = Op0.getValueSizeInBits();
8666 unsigned AndBitWidth = And.getValueSizeInBits();
8667 if (BitWidth > AndBitWidth) {
8669 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8670 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8674 RHS = Op0.getOperand(1);
8676 } else if (Op1.getOpcode() == ISD::Constant) {
8677 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8678 uint64_t AndRHSVal = AndRHS->getZExtValue();
8679 SDValue AndLHS = Op0;
8681 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8682 LHS = AndLHS.getOperand(0);
8683 RHS = AndLHS.getOperand(1);
8686 // Use BT if the immediate can't be encoded in a TEST instruction.
8687 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8689 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8693 if (LHS.getNode()) {
8694 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8695 // instruction. Since the shift amount is in-range-or-undefined, we know
8696 // that doing a bittest on the i32 value is ok. We extend to i32 because
8697 // the encoding for the i16 version is larger than the i32 version.
8698 // Also promote i16 to i32 for performance / code size reason.
8699 if (LHS.getValueType() == MVT::i8 ||
8700 LHS.getValueType() == MVT::i16)
8701 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8703 // If the operand types disagree, extend the shift amount to match. Since
8704 // BT ignores high bits (like shifts) we can use anyextend.
8705 if (LHS.getValueType() != RHS.getValueType())
8706 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8708 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8709 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8710 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8711 DAG.getConstant(Cond, MVT::i8), BT);
8717 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8719 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8721 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8722 SDValue Op0 = Op.getOperand(0);
8723 SDValue Op1 = Op.getOperand(1);
8724 DebugLoc dl = Op.getDebugLoc();
8725 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8727 // Optimize to BT if possible.
8728 // Lower (X & (1 << N)) == 0 to BT(X, N).
8729 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8730 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8731 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8732 Op1.getOpcode() == ISD::Constant &&
8733 cast<ConstantSDNode>(Op1)->isNullValue() &&
8734 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8735 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8736 if (NewSetCC.getNode())
8740 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8742 if (Op1.getOpcode() == ISD::Constant &&
8743 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8744 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8745 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8747 // If the input is a setcc, then reuse the input setcc or use a new one with
8748 // the inverted condition.
8749 if (Op0.getOpcode() == X86ISD::SETCC) {
8750 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8751 bool Invert = (CC == ISD::SETNE) ^
8752 cast<ConstantSDNode>(Op1)->isNullValue();
8753 if (!Invert) return Op0;
8755 CCode = X86::GetOppositeBranchCondition(CCode);
8756 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8757 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8761 bool isFP = Op1.getValueType().isFloatingPoint();
8762 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8763 if (X86CC == X86::COND_INVALID)
8766 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8767 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8768 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8769 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8772 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8773 // ones, and then concatenate the result back.
8774 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8775 EVT VT = Op.getValueType();
8777 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8778 "Unsupported value type for operation");
8780 unsigned NumElems = VT.getVectorNumElements();
8781 DebugLoc dl = Op.getDebugLoc();
8782 SDValue CC = Op.getOperand(2);
8784 // Extract the LHS vectors
8785 SDValue LHS = Op.getOperand(0);
8786 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8787 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8789 // Extract the RHS vectors
8790 SDValue RHS = Op.getOperand(1);
8791 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8792 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8794 // Issue the operation on the smaller types and concatenate the result back
8795 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8796 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8797 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8798 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8799 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8803 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8805 SDValue Op0 = Op.getOperand(0);
8806 SDValue Op1 = Op.getOperand(1);
8807 SDValue CC = Op.getOperand(2);
8808 EVT VT = Op.getValueType();
8809 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8810 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8811 DebugLoc dl = Op.getDebugLoc();
8815 EVT EltVT = Op0.getValueType().getVectorElementType();
8816 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8822 // SSE Condition code mapping:
8831 switch (SetCCOpcode) {
8832 default: llvm_unreachable("Unexpected SETCC condition");
8834 case ISD::SETEQ: SSECC = 0; break;
8836 case ISD::SETGT: Swap = true; // Fallthrough
8838 case ISD::SETOLT: SSECC = 1; break;
8840 case ISD::SETGE: Swap = true; // Fallthrough
8842 case ISD::SETOLE: SSECC = 2; break;
8843 case ISD::SETUO: SSECC = 3; break;
8845 case ISD::SETNE: SSECC = 4; break;
8846 case ISD::SETULE: Swap = true; // Fallthrough
8847 case ISD::SETUGE: SSECC = 5; break;
8848 case ISD::SETULT: Swap = true; // Fallthrough
8849 case ISD::SETUGT: SSECC = 6; break;
8850 case ISD::SETO: SSECC = 7; break;
8852 case ISD::SETONE: SSECC = 8; break;
8855 std::swap(Op0, Op1);
8857 // In the two special cases we can't handle, emit two comparisons.
8860 unsigned CombineOpc;
8861 if (SetCCOpcode == ISD::SETUEQ) {
8862 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8864 assert(SetCCOpcode == ISD::SETONE);
8865 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8868 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8869 DAG.getConstant(CC0, MVT::i8));
8870 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8871 DAG.getConstant(CC1, MVT::i8));
8872 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8874 // Handle all other FP comparisons here.
8875 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8876 DAG.getConstant(SSECC, MVT::i8));
8879 // Break 256-bit integer vector compare into smaller ones.
8880 if (VT.is256BitVector() && !Subtarget->hasAVX2())
8881 return Lower256IntVSETCC(Op, DAG);
8883 // We are handling one of the integer comparisons here. Since SSE only has
8884 // GT and EQ comparisons for integer, swapping operands and multiple
8885 // operations may be required for some comparisons.
8887 bool Swap = false, Invert = false, FlipSigns = false;
8889 switch (SetCCOpcode) {
8890 default: llvm_unreachable("Unexpected SETCC condition");
8891 case ISD::SETNE: Invert = true;
8892 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8893 case ISD::SETLT: Swap = true;
8894 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8895 case ISD::SETGE: Swap = true;
8896 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8897 case ISD::SETULT: Swap = true;
8898 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8899 case ISD::SETUGE: Swap = true;
8900 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8903 std::swap(Op0, Op1);
8905 // Check that the operation in question is available (most are plain SSE2,
8906 // but PCMPGTQ and PCMPEQQ have different requirements).
8907 if (VT == MVT::v2i64) {
8908 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8910 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8914 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8915 // bits of the inputs before performing those operations.
8917 EVT EltVT = VT.getVectorElementType();
8918 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8920 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8921 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8923 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8924 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8927 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8929 // If the logical-not of the result is required, perform that now.
8931 Result = DAG.getNOT(dl, Result, VT);
8936 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8937 static bool isX86LogicalCmp(SDValue Op) {
8938 unsigned Opc = Op.getNode()->getOpcode();
8939 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8940 Opc == X86ISD::SAHF)
8942 if (Op.getResNo() == 1 &&
8943 (Opc == X86ISD::ADD ||
8944 Opc == X86ISD::SUB ||
8945 Opc == X86ISD::ADC ||
8946 Opc == X86ISD::SBB ||
8947 Opc == X86ISD::SMUL ||
8948 Opc == X86ISD::UMUL ||
8949 Opc == X86ISD::INC ||
8950 Opc == X86ISD::DEC ||
8951 Opc == X86ISD::OR ||
8952 Opc == X86ISD::XOR ||
8953 Opc == X86ISD::AND))
8956 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8962 static bool isZero(SDValue V) {
8963 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8964 return C && C->isNullValue();
8967 static bool isAllOnes(SDValue V) {
8968 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8969 return C && C->isAllOnesValue();
8972 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8973 if (V.getOpcode() != ISD::TRUNCATE)
8976 SDValue VOp0 = V.getOperand(0);
8977 unsigned InBits = VOp0.getValueSizeInBits();
8978 unsigned Bits = V.getValueSizeInBits();
8979 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8982 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8983 bool addTest = true;
8984 SDValue Cond = Op.getOperand(0);
8985 SDValue Op1 = Op.getOperand(1);
8986 SDValue Op2 = Op.getOperand(2);
8987 DebugLoc DL = Op.getDebugLoc();
8990 if (Cond.getOpcode() == ISD::SETCC) {
8991 SDValue NewCond = LowerSETCC(Cond, DAG);
8992 if (NewCond.getNode())
8996 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8997 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8998 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8999 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9000 if (Cond.getOpcode() == X86ISD::SETCC &&
9001 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9002 isZero(Cond.getOperand(1).getOperand(1))) {
9003 SDValue Cmp = Cond.getOperand(1);
9005 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9007 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9008 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9009 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9011 SDValue CmpOp0 = Cmp.getOperand(0);
9012 // Apply further optimizations for special cases
9013 // (select (x != 0), -1, 0) -> neg & sbb
9014 // (select (x == 0), 0, -1) -> neg & sbb
9015 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9016 if (YC->isNullValue() &&
9017 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9018 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9019 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9020 DAG.getConstant(0, CmpOp0.getValueType()),
9022 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9023 DAG.getConstant(X86::COND_B, MVT::i8),
9024 SDValue(Neg.getNode(), 1));
9028 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9029 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9030 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9032 SDValue Res = // Res = 0 or -1.
9033 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9034 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9036 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9037 Res = DAG.getNOT(DL, Res, Res.getValueType());
9039 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9040 if (N2C == 0 || !N2C->isNullValue())
9041 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9046 // Look past (and (setcc_carry (cmp ...)), 1).
9047 if (Cond.getOpcode() == ISD::AND &&
9048 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9049 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9050 if (C && C->getAPIntValue() == 1)
9051 Cond = Cond.getOperand(0);
9054 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9055 // setting operand in place of the X86ISD::SETCC.
9056 unsigned CondOpcode = Cond.getOpcode();
9057 if (CondOpcode == X86ISD::SETCC ||
9058 CondOpcode == X86ISD::SETCC_CARRY) {
9059 CC = Cond.getOperand(0);
9061 SDValue Cmp = Cond.getOperand(1);
9062 unsigned Opc = Cmp.getOpcode();
9063 EVT VT = Op.getValueType();
9065 bool IllegalFPCMov = false;
9066 if (VT.isFloatingPoint() && !VT.isVector() &&
9067 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9068 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9070 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9071 Opc == X86ISD::BT) { // FIXME
9075 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9076 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9077 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9078 Cond.getOperand(0).getValueType() != MVT::i8)) {
9079 SDValue LHS = Cond.getOperand(0);
9080 SDValue RHS = Cond.getOperand(1);
9084 switch (CondOpcode) {
9085 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9086 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9087 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9088 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9089 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9090 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9091 default: llvm_unreachable("unexpected overflowing operator");
9093 if (CondOpcode == ISD::UMULO)
9094 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9097 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9099 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9101 if (CondOpcode == ISD::UMULO)
9102 Cond = X86Op.getValue(2);
9104 Cond = X86Op.getValue(1);
9106 CC = DAG.getConstant(X86Cond, MVT::i8);
9111 // Look pass the truncate if the high bits are known zero.
9112 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9113 Cond = Cond.getOperand(0);
9115 // We know the result of AND is compared against zero. Try to match
9117 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9118 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9119 if (NewSetCC.getNode()) {
9120 CC = NewSetCC.getOperand(0);
9121 Cond = NewSetCC.getOperand(1);
9128 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9129 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9132 // a < b ? -1 : 0 -> RES = ~setcc_carry
9133 // a < b ? 0 : -1 -> RES = setcc_carry
9134 // a >= b ? -1 : 0 -> RES = setcc_carry
9135 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9136 if (Cond.getOpcode() == X86ISD::SUB) {
9137 Cond = ConvertCmpIfNecessary(Cond, DAG);
9138 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9140 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9141 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9142 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9143 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9144 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9145 return DAG.getNOT(DL, Res, Res.getValueType());
9150 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9151 // condition is true.
9152 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9153 SDValue Ops[] = { Op2, Op1, CC, Cond };
9154 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9157 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9158 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9159 // from the AND / OR.
9160 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9161 Opc = Op.getOpcode();
9162 if (Opc != ISD::OR && Opc != ISD::AND)
9164 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9165 Op.getOperand(0).hasOneUse() &&
9166 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9167 Op.getOperand(1).hasOneUse());
9170 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9171 // 1 and that the SETCC node has a single use.
9172 static bool isXor1OfSetCC(SDValue Op) {
9173 if (Op.getOpcode() != ISD::XOR)
9175 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9176 if (N1C && N1C->getAPIntValue() == 1) {
9177 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9178 Op.getOperand(0).hasOneUse();
9183 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9184 bool addTest = true;
9185 SDValue Chain = Op.getOperand(0);
9186 SDValue Cond = Op.getOperand(1);
9187 SDValue Dest = Op.getOperand(2);
9188 DebugLoc dl = Op.getDebugLoc();
9190 bool Inverted = false;
9192 if (Cond.getOpcode() == ISD::SETCC) {
9193 // Check for setcc([su]{add,sub,mul}o == 0).
9194 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9195 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9196 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9197 Cond.getOperand(0).getResNo() == 1 &&
9198 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9199 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9200 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9201 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9202 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9203 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9205 Cond = Cond.getOperand(0);
9207 SDValue NewCond = LowerSETCC(Cond, DAG);
9208 if (NewCond.getNode())
9213 // FIXME: LowerXALUO doesn't handle these!!
9214 else if (Cond.getOpcode() == X86ISD::ADD ||
9215 Cond.getOpcode() == X86ISD::SUB ||
9216 Cond.getOpcode() == X86ISD::SMUL ||
9217 Cond.getOpcode() == X86ISD::UMUL)
9218 Cond = LowerXALUO(Cond, DAG);
9221 // Look pass (and (setcc_carry (cmp ...)), 1).
9222 if (Cond.getOpcode() == ISD::AND &&
9223 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9224 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9225 if (C && C->getAPIntValue() == 1)
9226 Cond = Cond.getOperand(0);
9229 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9230 // setting operand in place of the X86ISD::SETCC.
9231 unsigned CondOpcode = Cond.getOpcode();
9232 if (CondOpcode == X86ISD::SETCC ||
9233 CondOpcode == X86ISD::SETCC_CARRY) {
9234 CC = Cond.getOperand(0);
9236 SDValue Cmp = Cond.getOperand(1);
9237 unsigned Opc = Cmp.getOpcode();
9238 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9239 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9243 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9247 // These can only come from an arithmetic instruction with overflow,
9248 // e.g. SADDO, UADDO.
9249 Cond = Cond.getNode()->getOperand(1);
9255 CondOpcode = Cond.getOpcode();
9256 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9257 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9258 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9259 Cond.getOperand(0).getValueType() != MVT::i8)) {
9260 SDValue LHS = Cond.getOperand(0);
9261 SDValue RHS = Cond.getOperand(1);
9265 switch (CondOpcode) {
9266 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9267 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9268 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9269 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9270 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9271 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9272 default: llvm_unreachable("unexpected overflowing operator");
9275 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9276 if (CondOpcode == ISD::UMULO)
9277 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9280 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9282 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9284 if (CondOpcode == ISD::UMULO)
9285 Cond = X86Op.getValue(2);
9287 Cond = X86Op.getValue(1);
9289 CC = DAG.getConstant(X86Cond, MVT::i8);
9293 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9294 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9295 if (CondOpc == ISD::OR) {
9296 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9297 // two branches instead of an explicit OR instruction with a
9299 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9300 isX86LogicalCmp(Cmp)) {
9301 CC = Cond.getOperand(0).getOperand(0);
9302 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9303 Chain, Dest, CC, Cmp);
9304 CC = Cond.getOperand(1).getOperand(0);
9308 } else { // ISD::AND
9309 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9310 // two branches instead of an explicit AND instruction with a
9311 // separate test. However, we only do this if this block doesn't
9312 // have a fall-through edge, because this requires an explicit
9313 // jmp when the condition is false.
9314 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9315 isX86LogicalCmp(Cmp) &&
9316 Op.getNode()->hasOneUse()) {
9317 X86::CondCode CCode =
9318 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9319 CCode = X86::GetOppositeBranchCondition(CCode);
9320 CC = DAG.getConstant(CCode, MVT::i8);
9321 SDNode *User = *Op.getNode()->use_begin();
9322 // Look for an unconditional branch following this conditional branch.
9323 // We need this because we need to reverse the successors in order
9324 // to implement FCMP_OEQ.
9325 if (User->getOpcode() == ISD::BR) {
9326 SDValue FalseBB = User->getOperand(1);
9328 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9329 assert(NewBR == User);
9333 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9334 Chain, Dest, CC, Cmp);
9335 X86::CondCode CCode =
9336 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9337 CCode = X86::GetOppositeBranchCondition(CCode);
9338 CC = DAG.getConstant(CCode, MVT::i8);
9344 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9345 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9346 // It should be transformed during dag combiner except when the condition
9347 // is set by a arithmetics with overflow node.
9348 X86::CondCode CCode =
9349 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9350 CCode = X86::GetOppositeBranchCondition(CCode);
9351 CC = DAG.getConstant(CCode, MVT::i8);
9352 Cond = Cond.getOperand(0).getOperand(1);
9354 } else if (Cond.getOpcode() == ISD::SETCC &&
9355 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9356 // For FCMP_OEQ, we can emit
9357 // two branches instead of an explicit AND instruction with a
9358 // separate test. However, we only do this if this block doesn't
9359 // have a fall-through edge, because this requires an explicit
9360 // jmp when the condition is false.
9361 if (Op.getNode()->hasOneUse()) {
9362 SDNode *User = *Op.getNode()->use_begin();
9363 // Look for an unconditional branch following this conditional branch.
9364 // We need this because we need to reverse the successors in order
9365 // to implement FCMP_OEQ.
9366 if (User->getOpcode() == ISD::BR) {
9367 SDValue FalseBB = User->getOperand(1);
9369 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9370 assert(NewBR == User);
9374 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9375 Cond.getOperand(0), Cond.getOperand(1));
9376 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9377 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9378 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9379 Chain, Dest, CC, Cmp);
9380 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9385 } else if (Cond.getOpcode() == ISD::SETCC &&
9386 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9387 // For FCMP_UNE, we can emit
9388 // two branches instead of an explicit AND instruction with a
9389 // separate test. However, we only do this if this block doesn't
9390 // have a fall-through edge, because this requires an explicit
9391 // jmp when the condition is false.
9392 if (Op.getNode()->hasOneUse()) {
9393 SDNode *User = *Op.getNode()->use_begin();
9394 // Look for an unconditional branch following this conditional branch.
9395 // We need this because we need to reverse the successors in order
9396 // to implement FCMP_UNE.
9397 if (User->getOpcode() == ISD::BR) {
9398 SDValue FalseBB = User->getOperand(1);
9400 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9401 assert(NewBR == User);
9404 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9405 Cond.getOperand(0), Cond.getOperand(1));
9406 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9407 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9408 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9409 Chain, Dest, CC, Cmp);
9410 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9420 // Look pass the truncate if the high bits are known zero.
9421 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9422 Cond = Cond.getOperand(0);
9424 // We know the result of AND is compared against zero. Try to match
9426 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9427 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9428 if (NewSetCC.getNode()) {
9429 CC = NewSetCC.getOperand(0);
9430 Cond = NewSetCC.getOperand(1);
9437 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9438 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9440 Cond = ConvertCmpIfNecessary(Cond, DAG);
9441 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9442 Chain, Dest, CC, Cond);
9446 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9447 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9448 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9449 // that the guard pages used by the OS virtual memory manager are allocated in
9450 // correct sequence.
9452 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9453 SelectionDAG &DAG) const {
9454 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9455 getTargetMachine().Options.EnableSegmentedStacks) &&
9456 "This should be used only on Windows targets or when segmented stacks "
9458 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9459 DebugLoc dl = Op.getDebugLoc();
9462 SDValue Chain = Op.getOperand(0);
9463 SDValue Size = Op.getOperand(1);
9464 // FIXME: Ensure alignment here
9466 bool Is64Bit = Subtarget->is64Bit();
9467 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9469 if (getTargetMachine().Options.EnableSegmentedStacks) {
9470 MachineFunction &MF = DAG.getMachineFunction();
9471 MachineRegisterInfo &MRI = MF.getRegInfo();
9474 // The 64 bit implementation of segmented stacks needs to clobber both r10
9475 // r11. This makes it impossible to use it along with nested parameters.
9476 const Function *F = MF.getFunction();
9478 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9480 if (I->hasNestAttr())
9481 report_fatal_error("Cannot use segmented stacks with functions that "
9482 "have nested arguments.");
9485 const TargetRegisterClass *AddrRegClass =
9486 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9487 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9488 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9489 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9490 DAG.getRegister(Vreg, SPTy));
9491 SDValue Ops1[2] = { Value, Chain };
9492 return DAG.getMergeValues(Ops1, 2, dl);
9495 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9497 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9498 Flag = Chain.getValue(1);
9499 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9501 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9502 Flag = Chain.getValue(1);
9504 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9506 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9507 return DAG.getMergeValues(Ops1, 2, dl);
9511 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9512 MachineFunction &MF = DAG.getMachineFunction();
9513 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9515 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9516 DebugLoc DL = Op.getDebugLoc();
9518 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9519 // vastart just stores the address of the VarArgsFrameIndex slot into the
9520 // memory location argument.
9521 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9523 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9524 MachinePointerInfo(SV), false, false, 0);
9528 // gp_offset (0 - 6 * 8)
9529 // fp_offset (48 - 48 + 8 * 16)
9530 // overflow_arg_area (point to parameters coming in memory).
9532 SmallVector<SDValue, 8> MemOps;
9533 SDValue FIN = Op.getOperand(1);
9535 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9536 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9538 FIN, MachinePointerInfo(SV), false, false, 0);
9539 MemOps.push_back(Store);
9542 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9543 FIN, DAG.getIntPtrConstant(4));
9544 Store = DAG.getStore(Op.getOperand(0), DL,
9545 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9547 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9548 MemOps.push_back(Store);
9550 // Store ptr to overflow_arg_area
9551 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9552 FIN, DAG.getIntPtrConstant(4));
9553 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9555 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9556 MachinePointerInfo(SV, 8),
9558 MemOps.push_back(Store);
9560 // Store ptr to reg_save_area.
9561 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9562 FIN, DAG.getIntPtrConstant(8));
9563 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9565 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9566 MachinePointerInfo(SV, 16), false, false, 0);
9567 MemOps.push_back(Store);
9568 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9569 &MemOps[0], MemOps.size());
9572 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9573 assert(Subtarget->is64Bit() &&
9574 "LowerVAARG only handles 64-bit va_arg!");
9575 assert((Subtarget->isTargetLinux() ||
9576 Subtarget->isTargetDarwin()) &&
9577 "Unhandled target in LowerVAARG");
9578 assert(Op.getNode()->getNumOperands() == 4);
9579 SDValue Chain = Op.getOperand(0);
9580 SDValue SrcPtr = Op.getOperand(1);
9581 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9582 unsigned Align = Op.getConstantOperandVal(3);
9583 DebugLoc dl = Op.getDebugLoc();
9585 EVT ArgVT = Op.getNode()->getValueType(0);
9586 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9587 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9590 // Decide which area this value should be read from.
9591 // TODO: Implement the AMD64 ABI in its entirety. This simple
9592 // selection mechanism works only for the basic types.
9593 if (ArgVT == MVT::f80) {
9594 llvm_unreachable("va_arg for f80 not yet implemented");
9595 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9596 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9597 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9598 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9600 llvm_unreachable("Unhandled argument type in LowerVAARG");
9604 // Sanity Check: Make sure using fp_offset makes sense.
9605 assert(!getTargetMachine().Options.UseSoftFloat &&
9606 !(DAG.getMachineFunction()
9607 .getFunction()->getFnAttributes()
9608 .hasAttribute(Attributes::NoImplicitFloat)) &&
9609 Subtarget->hasSSE1());
9612 // Insert VAARG_64 node into the DAG
9613 // VAARG_64 returns two values: Variable Argument Address, Chain
9614 SmallVector<SDValue, 11> InstOps;
9615 InstOps.push_back(Chain);
9616 InstOps.push_back(SrcPtr);
9617 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9618 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9619 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9620 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9621 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9622 VTs, &InstOps[0], InstOps.size(),
9624 MachinePointerInfo(SV),
9629 Chain = VAARG.getValue(1);
9631 // Load the next argument and return it
9632 return DAG.getLoad(ArgVT, dl,
9635 MachinePointerInfo(),
9636 false, false, false, 0);
9639 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9640 SelectionDAG &DAG) {
9641 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9642 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9643 SDValue Chain = Op.getOperand(0);
9644 SDValue DstPtr = Op.getOperand(1);
9645 SDValue SrcPtr = Op.getOperand(2);
9646 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9647 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9648 DebugLoc DL = Op.getDebugLoc();
9650 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9651 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9653 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9656 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9657 // may or may not be a constant. Takes immediate version of shift as input.
9658 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9659 SDValue SrcOp, SDValue ShAmt,
9660 SelectionDAG &DAG) {
9661 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9663 if (isa<ConstantSDNode>(ShAmt)) {
9664 // Constant may be a TargetConstant. Use a regular constant.
9665 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9667 default: llvm_unreachable("Unknown target vector shift node");
9671 return DAG.getNode(Opc, dl, VT, SrcOp,
9672 DAG.getConstant(ShiftAmt, MVT::i32));
9676 // Change opcode to non-immediate version
9678 default: llvm_unreachable("Unknown target vector shift node");
9679 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9680 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9681 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9684 // Need to build a vector containing shift amount
9685 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9688 ShOps[1] = DAG.getConstant(0, MVT::i32);
9689 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9690 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9692 // The return type has to be a 128-bit type with the same element
9693 // type as the input type.
9694 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9695 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9697 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9698 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9701 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9702 DebugLoc dl = Op.getDebugLoc();
9703 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9705 default: return SDValue(); // Don't custom lower most intrinsics.
9706 // Comparison intrinsics.
9707 case Intrinsic::x86_sse_comieq_ss:
9708 case Intrinsic::x86_sse_comilt_ss:
9709 case Intrinsic::x86_sse_comile_ss:
9710 case Intrinsic::x86_sse_comigt_ss:
9711 case Intrinsic::x86_sse_comige_ss:
9712 case Intrinsic::x86_sse_comineq_ss:
9713 case Intrinsic::x86_sse_ucomieq_ss:
9714 case Intrinsic::x86_sse_ucomilt_ss:
9715 case Intrinsic::x86_sse_ucomile_ss:
9716 case Intrinsic::x86_sse_ucomigt_ss:
9717 case Intrinsic::x86_sse_ucomige_ss:
9718 case Intrinsic::x86_sse_ucomineq_ss:
9719 case Intrinsic::x86_sse2_comieq_sd:
9720 case Intrinsic::x86_sse2_comilt_sd:
9721 case Intrinsic::x86_sse2_comile_sd:
9722 case Intrinsic::x86_sse2_comigt_sd:
9723 case Intrinsic::x86_sse2_comige_sd:
9724 case Intrinsic::x86_sse2_comineq_sd:
9725 case Intrinsic::x86_sse2_ucomieq_sd:
9726 case Intrinsic::x86_sse2_ucomilt_sd:
9727 case Intrinsic::x86_sse2_ucomile_sd:
9728 case Intrinsic::x86_sse2_ucomigt_sd:
9729 case Intrinsic::x86_sse2_ucomige_sd:
9730 case Intrinsic::x86_sse2_ucomineq_sd: {
9734 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9735 case Intrinsic::x86_sse_comieq_ss:
9736 case Intrinsic::x86_sse2_comieq_sd:
9740 case Intrinsic::x86_sse_comilt_ss:
9741 case Intrinsic::x86_sse2_comilt_sd:
9745 case Intrinsic::x86_sse_comile_ss:
9746 case Intrinsic::x86_sse2_comile_sd:
9750 case Intrinsic::x86_sse_comigt_ss:
9751 case Intrinsic::x86_sse2_comigt_sd:
9755 case Intrinsic::x86_sse_comige_ss:
9756 case Intrinsic::x86_sse2_comige_sd:
9760 case Intrinsic::x86_sse_comineq_ss:
9761 case Intrinsic::x86_sse2_comineq_sd:
9765 case Intrinsic::x86_sse_ucomieq_ss:
9766 case Intrinsic::x86_sse2_ucomieq_sd:
9767 Opc = X86ISD::UCOMI;
9770 case Intrinsic::x86_sse_ucomilt_ss:
9771 case Intrinsic::x86_sse2_ucomilt_sd:
9772 Opc = X86ISD::UCOMI;
9775 case Intrinsic::x86_sse_ucomile_ss:
9776 case Intrinsic::x86_sse2_ucomile_sd:
9777 Opc = X86ISD::UCOMI;
9780 case Intrinsic::x86_sse_ucomigt_ss:
9781 case Intrinsic::x86_sse2_ucomigt_sd:
9782 Opc = X86ISD::UCOMI;
9785 case Intrinsic::x86_sse_ucomige_ss:
9786 case Intrinsic::x86_sse2_ucomige_sd:
9787 Opc = X86ISD::UCOMI;
9790 case Intrinsic::x86_sse_ucomineq_ss:
9791 case Intrinsic::x86_sse2_ucomineq_sd:
9792 Opc = X86ISD::UCOMI;
9797 SDValue LHS = Op.getOperand(1);
9798 SDValue RHS = Op.getOperand(2);
9799 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9800 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9801 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9802 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9803 DAG.getConstant(X86CC, MVT::i8), Cond);
9804 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9807 // Arithmetic intrinsics.
9808 case Intrinsic::x86_sse2_pmulu_dq:
9809 case Intrinsic::x86_avx2_pmulu_dq:
9810 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9811 Op.getOperand(1), Op.getOperand(2));
9813 // SSE3/AVX horizontal add/sub intrinsics
9814 case Intrinsic::x86_sse3_hadd_ps:
9815 case Intrinsic::x86_sse3_hadd_pd:
9816 case Intrinsic::x86_avx_hadd_ps_256:
9817 case Intrinsic::x86_avx_hadd_pd_256:
9818 case Intrinsic::x86_sse3_hsub_ps:
9819 case Intrinsic::x86_sse3_hsub_pd:
9820 case Intrinsic::x86_avx_hsub_ps_256:
9821 case Intrinsic::x86_avx_hsub_pd_256:
9822 case Intrinsic::x86_ssse3_phadd_w_128:
9823 case Intrinsic::x86_ssse3_phadd_d_128:
9824 case Intrinsic::x86_avx2_phadd_w:
9825 case Intrinsic::x86_avx2_phadd_d:
9826 case Intrinsic::x86_ssse3_phsub_w_128:
9827 case Intrinsic::x86_ssse3_phsub_d_128:
9828 case Intrinsic::x86_avx2_phsub_w:
9829 case Intrinsic::x86_avx2_phsub_d: {
9832 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9833 case Intrinsic::x86_sse3_hadd_ps:
9834 case Intrinsic::x86_sse3_hadd_pd:
9835 case Intrinsic::x86_avx_hadd_ps_256:
9836 case Intrinsic::x86_avx_hadd_pd_256:
9837 Opcode = X86ISD::FHADD;
9839 case Intrinsic::x86_sse3_hsub_ps:
9840 case Intrinsic::x86_sse3_hsub_pd:
9841 case Intrinsic::x86_avx_hsub_ps_256:
9842 case Intrinsic::x86_avx_hsub_pd_256:
9843 Opcode = X86ISD::FHSUB;
9845 case Intrinsic::x86_ssse3_phadd_w_128:
9846 case Intrinsic::x86_ssse3_phadd_d_128:
9847 case Intrinsic::x86_avx2_phadd_w:
9848 case Intrinsic::x86_avx2_phadd_d:
9849 Opcode = X86ISD::HADD;
9851 case Intrinsic::x86_ssse3_phsub_w_128:
9852 case Intrinsic::x86_ssse3_phsub_d_128:
9853 case Intrinsic::x86_avx2_phsub_w:
9854 case Intrinsic::x86_avx2_phsub_d:
9855 Opcode = X86ISD::HSUB;
9858 return DAG.getNode(Opcode, dl, Op.getValueType(),
9859 Op.getOperand(1), Op.getOperand(2));
9862 // AVX2 variable shift intrinsics
9863 case Intrinsic::x86_avx2_psllv_d:
9864 case Intrinsic::x86_avx2_psllv_q:
9865 case Intrinsic::x86_avx2_psllv_d_256:
9866 case Intrinsic::x86_avx2_psllv_q_256:
9867 case Intrinsic::x86_avx2_psrlv_d:
9868 case Intrinsic::x86_avx2_psrlv_q:
9869 case Intrinsic::x86_avx2_psrlv_d_256:
9870 case Intrinsic::x86_avx2_psrlv_q_256:
9871 case Intrinsic::x86_avx2_psrav_d:
9872 case Intrinsic::x86_avx2_psrav_d_256: {
9875 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9876 case Intrinsic::x86_avx2_psllv_d:
9877 case Intrinsic::x86_avx2_psllv_q:
9878 case Intrinsic::x86_avx2_psllv_d_256:
9879 case Intrinsic::x86_avx2_psllv_q_256:
9882 case Intrinsic::x86_avx2_psrlv_d:
9883 case Intrinsic::x86_avx2_psrlv_q:
9884 case Intrinsic::x86_avx2_psrlv_d_256:
9885 case Intrinsic::x86_avx2_psrlv_q_256:
9888 case Intrinsic::x86_avx2_psrav_d:
9889 case Intrinsic::x86_avx2_psrav_d_256:
9893 return DAG.getNode(Opcode, dl, Op.getValueType(),
9894 Op.getOperand(1), Op.getOperand(2));
9897 case Intrinsic::x86_ssse3_pshuf_b_128:
9898 case Intrinsic::x86_avx2_pshuf_b:
9899 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9900 Op.getOperand(1), Op.getOperand(2));
9902 case Intrinsic::x86_ssse3_psign_b_128:
9903 case Intrinsic::x86_ssse3_psign_w_128:
9904 case Intrinsic::x86_ssse3_psign_d_128:
9905 case Intrinsic::x86_avx2_psign_b:
9906 case Intrinsic::x86_avx2_psign_w:
9907 case Intrinsic::x86_avx2_psign_d:
9908 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9909 Op.getOperand(1), Op.getOperand(2));
9911 case Intrinsic::x86_sse41_insertps:
9912 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9913 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9915 case Intrinsic::x86_avx_vperm2f128_ps_256:
9916 case Intrinsic::x86_avx_vperm2f128_pd_256:
9917 case Intrinsic::x86_avx_vperm2f128_si_256:
9918 case Intrinsic::x86_avx2_vperm2i128:
9919 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9920 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9922 case Intrinsic::x86_avx2_permd:
9923 case Intrinsic::x86_avx2_permps:
9924 // Operands intentionally swapped. Mask is last operand to intrinsic,
9925 // but second operand for node/intruction.
9926 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9927 Op.getOperand(2), Op.getOperand(1));
9929 // ptest and testp intrinsics. The intrinsic these come from are designed to
9930 // return an integer value, not just an instruction so lower it to the ptest
9931 // or testp pattern and a setcc for the result.
9932 case Intrinsic::x86_sse41_ptestz:
9933 case Intrinsic::x86_sse41_ptestc:
9934 case Intrinsic::x86_sse41_ptestnzc:
9935 case Intrinsic::x86_avx_ptestz_256:
9936 case Intrinsic::x86_avx_ptestc_256:
9937 case Intrinsic::x86_avx_ptestnzc_256:
9938 case Intrinsic::x86_avx_vtestz_ps:
9939 case Intrinsic::x86_avx_vtestc_ps:
9940 case Intrinsic::x86_avx_vtestnzc_ps:
9941 case Intrinsic::x86_avx_vtestz_pd:
9942 case Intrinsic::x86_avx_vtestc_pd:
9943 case Intrinsic::x86_avx_vtestnzc_pd:
9944 case Intrinsic::x86_avx_vtestz_ps_256:
9945 case Intrinsic::x86_avx_vtestc_ps_256:
9946 case Intrinsic::x86_avx_vtestnzc_ps_256:
9947 case Intrinsic::x86_avx_vtestz_pd_256:
9948 case Intrinsic::x86_avx_vtestc_pd_256:
9949 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9950 bool IsTestPacked = false;
9953 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9954 case Intrinsic::x86_avx_vtestz_ps:
9955 case Intrinsic::x86_avx_vtestz_pd:
9956 case Intrinsic::x86_avx_vtestz_ps_256:
9957 case Intrinsic::x86_avx_vtestz_pd_256:
9958 IsTestPacked = true; // Fallthrough
9959 case Intrinsic::x86_sse41_ptestz:
9960 case Intrinsic::x86_avx_ptestz_256:
9962 X86CC = X86::COND_E;
9964 case Intrinsic::x86_avx_vtestc_ps:
9965 case Intrinsic::x86_avx_vtestc_pd:
9966 case Intrinsic::x86_avx_vtestc_ps_256:
9967 case Intrinsic::x86_avx_vtestc_pd_256:
9968 IsTestPacked = true; // Fallthrough
9969 case Intrinsic::x86_sse41_ptestc:
9970 case Intrinsic::x86_avx_ptestc_256:
9972 X86CC = X86::COND_B;
9974 case Intrinsic::x86_avx_vtestnzc_ps:
9975 case Intrinsic::x86_avx_vtestnzc_pd:
9976 case Intrinsic::x86_avx_vtestnzc_ps_256:
9977 case Intrinsic::x86_avx_vtestnzc_pd_256:
9978 IsTestPacked = true; // Fallthrough
9979 case Intrinsic::x86_sse41_ptestnzc:
9980 case Intrinsic::x86_avx_ptestnzc_256:
9982 X86CC = X86::COND_A;
9986 SDValue LHS = Op.getOperand(1);
9987 SDValue RHS = Op.getOperand(2);
9988 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9989 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9990 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9991 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9992 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9995 // SSE/AVX shift intrinsics
9996 case Intrinsic::x86_sse2_psll_w:
9997 case Intrinsic::x86_sse2_psll_d:
9998 case Intrinsic::x86_sse2_psll_q:
9999 case Intrinsic::x86_avx2_psll_w:
10000 case Intrinsic::x86_avx2_psll_d:
10001 case Intrinsic::x86_avx2_psll_q:
10002 case Intrinsic::x86_sse2_psrl_w:
10003 case Intrinsic::x86_sse2_psrl_d:
10004 case Intrinsic::x86_sse2_psrl_q:
10005 case Intrinsic::x86_avx2_psrl_w:
10006 case Intrinsic::x86_avx2_psrl_d:
10007 case Intrinsic::x86_avx2_psrl_q:
10008 case Intrinsic::x86_sse2_psra_w:
10009 case Intrinsic::x86_sse2_psra_d:
10010 case Intrinsic::x86_avx2_psra_w:
10011 case Intrinsic::x86_avx2_psra_d: {
10014 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10015 case Intrinsic::x86_sse2_psll_w:
10016 case Intrinsic::x86_sse2_psll_d:
10017 case Intrinsic::x86_sse2_psll_q:
10018 case Intrinsic::x86_avx2_psll_w:
10019 case Intrinsic::x86_avx2_psll_d:
10020 case Intrinsic::x86_avx2_psll_q:
10021 Opcode = X86ISD::VSHL;
10023 case Intrinsic::x86_sse2_psrl_w:
10024 case Intrinsic::x86_sse2_psrl_d:
10025 case Intrinsic::x86_sse2_psrl_q:
10026 case Intrinsic::x86_avx2_psrl_w:
10027 case Intrinsic::x86_avx2_psrl_d:
10028 case Intrinsic::x86_avx2_psrl_q:
10029 Opcode = X86ISD::VSRL;
10031 case Intrinsic::x86_sse2_psra_w:
10032 case Intrinsic::x86_sse2_psra_d:
10033 case Intrinsic::x86_avx2_psra_w:
10034 case Intrinsic::x86_avx2_psra_d:
10035 Opcode = X86ISD::VSRA;
10038 return DAG.getNode(Opcode, dl, Op.getValueType(),
10039 Op.getOperand(1), Op.getOperand(2));
10042 // SSE/AVX immediate shift intrinsics
10043 case Intrinsic::x86_sse2_pslli_w:
10044 case Intrinsic::x86_sse2_pslli_d:
10045 case Intrinsic::x86_sse2_pslli_q:
10046 case Intrinsic::x86_avx2_pslli_w:
10047 case Intrinsic::x86_avx2_pslli_d:
10048 case Intrinsic::x86_avx2_pslli_q:
10049 case Intrinsic::x86_sse2_psrli_w:
10050 case Intrinsic::x86_sse2_psrli_d:
10051 case Intrinsic::x86_sse2_psrli_q:
10052 case Intrinsic::x86_avx2_psrli_w:
10053 case Intrinsic::x86_avx2_psrli_d:
10054 case Intrinsic::x86_avx2_psrli_q:
10055 case Intrinsic::x86_sse2_psrai_w:
10056 case Intrinsic::x86_sse2_psrai_d:
10057 case Intrinsic::x86_avx2_psrai_w:
10058 case Intrinsic::x86_avx2_psrai_d: {
10061 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10062 case Intrinsic::x86_sse2_pslli_w:
10063 case Intrinsic::x86_sse2_pslli_d:
10064 case Intrinsic::x86_sse2_pslli_q:
10065 case Intrinsic::x86_avx2_pslli_w:
10066 case Intrinsic::x86_avx2_pslli_d:
10067 case Intrinsic::x86_avx2_pslli_q:
10068 Opcode = X86ISD::VSHLI;
10070 case Intrinsic::x86_sse2_psrli_w:
10071 case Intrinsic::x86_sse2_psrli_d:
10072 case Intrinsic::x86_sse2_psrli_q:
10073 case Intrinsic::x86_avx2_psrli_w:
10074 case Intrinsic::x86_avx2_psrli_d:
10075 case Intrinsic::x86_avx2_psrli_q:
10076 Opcode = X86ISD::VSRLI;
10078 case Intrinsic::x86_sse2_psrai_w:
10079 case Intrinsic::x86_sse2_psrai_d:
10080 case Intrinsic::x86_avx2_psrai_w:
10081 case Intrinsic::x86_avx2_psrai_d:
10082 Opcode = X86ISD::VSRAI;
10085 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10086 Op.getOperand(1), Op.getOperand(2), DAG);
10089 case Intrinsic::x86_sse42_pcmpistria128:
10090 case Intrinsic::x86_sse42_pcmpestria128:
10091 case Intrinsic::x86_sse42_pcmpistric128:
10092 case Intrinsic::x86_sse42_pcmpestric128:
10093 case Intrinsic::x86_sse42_pcmpistrio128:
10094 case Intrinsic::x86_sse42_pcmpestrio128:
10095 case Intrinsic::x86_sse42_pcmpistris128:
10096 case Intrinsic::x86_sse42_pcmpestris128:
10097 case Intrinsic::x86_sse42_pcmpistriz128:
10098 case Intrinsic::x86_sse42_pcmpestriz128: {
10102 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10103 case Intrinsic::x86_sse42_pcmpistria128:
10104 Opcode = X86ISD::PCMPISTRI;
10105 X86CC = X86::COND_A;
10107 case Intrinsic::x86_sse42_pcmpestria128:
10108 Opcode = X86ISD::PCMPESTRI;
10109 X86CC = X86::COND_A;
10111 case Intrinsic::x86_sse42_pcmpistric128:
10112 Opcode = X86ISD::PCMPISTRI;
10113 X86CC = X86::COND_B;
10115 case Intrinsic::x86_sse42_pcmpestric128:
10116 Opcode = X86ISD::PCMPESTRI;
10117 X86CC = X86::COND_B;
10119 case Intrinsic::x86_sse42_pcmpistrio128:
10120 Opcode = X86ISD::PCMPISTRI;
10121 X86CC = X86::COND_O;
10123 case Intrinsic::x86_sse42_pcmpestrio128:
10124 Opcode = X86ISD::PCMPESTRI;
10125 X86CC = X86::COND_O;
10127 case Intrinsic::x86_sse42_pcmpistris128:
10128 Opcode = X86ISD::PCMPISTRI;
10129 X86CC = X86::COND_S;
10131 case Intrinsic::x86_sse42_pcmpestris128:
10132 Opcode = X86ISD::PCMPESTRI;
10133 X86CC = X86::COND_S;
10135 case Intrinsic::x86_sse42_pcmpistriz128:
10136 Opcode = X86ISD::PCMPISTRI;
10137 X86CC = X86::COND_E;
10139 case Intrinsic::x86_sse42_pcmpestriz128:
10140 Opcode = X86ISD::PCMPESTRI;
10141 X86CC = X86::COND_E;
10144 SmallVector<SDValue, 5> NewOps;
10145 NewOps.append(Op->op_begin()+1, Op->op_end());
10146 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10147 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10148 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10149 DAG.getConstant(X86CC, MVT::i8),
10150 SDValue(PCMP.getNode(), 1));
10151 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10154 case Intrinsic::x86_sse42_pcmpistri128:
10155 case Intrinsic::x86_sse42_pcmpestri128: {
10157 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10158 Opcode = X86ISD::PCMPISTRI;
10160 Opcode = X86ISD::PCMPESTRI;
10162 SmallVector<SDValue, 5> NewOps;
10163 NewOps.append(Op->op_begin()+1, Op->op_end());
10164 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10165 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10167 case Intrinsic::x86_fma_vfmadd_ps:
10168 case Intrinsic::x86_fma_vfmadd_pd:
10169 case Intrinsic::x86_fma_vfmsub_ps:
10170 case Intrinsic::x86_fma_vfmsub_pd:
10171 case Intrinsic::x86_fma_vfnmadd_ps:
10172 case Intrinsic::x86_fma_vfnmadd_pd:
10173 case Intrinsic::x86_fma_vfnmsub_ps:
10174 case Intrinsic::x86_fma_vfnmsub_pd:
10175 case Intrinsic::x86_fma_vfmaddsub_ps:
10176 case Intrinsic::x86_fma_vfmaddsub_pd:
10177 case Intrinsic::x86_fma_vfmsubadd_ps:
10178 case Intrinsic::x86_fma_vfmsubadd_pd:
10179 case Intrinsic::x86_fma_vfmadd_ps_256:
10180 case Intrinsic::x86_fma_vfmadd_pd_256:
10181 case Intrinsic::x86_fma_vfmsub_ps_256:
10182 case Intrinsic::x86_fma_vfmsub_pd_256:
10183 case Intrinsic::x86_fma_vfnmadd_ps_256:
10184 case Intrinsic::x86_fma_vfnmadd_pd_256:
10185 case Intrinsic::x86_fma_vfnmsub_ps_256:
10186 case Intrinsic::x86_fma_vfnmsub_pd_256:
10187 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10188 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10189 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10190 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10193 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10194 case Intrinsic::x86_fma_vfmadd_ps:
10195 case Intrinsic::x86_fma_vfmadd_pd:
10196 case Intrinsic::x86_fma_vfmadd_ps_256:
10197 case Intrinsic::x86_fma_vfmadd_pd_256:
10198 Opc = X86ISD::FMADD;
10200 case Intrinsic::x86_fma_vfmsub_ps:
10201 case Intrinsic::x86_fma_vfmsub_pd:
10202 case Intrinsic::x86_fma_vfmsub_ps_256:
10203 case Intrinsic::x86_fma_vfmsub_pd_256:
10204 Opc = X86ISD::FMSUB;
10206 case Intrinsic::x86_fma_vfnmadd_ps:
10207 case Intrinsic::x86_fma_vfnmadd_pd:
10208 case Intrinsic::x86_fma_vfnmadd_ps_256:
10209 case Intrinsic::x86_fma_vfnmadd_pd_256:
10210 Opc = X86ISD::FNMADD;
10212 case Intrinsic::x86_fma_vfnmsub_ps:
10213 case Intrinsic::x86_fma_vfnmsub_pd:
10214 case Intrinsic::x86_fma_vfnmsub_ps_256:
10215 case Intrinsic::x86_fma_vfnmsub_pd_256:
10216 Opc = X86ISD::FNMSUB;
10218 case Intrinsic::x86_fma_vfmaddsub_ps:
10219 case Intrinsic::x86_fma_vfmaddsub_pd:
10220 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10221 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10222 Opc = X86ISD::FMADDSUB;
10224 case Intrinsic::x86_fma_vfmsubadd_ps:
10225 case Intrinsic::x86_fma_vfmsubadd_pd:
10226 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10227 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10228 Opc = X86ISD::FMSUBADD;
10232 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10233 Op.getOperand(2), Op.getOperand(3));
10238 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10239 DebugLoc dl = Op.getDebugLoc();
10240 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10242 default: return SDValue(); // Don't custom lower most intrinsics.
10244 // RDRAND intrinsics.
10245 case Intrinsic::x86_rdrand_16:
10246 case Intrinsic::x86_rdrand_32:
10247 case Intrinsic::x86_rdrand_64: {
10248 // Emit the node with the right value type.
10249 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10250 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10252 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10253 // return the value from Rand, which is always 0, casted to i32.
10254 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10255 DAG.getConstant(1, Op->getValueType(1)),
10256 DAG.getConstant(X86::COND_B, MVT::i32),
10257 SDValue(Result.getNode(), 1) };
10258 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10259 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10262 // Return { result, isValid, chain }.
10263 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10264 SDValue(Result.getNode(), 2));
10269 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10270 SelectionDAG &DAG) const {
10271 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10272 MFI->setReturnAddressIsTaken(true);
10274 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10275 DebugLoc dl = Op.getDebugLoc();
10278 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10280 DAG.getConstant(TD->getPointerSize(),
10281 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10282 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10283 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10284 FrameAddr, Offset),
10285 MachinePointerInfo(), false, false, false, 0);
10288 // Just load the return address.
10289 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10290 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10291 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10294 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10295 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10296 MFI->setFrameAddressIsTaken(true);
10298 EVT VT = Op.getValueType();
10299 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10300 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10301 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10302 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10304 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10305 MachinePointerInfo(),
10306 false, false, false, 0);
10310 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10311 SelectionDAG &DAG) const {
10312 return DAG.getIntPtrConstant(2*TD->getPointerSize());
10315 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10316 SDValue Chain = Op.getOperand(0);
10317 SDValue Offset = Op.getOperand(1);
10318 SDValue Handler = Op.getOperand(2);
10319 DebugLoc dl = Op.getDebugLoc();
10321 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10322 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10324 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10326 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10327 DAG.getIntPtrConstant(TD->getPointerSize()));
10328 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10329 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10331 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10333 return DAG.getNode(X86ISD::EH_RETURN, dl,
10335 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10338 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10339 return Op.getOperand(0);
10342 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10343 SelectionDAG &DAG) const {
10344 SDValue Root = Op.getOperand(0);
10345 SDValue Trmp = Op.getOperand(1); // trampoline
10346 SDValue FPtr = Op.getOperand(2); // nested function
10347 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10348 DebugLoc dl = Op.getDebugLoc();
10350 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10351 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10353 if (Subtarget->is64Bit()) {
10354 SDValue OutChains[6];
10356 // Large code-model.
10357 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10358 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10360 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10361 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10363 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10365 // Load the pointer to the nested function into R11.
10366 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10367 SDValue Addr = Trmp;
10368 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10369 Addr, MachinePointerInfo(TrmpAddr),
10372 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10373 DAG.getConstant(2, MVT::i64));
10374 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10375 MachinePointerInfo(TrmpAddr, 2),
10378 // Load the 'nest' parameter value into R10.
10379 // R10 is specified in X86CallingConv.td
10380 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10381 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10382 DAG.getConstant(10, MVT::i64));
10383 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10384 Addr, MachinePointerInfo(TrmpAddr, 10),
10387 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10388 DAG.getConstant(12, MVT::i64));
10389 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10390 MachinePointerInfo(TrmpAddr, 12),
10393 // Jump to the nested function.
10394 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10395 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10396 DAG.getConstant(20, MVT::i64));
10397 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10398 Addr, MachinePointerInfo(TrmpAddr, 20),
10401 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10402 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10403 DAG.getConstant(22, MVT::i64));
10404 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10405 MachinePointerInfo(TrmpAddr, 22),
10408 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10410 const Function *Func =
10411 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10412 CallingConv::ID CC = Func->getCallingConv();
10417 llvm_unreachable("Unsupported calling convention");
10418 case CallingConv::C:
10419 case CallingConv::X86_StdCall: {
10420 // Pass 'nest' parameter in ECX.
10421 // Must be kept in sync with X86CallingConv.td
10422 NestReg = X86::ECX;
10424 // Check that ECX wasn't needed by an 'inreg' parameter.
10425 FunctionType *FTy = Func->getFunctionType();
10426 const AttrListPtr &Attrs = Func->getAttributes();
10428 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10429 unsigned InRegCount = 0;
10432 for (FunctionType::param_iterator I = FTy->param_begin(),
10433 E = FTy->param_end(); I != E; ++I, ++Idx)
10434 if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10435 // FIXME: should only count parameters that are lowered to integers.
10436 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10438 if (InRegCount > 2) {
10439 report_fatal_error("Nest register in use - reduce number of inreg"
10445 case CallingConv::X86_FastCall:
10446 case CallingConv::X86_ThisCall:
10447 case CallingConv::Fast:
10448 // Pass 'nest' parameter in EAX.
10449 // Must be kept in sync with X86CallingConv.td
10450 NestReg = X86::EAX;
10454 SDValue OutChains[4];
10455 SDValue Addr, Disp;
10457 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10458 DAG.getConstant(10, MVT::i32));
10459 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10461 // This is storing the opcode for MOV32ri.
10462 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10463 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10464 OutChains[0] = DAG.getStore(Root, dl,
10465 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10466 Trmp, MachinePointerInfo(TrmpAddr),
10469 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10470 DAG.getConstant(1, MVT::i32));
10471 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10472 MachinePointerInfo(TrmpAddr, 1),
10475 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10476 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10477 DAG.getConstant(5, MVT::i32));
10478 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10479 MachinePointerInfo(TrmpAddr, 5),
10482 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10483 DAG.getConstant(6, MVT::i32));
10484 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10485 MachinePointerInfo(TrmpAddr, 6),
10488 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10492 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10493 SelectionDAG &DAG) const {
10495 The rounding mode is in bits 11:10 of FPSR, and has the following
10497 00 Round to nearest
10502 FLT_ROUNDS, on the other hand, expects the following:
10509 To perform the conversion, we do:
10510 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10513 MachineFunction &MF = DAG.getMachineFunction();
10514 const TargetMachine &TM = MF.getTarget();
10515 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10516 unsigned StackAlignment = TFI.getStackAlignment();
10517 EVT VT = Op.getValueType();
10518 DebugLoc DL = Op.getDebugLoc();
10520 // Save FP Control Word to stack slot
10521 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10522 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10525 MachineMemOperand *MMO =
10526 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10527 MachineMemOperand::MOStore, 2, 2);
10529 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10530 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10531 DAG.getVTList(MVT::Other),
10532 Ops, 2, MVT::i16, MMO);
10534 // Load FP Control Word from stack slot
10535 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10536 MachinePointerInfo(), false, false, false, 0);
10538 // Transform as necessary
10540 DAG.getNode(ISD::SRL, DL, MVT::i16,
10541 DAG.getNode(ISD::AND, DL, MVT::i16,
10542 CWD, DAG.getConstant(0x800, MVT::i16)),
10543 DAG.getConstant(11, MVT::i8));
10545 DAG.getNode(ISD::SRL, DL, MVT::i16,
10546 DAG.getNode(ISD::AND, DL, MVT::i16,
10547 CWD, DAG.getConstant(0x400, MVT::i16)),
10548 DAG.getConstant(9, MVT::i8));
10551 DAG.getNode(ISD::AND, DL, MVT::i16,
10552 DAG.getNode(ISD::ADD, DL, MVT::i16,
10553 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10554 DAG.getConstant(1, MVT::i16)),
10555 DAG.getConstant(3, MVT::i16));
10558 return DAG.getNode((VT.getSizeInBits() < 16 ?
10559 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10562 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10563 EVT VT = Op.getValueType();
10565 unsigned NumBits = VT.getSizeInBits();
10566 DebugLoc dl = Op.getDebugLoc();
10568 Op = Op.getOperand(0);
10569 if (VT == MVT::i8) {
10570 // Zero extend to i32 since there is not an i8 bsr.
10572 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10575 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10576 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10577 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10579 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10582 DAG.getConstant(NumBits+NumBits-1, OpVT),
10583 DAG.getConstant(X86::COND_E, MVT::i8),
10586 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10588 // Finally xor with NumBits-1.
10589 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10592 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10596 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10597 EVT VT = Op.getValueType();
10599 unsigned NumBits = VT.getSizeInBits();
10600 DebugLoc dl = Op.getDebugLoc();
10602 Op = Op.getOperand(0);
10603 if (VT == MVT::i8) {
10604 // Zero extend to i32 since there is not an i8 bsr.
10606 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10609 // Issue a bsr (scan bits in reverse).
10610 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10611 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10613 // And xor with NumBits-1.
10614 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10617 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10621 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10622 EVT VT = Op.getValueType();
10623 unsigned NumBits = VT.getSizeInBits();
10624 DebugLoc dl = Op.getDebugLoc();
10625 Op = Op.getOperand(0);
10627 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10628 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10629 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10631 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10634 DAG.getConstant(NumBits, VT),
10635 DAG.getConstant(X86::COND_E, MVT::i8),
10638 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10641 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10642 // ones, and then concatenate the result back.
10643 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10644 EVT VT = Op.getValueType();
10646 assert(VT.is256BitVector() && VT.isInteger() &&
10647 "Unsupported value type for operation");
10649 unsigned NumElems = VT.getVectorNumElements();
10650 DebugLoc dl = Op.getDebugLoc();
10652 // Extract the LHS vectors
10653 SDValue LHS = Op.getOperand(0);
10654 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10655 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10657 // Extract the RHS vectors
10658 SDValue RHS = Op.getOperand(1);
10659 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10660 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10662 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10663 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10665 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10666 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10667 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10670 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10671 assert(Op.getValueType().is256BitVector() &&
10672 Op.getValueType().isInteger() &&
10673 "Only handle AVX 256-bit vector integer operation");
10674 return Lower256IntArith(Op, DAG);
10677 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10678 assert(Op.getValueType().is256BitVector() &&
10679 Op.getValueType().isInteger() &&
10680 "Only handle AVX 256-bit vector integer operation");
10681 return Lower256IntArith(Op, DAG);
10684 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10685 SelectionDAG &DAG) {
10686 EVT VT = Op.getValueType();
10688 // Decompose 256-bit ops into smaller 128-bit ops.
10689 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10690 return Lower256IntArith(Op, DAG);
10692 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10693 "Only know how to lower V2I64/V4I64 multiply");
10695 DebugLoc dl = Op.getDebugLoc();
10697 // Ahi = psrlqi(a, 32);
10698 // Bhi = psrlqi(b, 32);
10700 // AloBlo = pmuludq(a, b);
10701 // AloBhi = pmuludq(a, Bhi);
10702 // AhiBlo = pmuludq(Ahi, b);
10704 // AloBhi = psllqi(AloBhi, 32);
10705 // AhiBlo = psllqi(AhiBlo, 32);
10706 // return AloBlo + AloBhi + AhiBlo;
10708 SDValue A = Op.getOperand(0);
10709 SDValue B = Op.getOperand(1);
10711 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10713 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10714 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10716 // Bit cast to 32-bit vectors for MULUDQ
10717 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10718 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10719 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10720 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10721 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10723 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10724 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10725 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10727 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10728 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10730 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10731 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10734 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10736 EVT VT = Op.getValueType();
10737 DebugLoc dl = Op.getDebugLoc();
10738 SDValue R = Op.getOperand(0);
10739 SDValue Amt = Op.getOperand(1);
10740 LLVMContext *Context = DAG.getContext();
10742 if (!Subtarget->hasSSE2())
10745 // Optimize shl/srl/sra with constant shift amount.
10746 if (isSplatVector(Amt.getNode())) {
10747 SDValue SclrAmt = Amt->getOperand(0);
10748 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10749 uint64_t ShiftAmt = C->getZExtValue();
10751 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10752 (Subtarget->hasAVX2() &&
10753 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10754 if (Op.getOpcode() == ISD::SHL)
10755 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10756 DAG.getConstant(ShiftAmt, MVT::i32));
10757 if (Op.getOpcode() == ISD::SRL)
10758 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10759 DAG.getConstant(ShiftAmt, MVT::i32));
10760 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10761 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10762 DAG.getConstant(ShiftAmt, MVT::i32));
10765 if (VT == MVT::v16i8) {
10766 if (Op.getOpcode() == ISD::SHL) {
10767 // Make a large shift.
10768 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10769 DAG.getConstant(ShiftAmt, MVT::i32));
10770 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10771 // Zero out the rightmost bits.
10772 SmallVector<SDValue, 16> V(16,
10773 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10775 return DAG.getNode(ISD::AND, dl, VT, SHL,
10776 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10778 if (Op.getOpcode() == ISD::SRL) {
10779 // Make a large shift.
10780 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10781 DAG.getConstant(ShiftAmt, MVT::i32));
10782 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10783 // Zero out the leftmost bits.
10784 SmallVector<SDValue, 16> V(16,
10785 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10787 return DAG.getNode(ISD::AND, dl, VT, SRL,
10788 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10790 if (Op.getOpcode() == ISD::SRA) {
10791 if (ShiftAmt == 7) {
10792 // R s>> 7 === R s< 0
10793 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10794 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10797 // R s>> a === ((R u>> a) ^ m) - m
10798 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10799 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10801 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10802 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10803 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10806 llvm_unreachable("Unknown shift opcode.");
10809 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10810 if (Op.getOpcode() == ISD::SHL) {
10811 // Make a large shift.
10812 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10813 DAG.getConstant(ShiftAmt, MVT::i32));
10814 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10815 // Zero out the rightmost bits.
10816 SmallVector<SDValue, 32> V(32,
10817 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10819 return DAG.getNode(ISD::AND, dl, VT, SHL,
10820 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10822 if (Op.getOpcode() == ISD::SRL) {
10823 // Make a large shift.
10824 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10825 DAG.getConstant(ShiftAmt, MVT::i32));
10826 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10827 // Zero out the leftmost bits.
10828 SmallVector<SDValue, 32> V(32,
10829 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10831 return DAG.getNode(ISD::AND, dl, VT, SRL,
10832 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10834 if (Op.getOpcode() == ISD::SRA) {
10835 if (ShiftAmt == 7) {
10836 // R s>> 7 === R s< 0
10837 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10838 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10841 // R s>> a === ((R u>> a) ^ m) - m
10842 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10843 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10845 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10846 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10847 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10850 llvm_unreachable("Unknown shift opcode.");
10855 // Lower SHL with variable shift amount.
10856 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10857 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10858 DAG.getConstant(23, MVT::i32));
10860 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10861 Constant *C = ConstantDataVector::get(*Context, CV);
10862 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10863 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10864 MachinePointerInfo::getConstantPool(),
10865 false, false, false, 16);
10867 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10868 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10869 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10870 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10872 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10873 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10876 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10877 DAG.getConstant(5, MVT::i32));
10878 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10880 // Turn 'a' into a mask suitable for VSELECT
10881 SDValue VSelM = DAG.getConstant(0x80, VT);
10882 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10883 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10885 SDValue CM1 = DAG.getConstant(0x0f, VT);
10886 SDValue CM2 = DAG.getConstant(0x3f, VT);
10888 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10889 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10890 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10891 DAG.getConstant(4, MVT::i32), DAG);
10892 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10893 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10896 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10897 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10898 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10900 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10901 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10902 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10903 DAG.getConstant(2, MVT::i32), DAG);
10904 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10905 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10908 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10909 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10910 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10912 // return VSELECT(r, r+r, a);
10913 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10914 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10918 // Decompose 256-bit shifts into smaller 128-bit shifts.
10919 if (VT.is256BitVector()) {
10920 unsigned NumElems = VT.getVectorNumElements();
10921 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10922 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10924 // Extract the two vectors
10925 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10926 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10928 // Recreate the shift amount vectors
10929 SDValue Amt1, Amt2;
10930 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10931 // Constant shift amount
10932 SmallVector<SDValue, 4> Amt1Csts;
10933 SmallVector<SDValue, 4> Amt2Csts;
10934 for (unsigned i = 0; i != NumElems/2; ++i)
10935 Amt1Csts.push_back(Amt->getOperand(i));
10936 for (unsigned i = NumElems/2; i != NumElems; ++i)
10937 Amt2Csts.push_back(Amt->getOperand(i));
10939 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10940 &Amt1Csts[0], NumElems/2);
10941 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10942 &Amt2Csts[0], NumElems/2);
10944 // Variable shift amount
10945 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10946 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10949 // Issue new vector shifts for the smaller types
10950 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10951 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10953 // Concatenate the result back
10954 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10960 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
10961 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10962 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10963 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10964 // has only one use.
10965 SDNode *N = Op.getNode();
10966 SDValue LHS = N->getOperand(0);
10967 SDValue RHS = N->getOperand(1);
10968 unsigned BaseOp = 0;
10970 DebugLoc DL = Op.getDebugLoc();
10971 switch (Op.getOpcode()) {
10972 default: llvm_unreachable("Unknown ovf instruction!");
10974 // A subtract of one will be selected as a INC. Note that INC doesn't
10975 // set CF, so we can't do this for UADDO.
10976 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10978 BaseOp = X86ISD::INC;
10979 Cond = X86::COND_O;
10982 BaseOp = X86ISD::ADD;
10983 Cond = X86::COND_O;
10986 BaseOp = X86ISD::ADD;
10987 Cond = X86::COND_B;
10990 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10991 // set CF, so we can't do this for USUBO.
10992 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10994 BaseOp = X86ISD::DEC;
10995 Cond = X86::COND_O;
10998 BaseOp = X86ISD::SUB;
10999 Cond = X86::COND_O;
11002 BaseOp = X86ISD::SUB;
11003 Cond = X86::COND_B;
11006 BaseOp = X86ISD::SMUL;
11007 Cond = X86::COND_O;
11009 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11010 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11012 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11015 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11016 DAG.getConstant(X86::COND_O, MVT::i32),
11017 SDValue(Sum.getNode(), 2));
11019 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11023 // Also sets EFLAGS.
11024 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11025 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11028 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11029 DAG.getConstant(Cond, MVT::i32),
11030 SDValue(Sum.getNode(), 1));
11032 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11035 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11036 SelectionDAG &DAG) const {
11037 DebugLoc dl = Op.getDebugLoc();
11038 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11039 EVT VT = Op.getValueType();
11041 if (!Subtarget->hasSSE2() || !VT.isVector())
11044 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11045 ExtraVT.getScalarType().getSizeInBits();
11046 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11048 switch (VT.getSimpleVT().SimpleTy) {
11049 default: return SDValue();
11052 if (!Subtarget->hasAVX())
11054 if (!Subtarget->hasAVX2()) {
11055 // needs to be split
11056 unsigned NumElems = VT.getVectorNumElements();
11058 // Extract the LHS vectors
11059 SDValue LHS = Op.getOperand(0);
11060 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11061 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11063 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11064 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11066 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11067 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11068 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11070 SDValue Extra = DAG.getValueType(ExtraVT);
11072 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11073 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11075 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11080 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11081 Op.getOperand(0), ShAmt, DAG);
11082 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11088 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11089 SelectionDAG &DAG) {
11090 DebugLoc dl = Op.getDebugLoc();
11092 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11093 // There isn't any reason to disable it if the target processor supports it.
11094 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11095 SDValue Chain = Op.getOperand(0);
11096 SDValue Zero = DAG.getConstant(0, MVT::i32);
11098 DAG.getRegister(X86::ESP, MVT::i32), // Base
11099 DAG.getTargetConstant(1, MVT::i8), // Scale
11100 DAG.getRegister(0, MVT::i32), // Index
11101 DAG.getTargetConstant(0, MVT::i32), // Disp
11102 DAG.getRegister(0, MVT::i32), // Segment.
11107 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11108 array_lengthof(Ops));
11109 return SDValue(Res, 0);
11112 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11114 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11116 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11117 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11118 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11119 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11121 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11122 if (!Op1 && !Op2 && !Op3 && Op4)
11123 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11125 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11126 if (Op1 && !Op2 && !Op3 && !Op4)
11127 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11129 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11131 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11134 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11135 SelectionDAG &DAG) {
11136 DebugLoc dl = Op.getDebugLoc();
11137 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11138 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11139 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11140 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11142 // The only fence that needs an instruction is a sequentially-consistent
11143 // cross-thread fence.
11144 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11145 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11146 // no-sse2). There isn't any reason to disable it if the target processor
11148 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11149 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11151 SDValue Chain = Op.getOperand(0);
11152 SDValue Zero = DAG.getConstant(0, MVT::i32);
11154 DAG.getRegister(X86::ESP, MVT::i32), // Base
11155 DAG.getTargetConstant(1, MVT::i8), // Scale
11156 DAG.getRegister(0, MVT::i32), // Index
11157 DAG.getTargetConstant(0, MVT::i32), // Disp
11158 DAG.getRegister(0, MVT::i32), // Segment.
11163 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11164 array_lengthof(Ops));
11165 return SDValue(Res, 0);
11168 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11169 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11173 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11174 SelectionDAG &DAG) {
11175 EVT T = Op.getValueType();
11176 DebugLoc DL = Op.getDebugLoc();
11179 switch(T.getSimpleVT().SimpleTy) {
11180 default: llvm_unreachable("Invalid value type!");
11181 case MVT::i8: Reg = X86::AL; size = 1; break;
11182 case MVT::i16: Reg = X86::AX; size = 2; break;
11183 case MVT::i32: Reg = X86::EAX; size = 4; break;
11185 assert(Subtarget->is64Bit() && "Node not type legal!");
11186 Reg = X86::RAX; size = 8;
11189 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11190 Op.getOperand(2), SDValue());
11191 SDValue Ops[] = { cpIn.getValue(0),
11194 DAG.getTargetConstant(size, MVT::i8),
11195 cpIn.getValue(1) };
11196 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11197 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11198 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11201 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11205 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11206 SelectionDAG &DAG) {
11207 assert(Subtarget->is64Bit() && "Result not type legalized?");
11208 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11209 SDValue TheChain = Op.getOperand(0);
11210 DebugLoc dl = Op.getDebugLoc();
11211 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11212 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11213 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11215 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11216 DAG.getConstant(32, MVT::i8));
11218 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11221 return DAG.getMergeValues(Ops, 2, dl);
11224 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11225 EVT SrcVT = Op.getOperand(0).getValueType();
11226 EVT DstVT = Op.getValueType();
11227 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11228 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11229 assert((DstVT == MVT::i64 ||
11230 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11231 "Unexpected custom BITCAST");
11232 // i64 <=> MMX conversions are Legal.
11233 if (SrcVT==MVT::i64 && DstVT.isVector())
11235 if (DstVT==MVT::i64 && SrcVT.isVector())
11237 // MMX <=> MMX conversions are Legal.
11238 if (SrcVT.isVector() && DstVT.isVector())
11240 // All other conversions need to be expanded.
11244 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11245 SDNode *Node = Op.getNode();
11246 DebugLoc dl = Node->getDebugLoc();
11247 EVT T = Node->getValueType(0);
11248 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11249 DAG.getConstant(0, T), Node->getOperand(2));
11250 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11251 cast<AtomicSDNode>(Node)->getMemoryVT(),
11252 Node->getOperand(0),
11253 Node->getOperand(1), negOp,
11254 cast<AtomicSDNode>(Node)->getSrcValue(),
11255 cast<AtomicSDNode>(Node)->getAlignment(),
11256 cast<AtomicSDNode>(Node)->getOrdering(),
11257 cast<AtomicSDNode>(Node)->getSynchScope());
11260 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11261 SDNode *Node = Op.getNode();
11262 DebugLoc dl = Node->getDebugLoc();
11263 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11265 // Convert seq_cst store -> xchg
11266 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11267 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11268 // (The only way to get a 16-byte store is cmpxchg16b)
11269 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11270 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11271 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11272 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11273 cast<AtomicSDNode>(Node)->getMemoryVT(),
11274 Node->getOperand(0),
11275 Node->getOperand(1), Node->getOperand(2),
11276 cast<AtomicSDNode>(Node)->getMemOperand(),
11277 cast<AtomicSDNode>(Node)->getOrdering(),
11278 cast<AtomicSDNode>(Node)->getSynchScope());
11279 return Swap.getValue(1);
11281 // Other atomic stores have a simple pattern.
11285 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11286 EVT VT = Op.getNode()->getValueType(0);
11288 // Let legalize expand this if it isn't a legal type yet.
11289 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11292 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11295 bool ExtraOp = false;
11296 switch (Op.getOpcode()) {
11297 default: llvm_unreachable("Invalid code");
11298 case ISD::ADDC: Opc = X86ISD::ADD; break;
11299 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11300 case ISD::SUBC: Opc = X86ISD::SUB; break;
11301 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11305 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11307 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11308 Op.getOperand(1), Op.getOperand(2));
11311 /// LowerOperation - Provide custom lowering hooks for some operations.
11313 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11314 switch (Op.getOpcode()) {
11315 default: llvm_unreachable("Should not custom lower this!");
11316 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11317 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11318 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11319 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11320 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11321 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11322 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11323 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11324 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11325 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11326 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11327 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11328 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11329 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11330 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11331 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11332 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11333 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11334 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11335 case ISD::SHL_PARTS:
11336 case ISD::SRA_PARTS:
11337 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11338 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11339 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11340 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11341 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11342 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11343 case ISD::FABS: return LowerFABS(Op, DAG);
11344 case ISD::FNEG: return LowerFNEG(Op, DAG);
11345 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11346 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11347 case ISD::SETCC: return LowerSETCC(Op, DAG);
11348 case ISD::SELECT: return LowerSELECT(Op, DAG);
11349 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11350 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11351 case ISD::VASTART: return LowerVASTART(Op, DAG);
11352 case ISD::VAARG: return LowerVAARG(Op, DAG);
11353 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11354 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11355 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11356 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11357 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11358 case ISD::FRAME_TO_ARGS_OFFSET:
11359 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11360 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11361 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11362 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11363 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11364 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11365 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11366 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11367 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11368 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11371 case ISD::SHL: return LowerShift(Op, DAG);
11377 case ISD::UMULO: return LowerXALUO(Op, DAG);
11378 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11379 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11383 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11384 case ISD::ADD: return LowerADD(Op, DAG);
11385 case ISD::SUB: return LowerSUB(Op, DAG);
11389 static void ReplaceATOMIC_LOAD(SDNode *Node,
11390 SmallVectorImpl<SDValue> &Results,
11391 SelectionDAG &DAG) {
11392 DebugLoc dl = Node->getDebugLoc();
11393 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11395 // Convert wide load -> cmpxchg8b/cmpxchg16b
11396 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11397 // (The only way to get a 16-byte load is cmpxchg16b)
11398 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11399 SDValue Zero = DAG.getConstant(0, VT);
11400 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11401 Node->getOperand(0),
11402 Node->getOperand(1), Zero, Zero,
11403 cast<AtomicSDNode>(Node)->getMemOperand(),
11404 cast<AtomicSDNode>(Node)->getOrdering(),
11405 cast<AtomicSDNode>(Node)->getSynchScope());
11406 Results.push_back(Swap.getValue(0));
11407 Results.push_back(Swap.getValue(1));
11411 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11412 SelectionDAG &DAG, unsigned NewOp) {
11413 DebugLoc dl = Node->getDebugLoc();
11414 assert (Node->getValueType(0) == MVT::i64 &&
11415 "Only know how to expand i64 atomics");
11417 SDValue Chain = Node->getOperand(0);
11418 SDValue In1 = Node->getOperand(1);
11419 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11420 Node->getOperand(2), DAG.getIntPtrConstant(0));
11421 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11422 Node->getOperand(2), DAG.getIntPtrConstant(1));
11423 SDValue Ops[] = { Chain, In1, In2L, In2H };
11424 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11426 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11427 cast<MemSDNode>(Node)->getMemOperand());
11428 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11429 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11430 Results.push_back(Result.getValue(2));
11433 /// ReplaceNodeResults - Replace a node with an illegal result type
11434 /// with a new node built out of custom code.
11435 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11436 SmallVectorImpl<SDValue>&Results,
11437 SelectionDAG &DAG) const {
11438 DebugLoc dl = N->getDebugLoc();
11439 switch (N->getOpcode()) {
11441 llvm_unreachable("Do not know how to custom type legalize this operation!");
11442 case ISD::SIGN_EXTEND_INREG:
11447 // We don't want to expand or promote these.
11449 case ISD::FP_TO_SINT:
11450 case ISD::FP_TO_UINT: {
11451 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11453 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11456 std::pair<SDValue,SDValue> Vals =
11457 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11458 SDValue FIST = Vals.first, StackSlot = Vals.second;
11459 if (FIST.getNode() != 0) {
11460 EVT VT = N->getValueType(0);
11461 // Return a load from the stack slot.
11462 if (StackSlot.getNode() != 0)
11463 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11464 MachinePointerInfo(),
11465 false, false, false, 0));
11467 Results.push_back(FIST);
11471 case ISD::READCYCLECOUNTER: {
11472 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11473 SDValue TheChain = N->getOperand(0);
11474 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11475 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11477 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11479 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11480 SDValue Ops[] = { eax, edx };
11481 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11482 Results.push_back(edx.getValue(1));
11485 case ISD::ATOMIC_CMP_SWAP: {
11486 EVT T = N->getValueType(0);
11487 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11488 bool Regs64bit = T == MVT::i128;
11489 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11490 SDValue cpInL, cpInH;
11491 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11492 DAG.getConstant(0, HalfT));
11493 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11494 DAG.getConstant(1, HalfT));
11495 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11496 Regs64bit ? X86::RAX : X86::EAX,
11498 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11499 Regs64bit ? X86::RDX : X86::EDX,
11500 cpInH, cpInL.getValue(1));
11501 SDValue swapInL, swapInH;
11502 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11503 DAG.getConstant(0, HalfT));
11504 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11505 DAG.getConstant(1, HalfT));
11506 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11507 Regs64bit ? X86::RBX : X86::EBX,
11508 swapInL, cpInH.getValue(1));
11509 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11510 Regs64bit ? X86::RCX : X86::ECX,
11511 swapInH, swapInL.getValue(1));
11512 SDValue Ops[] = { swapInH.getValue(0),
11514 swapInH.getValue(1) };
11515 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11516 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11517 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11518 X86ISD::LCMPXCHG8_DAG;
11519 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11521 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11522 Regs64bit ? X86::RAX : X86::EAX,
11523 HalfT, Result.getValue(1));
11524 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11525 Regs64bit ? X86::RDX : X86::EDX,
11526 HalfT, cpOutL.getValue(2));
11527 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11528 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11529 Results.push_back(cpOutH.getValue(1));
11532 case ISD::ATOMIC_LOAD_ADD:
11533 case ISD::ATOMIC_LOAD_AND:
11534 case ISD::ATOMIC_LOAD_NAND:
11535 case ISD::ATOMIC_LOAD_OR:
11536 case ISD::ATOMIC_LOAD_SUB:
11537 case ISD::ATOMIC_LOAD_XOR:
11538 case ISD::ATOMIC_LOAD_MAX:
11539 case ISD::ATOMIC_LOAD_MIN:
11540 case ISD::ATOMIC_LOAD_UMAX:
11541 case ISD::ATOMIC_LOAD_UMIN:
11542 case ISD::ATOMIC_SWAP: {
11544 switch (N->getOpcode()) {
11545 default: llvm_unreachable("Unexpected opcode");
11546 case ISD::ATOMIC_LOAD_ADD:
11547 Opc = X86ISD::ATOMADD64_DAG;
11549 case ISD::ATOMIC_LOAD_AND:
11550 Opc = X86ISD::ATOMAND64_DAG;
11552 case ISD::ATOMIC_LOAD_NAND:
11553 Opc = X86ISD::ATOMNAND64_DAG;
11555 case ISD::ATOMIC_LOAD_OR:
11556 Opc = X86ISD::ATOMOR64_DAG;
11558 case ISD::ATOMIC_LOAD_SUB:
11559 Opc = X86ISD::ATOMSUB64_DAG;
11561 case ISD::ATOMIC_LOAD_XOR:
11562 Opc = X86ISD::ATOMXOR64_DAG;
11564 case ISD::ATOMIC_LOAD_MAX:
11565 Opc = X86ISD::ATOMMAX64_DAG;
11567 case ISD::ATOMIC_LOAD_MIN:
11568 Opc = X86ISD::ATOMMIN64_DAG;
11570 case ISD::ATOMIC_LOAD_UMAX:
11571 Opc = X86ISD::ATOMUMAX64_DAG;
11573 case ISD::ATOMIC_LOAD_UMIN:
11574 Opc = X86ISD::ATOMUMIN64_DAG;
11576 case ISD::ATOMIC_SWAP:
11577 Opc = X86ISD::ATOMSWAP64_DAG;
11580 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11583 case ISD::ATOMIC_LOAD:
11584 ReplaceATOMIC_LOAD(N, Results, DAG);
11588 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11590 default: return NULL;
11591 case X86ISD::BSF: return "X86ISD::BSF";
11592 case X86ISD::BSR: return "X86ISD::BSR";
11593 case X86ISD::SHLD: return "X86ISD::SHLD";
11594 case X86ISD::SHRD: return "X86ISD::SHRD";
11595 case X86ISD::FAND: return "X86ISD::FAND";
11596 case X86ISD::FOR: return "X86ISD::FOR";
11597 case X86ISD::FXOR: return "X86ISD::FXOR";
11598 case X86ISD::FSRL: return "X86ISD::FSRL";
11599 case X86ISD::FILD: return "X86ISD::FILD";
11600 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11601 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11602 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11603 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11604 case X86ISD::FLD: return "X86ISD::FLD";
11605 case X86ISD::FST: return "X86ISD::FST";
11606 case X86ISD::CALL: return "X86ISD::CALL";
11607 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11608 case X86ISD::BT: return "X86ISD::BT";
11609 case X86ISD::CMP: return "X86ISD::CMP";
11610 case X86ISD::COMI: return "X86ISD::COMI";
11611 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11612 case X86ISD::SETCC: return "X86ISD::SETCC";
11613 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11614 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11615 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11616 case X86ISD::CMOV: return "X86ISD::CMOV";
11617 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11618 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11619 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11620 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11621 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11622 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11623 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11624 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11625 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11626 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11627 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11628 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11629 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11630 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11631 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11632 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11633 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11634 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11635 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11636 case X86ISD::HADD: return "X86ISD::HADD";
11637 case X86ISD::HSUB: return "X86ISD::HSUB";
11638 case X86ISD::FHADD: return "X86ISD::FHADD";
11639 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11640 case X86ISD::FMAX: return "X86ISD::FMAX";
11641 case X86ISD::FMIN: return "X86ISD::FMIN";
11642 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11643 case X86ISD::FMINC: return "X86ISD::FMINC";
11644 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11645 case X86ISD::FRCP: return "X86ISD::FRCP";
11646 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11647 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11648 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11649 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11650 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11651 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11652 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11653 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11654 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11655 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11656 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11657 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11658 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11659 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11660 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11661 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11662 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11663 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11664 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11665 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11666 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11667 case X86ISD::VSHL: return "X86ISD::VSHL";
11668 case X86ISD::VSRL: return "X86ISD::VSRL";
11669 case X86ISD::VSRA: return "X86ISD::VSRA";
11670 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11671 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11672 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11673 case X86ISD::CMPP: return "X86ISD::CMPP";
11674 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11675 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11676 case X86ISD::ADD: return "X86ISD::ADD";
11677 case X86ISD::SUB: return "X86ISD::SUB";
11678 case X86ISD::ADC: return "X86ISD::ADC";
11679 case X86ISD::SBB: return "X86ISD::SBB";
11680 case X86ISD::SMUL: return "X86ISD::SMUL";
11681 case X86ISD::UMUL: return "X86ISD::UMUL";
11682 case X86ISD::INC: return "X86ISD::INC";
11683 case X86ISD::DEC: return "X86ISD::DEC";
11684 case X86ISD::OR: return "X86ISD::OR";
11685 case X86ISD::XOR: return "X86ISD::XOR";
11686 case X86ISD::AND: return "X86ISD::AND";
11687 case X86ISD::ANDN: return "X86ISD::ANDN";
11688 case X86ISD::BLSI: return "X86ISD::BLSI";
11689 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11690 case X86ISD::BLSR: return "X86ISD::BLSR";
11691 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11692 case X86ISD::PTEST: return "X86ISD::PTEST";
11693 case X86ISD::TESTP: return "X86ISD::TESTP";
11694 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11695 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11696 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11697 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11698 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11699 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11700 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11701 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11702 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11703 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11704 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11705 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11706 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11707 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11708 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11709 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11710 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11711 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11712 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11713 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11714 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11715 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11716 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11717 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11718 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11719 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11720 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11721 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11722 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11723 case X86ISD::SAHF: return "X86ISD::SAHF";
11724 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11725 case X86ISD::FMADD: return "X86ISD::FMADD";
11726 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11727 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11728 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11729 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11730 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11734 // isLegalAddressingMode - Return true if the addressing mode represented
11735 // by AM is legal for this target, for a load/store of the specified type.
11736 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11738 // X86 supports extremely general addressing modes.
11739 CodeModel::Model M = getTargetMachine().getCodeModel();
11740 Reloc::Model R = getTargetMachine().getRelocationModel();
11742 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11743 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11748 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11750 // If a reference to this global requires an extra load, we can't fold it.
11751 if (isGlobalStubReference(GVFlags))
11754 // If BaseGV requires a register for the PIC base, we cannot also have a
11755 // BaseReg specified.
11756 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11759 // If lower 4G is not available, then we must use rip-relative addressing.
11760 if ((M != CodeModel::Small || R != Reloc::Static) &&
11761 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11765 switch (AM.Scale) {
11771 // These scales always work.
11776 // These scales are formed with basereg+scalereg. Only accept if there is
11781 default: // Other stuff never works.
11789 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11790 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11792 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11793 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11794 if (NumBits1 <= NumBits2)
11799 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11800 return Imm == (int32_t)Imm;
11803 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11804 // Can also use sub to handle negated immediates.
11805 return Imm == (int32_t)Imm;
11808 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11809 if (!VT1.isInteger() || !VT2.isInteger())
11811 unsigned NumBits1 = VT1.getSizeInBits();
11812 unsigned NumBits2 = VT2.getSizeInBits();
11813 if (NumBits1 <= NumBits2)
11818 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11819 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11820 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11823 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11824 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11825 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11828 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11829 // i16 instructions are longer (0x66 prefix) and potentially slower.
11830 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11833 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11834 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11835 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11836 /// are assumed to be legal.
11838 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11840 // Very little shuffling can be done for 64-bit vectors right now.
11841 if (VT.getSizeInBits() == 64)
11844 // FIXME: pshufb, blends, shifts.
11845 return (VT.getVectorNumElements() == 2 ||
11846 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11847 isMOVLMask(M, VT) ||
11848 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11849 isPSHUFDMask(M, VT) ||
11850 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11851 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11852 isPALIGNRMask(M, VT, Subtarget) ||
11853 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11854 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11855 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11856 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11860 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11862 unsigned NumElts = VT.getVectorNumElements();
11863 // FIXME: This collection of masks seems suspect.
11866 if (NumElts == 4 && VT.is128BitVector()) {
11867 return (isMOVLMask(Mask, VT) ||
11868 isCommutedMOVLMask(Mask, VT, true) ||
11869 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11870 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11875 //===----------------------------------------------------------------------===//
11876 // X86 Scheduler Hooks
11877 //===----------------------------------------------------------------------===//
11879 // private utility function
11881 // Get CMPXCHG opcode for the specified data type.
11882 static unsigned getCmpXChgOpcode(EVT VT) {
11883 switch (VT.getSimpleVT().SimpleTy) {
11884 case MVT::i8: return X86::LCMPXCHG8;
11885 case MVT::i16: return X86::LCMPXCHG16;
11886 case MVT::i32: return X86::LCMPXCHG32;
11887 case MVT::i64: return X86::LCMPXCHG64;
11891 llvm_unreachable("Invalid operand size!");
11894 // Get LOAD opcode for the specified data type.
11895 static unsigned getLoadOpcode(EVT VT) {
11896 switch (VT.getSimpleVT().SimpleTy) {
11897 case MVT::i8: return X86::MOV8rm;
11898 case MVT::i16: return X86::MOV16rm;
11899 case MVT::i32: return X86::MOV32rm;
11900 case MVT::i64: return X86::MOV64rm;
11904 llvm_unreachable("Invalid operand size!");
11907 // Get opcode of the non-atomic one from the specified atomic instruction.
11908 static unsigned getNonAtomicOpcode(unsigned Opc) {
11910 case X86::ATOMAND8: return X86::AND8rr;
11911 case X86::ATOMAND16: return X86::AND16rr;
11912 case X86::ATOMAND32: return X86::AND32rr;
11913 case X86::ATOMAND64: return X86::AND64rr;
11914 case X86::ATOMOR8: return X86::OR8rr;
11915 case X86::ATOMOR16: return X86::OR16rr;
11916 case X86::ATOMOR32: return X86::OR32rr;
11917 case X86::ATOMOR64: return X86::OR64rr;
11918 case X86::ATOMXOR8: return X86::XOR8rr;
11919 case X86::ATOMXOR16: return X86::XOR16rr;
11920 case X86::ATOMXOR32: return X86::XOR32rr;
11921 case X86::ATOMXOR64: return X86::XOR64rr;
11923 llvm_unreachable("Unhandled atomic-load-op opcode!");
11926 // Get opcode of the non-atomic one from the specified atomic instruction with
11928 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
11929 unsigned &ExtraOpc) {
11931 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
11932 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
11933 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
11934 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
11935 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
11936 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
11937 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
11938 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
11939 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
11940 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
11941 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
11942 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
11943 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
11944 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
11945 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
11946 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
11947 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
11948 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
11949 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
11950 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
11952 llvm_unreachable("Unhandled atomic-load-op opcode!");
11955 // Get opcode of the non-atomic one from the specified atomic instruction for
11956 // 64-bit data type on 32-bit target.
11957 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
11959 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
11960 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
11961 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
11962 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
11963 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
11964 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
11965 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
11966 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
11967 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
11968 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
11970 llvm_unreachable("Unhandled atomic-load-op opcode!");
11973 // Get opcode of the non-atomic one from the specified atomic instruction for
11974 // 64-bit data type on 32-bit target with extra opcode.
11975 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
11977 unsigned &ExtraOpc) {
11979 case X86::ATOMNAND6432:
11980 ExtraOpc = X86::NOT32r;
11981 HiOpc = X86::AND32rr;
11982 return X86::AND32rr;
11984 llvm_unreachable("Unhandled atomic-load-op opcode!");
11987 // Get pseudo CMOV opcode from the specified data type.
11988 static unsigned getPseudoCMOVOpc(EVT VT) {
11989 switch (VT.getSimpleVT().SimpleTy) {
11990 case MVT::i8: return X86::CMOV_GR8;
11991 case MVT::i16: return X86::CMOV_GR16;
11992 case MVT::i32: return X86::CMOV_GR32;
11996 llvm_unreachable("Unknown CMOV opcode!");
11999 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12000 // They will be translated into a spin-loop or compare-exchange loop from
12003 // dst = atomic-fetch-op MI.addr, MI.val
12009 // EAX = LOAD MI.addr
12011 // t1 = OP MI.val, EAX
12012 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12017 MachineBasicBlock *
12018 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12019 MachineBasicBlock *MBB) const {
12020 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12021 DebugLoc DL = MI->getDebugLoc();
12023 MachineFunction *MF = MBB->getParent();
12024 MachineRegisterInfo &MRI = MF->getRegInfo();
12026 const BasicBlock *BB = MBB->getBasicBlock();
12027 MachineFunction::iterator I = MBB;
12030 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12031 "Unexpected number of operands");
12033 assert(MI->hasOneMemOperand() &&
12034 "Expected atomic-load-op to have one memoperand");
12036 // Memory Reference
12037 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12038 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12040 unsigned DstReg, SrcReg;
12041 unsigned MemOpndSlot;
12043 unsigned CurOp = 0;
12045 DstReg = MI->getOperand(CurOp++).getReg();
12046 MemOpndSlot = CurOp;
12047 CurOp += X86::AddrNumOperands;
12048 SrcReg = MI->getOperand(CurOp++).getReg();
12050 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12051 MVT::SimpleValueType VT = *RC->vt_begin();
12052 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12054 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12055 unsigned LOADOpc = getLoadOpcode(VT);
12057 // For the atomic load-arith operator, we generate
12060 // EAX = LOAD [MI.addr]
12062 // t1 = OP MI.val, EAX
12063 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12067 MachineBasicBlock *thisMBB = MBB;
12068 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12069 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12070 MF->insert(I, mainMBB);
12071 MF->insert(I, sinkMBB);
12073 MachineInstrBuilder MIB;
12075 // Transfer the remainder of BB and its successor edges to sinkMBB.
12076 sinkMBB->splice(sinkMBB->begin(), MBB,
12077 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12078 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12081 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12082 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12083 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12084 MIB.setMemRefs(MMOBegin, MMOEnd);
12086 thisMBB->addSuccessor(mainMBB);
12089 MachineBasicBlock *origMainMBB = mainMBB;
12090 mainMBB->addLiveIn(AccPhyReg);
12092 // Copy AccPhyReg as it is used more than once.
12093 unsigned AccReg = MRI.createVirtualRegister(RC);
12094 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12095 .addReg(AccPhyReg);
12097 unsigned t1 = MRI.createVirtualRegister(RC);
12098 unsigned Opc = MI->getOpcode();
12101 llvm_unreachable("Unhandled atomic-load-op opcode!");
12102 case X86::ATOMAND8:
12103 case X86::ATOMAND16:
12104 case X86::ATOMAND32:
12105 case X86::ATOMAND64:
12107 case X86::ATOMOR16:
12108 case X86::ATOMOR32:
12109 case X86::ATOMOR64:
12110 case X86::ATOMXOR8:
12111 case X86::ATOMXOR16:
12112 case X86::ATOMXOR32:
12113 case X86::ATOMXOR64: {
12114 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12115 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12119 case X86::ATOMNAND8:
12120 case X86::ATOMNAND16:
12121 case X86::ATOMNAND32:
12122 case X86::ATOMNAND64: {
12123 unsigned t2 = MRI.createVirtualRegister(RC);
12125 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12126 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12128 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12131 case X86::ATOMMAX8:
12132 case X86::ATOMMAX16:
12133 case X86::ATOMMAX32:
12134 case X86::ATOMMAX64:
12135 case X86::ATOMMIN8:
12136 case X86::ATOMMIN16:
12137 case X86::ATOMMIN32:
12138 case X86::ATOMMIN64:
12139 case X86::ATOMUMAX8:
12140 case X86::ATOMUMAX16:
12141 case X86::ATOMUMAX32:
12142 case X86::ATOMUMAX64:
12143 case X86::ATOMUMIN8:
12144 case X86::ATOMUMIN16:
12145 case X86::ATOMUMIN32:
12146 case X86::ATOMUMIN64: {
12148 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12150 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12154 if (Subtarget->hasCMov()) {
12155 if (VT != MVT::i8) {
12157 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12161 // Promote i8 to i32 to use CMOV32
12162 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12163 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12164 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12165 unsigned t2 = MRI.createVirtualRegister(RC32);
12167 unsigned Undef = MRI.createVirtualRegister(RC32);
12168 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12170 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12173 .addImm(X86::sub_8bit);
12174 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12177 .addImm(X86::sub_8bit);
12179 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12183 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12184 .addReg(t2, 0, X86::sub_8bit);
12187 // Use pseudo select and lower them.
12188 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12189 "Invalid atomic-load-op transformation!");
12190 unsigned SelOpc = getPseudoCMOVOpc(VT);
12191 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12192 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12193 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12194 .addReg(SrcReg).addReg(AccReg)
12196 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12202 // Copy AccPhyReg back from virtual register.
12203 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12206 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12207 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12208 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12210 MIB.setMemRefs(MMOBegin, MMOEnd);
12212 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12214 mainMBB->addSuccessor(origMainMBB);
12215 mainMBB->addSuccessor(sinkMBB);
12218 sinkMBB->addLiveIn(AccPhyReg);
12220 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12221 TII->get(TargetOpcode::COPY), DstReg)
12222 .addReg(AccPhyReg);
12224 MI->eraseFromParent();
12228 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12229 // instructions. They will be translated into a spin-loop or compare-exchange
12233 // dst = atomic-fetch-op MI.addr, MI.val
12239 // EAX = LOAD [MI.addr + 0]
12240 // EDX = LOAD [MI.addr + 4]
12242 // EBX = OP MI.val.lo, EAX
12243 // ECX = OP MI.val.hi, EDX
12244 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12249 MachineBasicBlock *
12250 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12251 MachineBasicBlock *MBB) const {
12252 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12253 DebugLoc DL = MI->getDebugLoc();
12255 MachineFunction *MF = MBB->getParent();
12256 MachineRegisterInfo &MRI = MF->getRegInfo();
12258 const BasicBlock *BB = MBB->getBasicBlock();
12259 MachineFunction::iterator I = MBB;
12262 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12263 "Unexpected number of operands");
12265 assert(MI->hasOneMemOperand() &&
12266 "Expected atomic-load-op32 to have one memoperand");
12268 // Memory Reference
12269 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12270 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12272 unsigned DstLoReg, DstHiReg;
12273 unsigned SrcLoReg, SrcHiReg;
12274 unsigned MemOpndSlot;
12276 unsigned CurOp = 0;
12278 DstLoReg = MI->getOperand(CurOp++).getReg();
12279 DstHiReg = MI->getOperand(CurOp++).getReg();
12280 MemOpndSlot = CurOp;
12281 CurOp += X86::AddrNumOperands;
12282 SrcLoReg = MI->getOperand(CurOp++).getReg();
12283 SrcHiReg = MI->getOperand(CurOp++).getReg();
12285 const TargetRegisterClass *RC = &X86::GR32RegClass;
12286 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12288 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12289 unsigned LOADOpc = X86::MOV32rm;
12291 // For the atomic load-arith operator, we generate
12294 // EAX = LOAD [MI.addr + 0]
12295 // EDX = LOAD [MI.addr + 4]
12297 // EBX = OP MI.vallo, EAX
12298 // ECX = OP MI.valhi, EDX
12299 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12303 MachineBasicBlock *thisMBB = MBB;
12304 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12305 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12306 MF->insert(I, mainMBB);
12307 MF->insert(I, sinkMBB);
12309 MachineInstrBuilder MIB;
12311 // Transfer the remainder of BB and its successor edges to sinkMBB.
12312 sinkMBB->splice(sinkMBB->begin(), MBB,
12313 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12314 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12318 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12319 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12320 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12321 MIB.setMemRefs(MMOBegin, MMOEnd);
12323 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12324 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12325 if (i == X86::AddrDisp) {
12326 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12327 // Don't forget to transfer the target flag.
12328 MachineOperand &MO = MIB->getOperand(MIB->getNumOperands()-1);
12329 MO.setTargetFlags(MI->getOperand(MemOpndSlot + i).getTargetFlags());
12331 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12333 MIB.setMemRefs(MMOBegin, MMOEnd);
12335 thisMBB->addSuccessor(mainMBB);
12338 MachineBasicBlock *origMainMBB = mainMBB;
12339 mainMBB->addLiveIn(X86::EAX);
12340 mainMBB->addLiveIn(X86::EDX);
12342 // Copy EDX:EAX as they are used more than once.
12343 unsigned LoReg = MRI.createVirtualRegister(RC);
12344 unsigned HiReg = MRI.createVirtualRegister(RC);
12345 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12346 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12348 unsigned t1L = MRI.createVirtualRegister(RC);
12349 unsigned t1H = MRI.createVirtualRegister(RC);
12351 unsigned Opc = MI->getOpcode();
12354 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12355 case X86::ATOMAND6432:
12356 case X86::ATOMOR6432:
12357 case X86::ATOMXOR6432:
12358 case X86::ATOMADD6432:
12359 case X86::ATOMSUB6432: {
12361 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12362 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12363 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12366 case X86::ATOMNAND6432: {
12367 unsigned HiOpc, NOTOpc;
12368 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12369 unsigned t2L = MRI.createVirtualRegister(RC);
12370 unsigned t2H = MRI.createVirtualRegister(RC);
12371 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12372 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12373 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12374 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12377 case X86::ATOMMAX6432:
12378 case X86::ATOMMIN6432:
12379 case X86::ATOMUMAX6432:
12380 case X86::ATOMUMIN6432: {
12382 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12383 unsigned cL = MRI.createVirtualRegister(RC8);
12384 unsigned cH = MRI.createVirtualRegister(RC8);
12385 unsigned cL32 = MRI.createVirtualRegister(RC);
12386 unsigned cH32 = MRI.createVirtualRegister(RC);
12387 unsigned cc = MRI.createVirtualRegister(RC);
12388 // cl := cmp src_lo, lo
12389 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12390 .addReg(SrcLoReg).addReg(LoReg);
12391 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12392 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12393 // ch := cmp src_hi, hi
12394 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12395 .addReg(SrcHiReg).addReg(HiReg);
12396 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12397 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12398 // cc := if (src_hi == hi) ? cl : ch;
12399 if (Subtarget->hasCMov()) {
12400 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12401 .addReg(cH32).addReg(cL32);
12403 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12404 .addReg(cH32).addReg(cL32)
12405 .addImm(X86::COND_E);
12406 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12408 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12409 if (Subtarget->hasCMov()) {
12410 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12411 .addReg(SrcLoReg).addReg(LoReg);
12412 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12413 .addReg(SrcHiReg).addReg(HiReg);
12415 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12416 .addReg(SrcLoReg).addReg(LoReg)
12417 .addImm(X86::COND_NE);
12418 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12419 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12420 .addReg(SrcHiReg).addReg(HiReg)
12421 .addImm(X86::COND_NE);
12422 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12426 case X86::ATOMSWAP6432: {
12428 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12429 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12430 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12435 // Copy EDX:EAX back from HiReg:LoReg
12436 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12437 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12438 // Copy ECX:EBX from t1H:t1L
12439 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12440 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12442 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12443 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12444 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12445 MIB.setMemRefs(MMOBegin, MMOEnd);
12447 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12449 mainMBB->addSuccessor(origMainMBB);
12450 mainMBB->addSuccessor(sinkMBB);
12453 sinkMBB->addLiveIn(X86::EAX);
12454 sinkMBB->addLiveIn(X86::EDX);
12456 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12457 TII->get(TargetOpcode::COPY), DstLoReg)
12459 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12460 TII->get(TargetOpcode::COPY), DstHiReg)
12463 MI->eraseFromParent();
12467 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12468 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12469 // in the .td file.
12470 MachineBasicBlock *
12471 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12472 unsigned numArgs, bool memArg) const {
12473 assert(Subtarget->hasSSE42() &&
12474 "Target must have SSE4.2 or AVX features enabled");
12476 DebugLoc dl = MI->getDebugLoc();
12477 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12479 if (!Subtarget->hasAVX()) {
12481 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12483 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12486 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12488 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12491 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12492 for (unsigned i = 0; i < numArgs; ++i) {
12493 MachineOperand &Op = MI->getOperand(i+1);
12494 if (!(Op.isReg() && Op.isImplicit()))
12495 MIB.addOperand(Op);
12497 BuildMI(*BB, MI, dl,
12498 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12499 .addReg(X86::XMM0);
12501 MI->eraseFromParent();
12505 MachineBasicBlock *
12506 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12507 DebugLoc dl = MI->getDebugLoc();
12508 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12510 // Address into RAX/EAX, other two args into ECX, EDX.
12511 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12512 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12513 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12514 for (int i = 0; i < X86::AddrNumOperands; ++i)
12515 MIB.addOperand(MI->getOperand(i));
12517 unsigned ValOps = X86::AddrNumOperands;
12518 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12519 .addReg(MI->getOperand(ValOps).getReg());
12520 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12521 .addReg(MI->getOperand(ValOps+1).getReg());
12523 // The instruction doesn't actually take any operands though.
12524 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12526 MI->eraseFromParent(); // The pseudo is gone now.
12530 MachineBasicBlock *
12531 X86TargetLowering::EmitVAARG64WithCustomInserter(
12533 MachineBasicBlock *MBB) const {
12534 // Emit va_arg instruction on X86-64.
12536 // Operands to this pseudo-instruction:
12537 // 0 ) Output : destination address (reg)
12538 // 1-5) Input : va_list address (addr, i64mem)
12539 // 6 ) ArgSize : Size (in bytes) of vararg type
12540 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12541 // 8 ) Align : Alignment of type
12542 // 9 ) EFLAGS (implicit-def)
12544 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12545 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12547 unsigned DestReg = MI->getOperand(0).getReg();
12548 MachineOperand &Base = MI->getOperand(1);
12549 MachineOperand &Scale = MI->getOperand(2);
12550 MachineOperand &Index = MI->getOperand(3);
12551 MachineOperand &Disp = MI->getOperand(4);
12552 MachineOperand &Segment = MI->getOperand(5);
12553 unsigned ArgSize = MI->getOperand(6).getImm();
12554 unsigned ArgMode = MI->getOperand(7).getImm();
12555 unsigned Align = MI->getOperand(8).getImm();
12557 // Memory Reference
12558 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12559 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12560 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12562 // Machine Information
12563 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12564 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12565 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12566 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12567 DebugLoc DL = MI->getDebugLoc();
12569 // struct va_list {
12572 // i64 overflow_area (address)
12573 // i64 reg_save_area (address)
12575 // sizeof(va_list) = 24
12576 // alignment(va_list) = 8
12578 unsigned TotalNumIntRegs = 6;
12579 unsigned TotalNumXMMRegs = 8;
12580 bool UseGPOffset = (ArgMode == 1);
12581 bool UseFPOffset = (ArgMode == 2);
12582 unsigned MaxOffset = TotalNumIntRegs * 8 +
12583 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12585 /* Align ArgSize to a multiple of 8 */
12586 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12587 bool NeedsAlign = (Align > 8);
12589 MachineBasicBlock *thisMBB = MBB;
12590 MachineBasicBlock *overflowMBB;
12591 MachineBasicBlock *offsetMBB;
12592 MachineBasicBlock *endMBB;
12594 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12595 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12596 unsigned OffsetReg = 0;
12598 if (!UseGPOffset && !UseFPOffset) {
12599 // If we only pull from the overflow region, we don't create a branch.
12600 // We don't need to alter control flow.
12601 OffsetDestReg = 0; // unused
12602 OverflowDestReg = DestReg;
12605 overflowMBB = thisMBB;
12608 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12609 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12610 // If not, pull from overflow_area. (branch to overflowMBB)
12615 // offsetMBB overflowMBB
12620 // Registers for the PHI in endMBB
12621 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12622 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12624 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12625 MachineFunction *MF = MBB->getParent();
12626 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12627 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12628 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12630 MachineFunction::iterator MBBIter = MBB;
12633 // Insert the new basic blocks
12634 MF->insert(MBBIter, offsetMBB);
12635 MF->insert(MBBIter, overflowMBB);
12636 MF->insert(MBBIter, endMBB);
12638 // Transfer the remainder of MBB and its successor edges to endMBB.
12639 endMBB->splice(endMBB->begin(), thisMBB,
12640 llvm::next(MachineBasicBlock::iterator(MI)),
12642 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12644 // Make offsetMBB and overflowMBB successors of thisMBB
12645 thisMBB->addSuccessor(offsetMBB);
12646 thisMBB->addSuccessor(overflowMBB);
12648 // endMBB is a successor of both offsetMBB and overflowMBB
12649 offsetMBB->addSuccessor(endMBB);
12650 overflowMBB->addSuccessor(endMBB);
12652 // Load the offset value into a register
12653 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12654 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12658 .addDisp(Disp, UseFPOffset ? 4 : 0)
12659 .addOperand(Segment)
12660 .setMemRefs(MMOBegin, MMOEnd);
12662 // Check if there is enough room left to pull this argument.
12663 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12665 .addImm(MaxOffset + 8 - ArgSizeA8);
12667 // Branch to "overflowMBB" if offset >= max
12668 // Fall through to "offsetMBB" otherwise
12669 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12670 .addMBB(overflowMBB);
12673 // In offsetMBB, emit code to use the reg_save_area.
12675 assert(OffsetReg != 0);
12677 // Read the reg_save_area address.
12678 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12679 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12684 .addOperand(Segment)
12685 .setMemRefs(MMOBegin, MMOEnd);
12687 // Zero-extend the offset
12688 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12689 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12692 .addImm(X86::sub_32bit);
12694 // Add the offset to the reg_save_area to get the final address.
12695 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12696 .addReg(OffsetReg64)
12697 .addReg(RegSaveReg);
12699 // Compute the offset for the next argument
12700 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12701 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12703 .addImm(UseFPOffset ? 16 : 8);
12705 // Store it back into the va_list.
12706 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12710 .addDisp(Disp, UseFPOffset ? 4 : 0)
12711 .addOperand(Segment)
12712 .addReg(NextOffsetReg)
12713 .setMemRefs(MMOBegin, MMOEnd);
12716 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12721 // Emit code to use overflow area
12724 // Load the overflow_area address into a register.
12725 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12726 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12731 .addOperand(Segment)
12732 .setMemRefs(MMOBegin, MMOEnd);
12734 // If we need to align it, do so. Otherwise, just copy the address
12735 // to OverflowDestReg.
12737 // Align the overflow address
12738 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12739 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12741 // aligned_addr = (addr + (align-1)) & ~(align-1)
12742 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12743 .addReg(OverflowAddrReg)
12746 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12748 .addImm(~(uint64_t)(Align-1));
12750 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12751 .addReg(OverflowAddrReg);
12754 // Compute the next overflow address after this argument.
12755 // (the overflow address should be kept 8-byte aligned)
12756 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12757 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12758 .addReg(OverflowDestReg)
12759 .addImm(ArgSizeA8);
12761 // Store the new overflow address.
12762 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12767 .addOperand(Segment)
12768 .addReg(NextAddrReg)
12769 .setMemRefs(MMOBegin, MMOEnd);
12771 // If we branched, emit the PHI to the front of endMBB.
12773 BuildMI(*endMBB, endMBB->begin(), DL,
12774 TII->get(X86::PHI), DestReg)
12775 .addReg(OffsetDestReg).addMBB(offsetMBB)
12776 .addReg(OverflowDestReg).addMBB(overflowMBB);
12779 // Erase the pseudo instruction
12780 MI->eraseFromParent();
12785 MachineBasicBlock *
12786 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12788 MachineBasicBlock *MBB) const {
12789 // Emit code to save XMM registers to the stack. The ABI says that the
12790 // number of registers to save is given in %al, so it's theoretically
12791 // possible to do an indirect jump trick to avoid saving all of them,
12792 // however this code takes a simpler approach and just executes all
12793 // of the stores if %al is non-zero. It's less code, and it's probably
12794 // easier on the hardware branch predictor, and stores aren't all that
12795 // expensive anyway.
12797 // Create the new basic blocks. One block contains all the XMM stores,
12798 // and one block is the final destination regardless of whether any
12799 // stores were performed.
12800 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12801 MachineFunction *F = MBB->getParent();
12802 MachineFunction::iterator MBBIter = MBB;
12804 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12805 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12806 F->insert(MBBIter, XMMSaveMBB);
12807 F->insert(MBBIter, EndMBB);
12809 // Transfer the remainder of MBB and its successor edges to EndMBB.
12810 EndMBB->splice(EndMBB->begin(), MBB,
12811 llvm::next(MachineBasicBlock::iterator(MI)),
12813 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12815 // The original block will now fall through to the XMM save block.
12816 MBB->addSuccessor(XMMSaveMBB);
12817 // The XMMSaveMBB will fall through to the end block.
12818 XMMSaveMBB->addSuccessor(EndMBB);
12820 // Now add the instructions.
12821 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12822 DebugLoc DL = MI->getDebugLoc();
12824 unsigned CountReg = MI->getOperand(0).getReg();
12825 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12826 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12828 if (!Subtarget->isTargetWin64()) {
12829 // If %al is 0, branch around the XMM save block.
12830 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12831 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12832 MBB->addSuccessor(EndMBB);
12835 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12836 // In the XMM save block, save all the XMM argument registers.
12837 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12838 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12839 MachineMemOperand *MMO =
12840 F->getMachineMemOperand(
12841 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12842 MachineMemOperand::MOStore,
12843 /*Size=*/16, /*Align=*/16);
12844 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12845 .addFrameIndex(RegSaveFrameIndex)
12846 .addImm(/*Scale=*/1)
12847 .addReg(/*IndexReg=*/0)
12848 .addImm(/*Disp=*/Offset)
12849 .addReg(/*Segment=*/0)
12850 .addReg(MI->getOperand(i).getReg())
12851 .addMemOperand(MMO);
12854 MI->eraseFromParent(); // The pseudo instruction is gone now.
12859 // The EFLAGS operand of SelectItr might be missing a kill marker
12860 // because there were multiple uses of EFLAGS, and ISel didn't know
12861 // which to mark. Figure out whether SelectItr should have had a
12862 // kill marker, and set it if it should. Returns the correct kill
12864 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12865 MachineBasicBlock* BB,
12866 const TargetRegisterInfo* TRI) {
12867 // Scan forward through BB for a use/def of EFLAGS.
12868 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12869 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12870 const MachineInstr& mi = *miI;
12871 if (mi.readsRegister(X86::EFLAGS))
12873 if (mi.definesRegister(X86::EFLAGS))
12874 break; // Should have kill-flag - update below.
12877 // If we hit the end of the block, check whether EFLAGS is live into a
12879 if (miI == BB->end()) {
12880 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12881 sEnd = BB->succ_end();
12882 sItr != sEnd; ++sItr) {
12883 MachineBasicBlock* succ = *sItr;
12884 if (succ->isLiveIn(X86::EFLAGS))
12889 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12890 // out. SelectMI should have a kill flag on EFLAGS.
12891 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12895 MachineBasicBlock *
12896 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12897 MachineBasicBlock *BB) const {
12898 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12899 DebugLoc DL = MI->getDebugLoc();
12901 // To "insert" a SELECT_CC instruction, we actually have to insert the
12902 // diamond control-flow pattern. The incoming instruction knows the
12903 // destination vreg to set, the condition code register to branch on, the
12904 // true/false values to select between, and a branch opcode to use.
12905 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12906 MachineFunction::iterator It = BB;
12912 // cmpTY ccX, r1, r2
12914 // fallthrough --> copy0MBB
12915 MachineBasicBlock *thisMBB = BB;
12916 MachineFunction *F = BB->getParent();
12917 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12918 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12919 F->insert(It, copy0MBB);
12920 F->insert(It, sinkMBB);
12922 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12923 // live into the sink and copy blocks.
12924 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12925 if (!MI->killsRegister(X86::EFLAGS) &&
12926 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12927 copy0MBB->addLiveIn(X86::EFLAGS);
12928 sinkMBB->addLiveIn(X86::EFLAGS);
12931 // Transfer the remainder of BB and its successor edges to sinkMBB.
12932 sinkMBB->splice(sinkMBB->begin(), BB,
12933 llvm::next(MachineBasicBlock::iterator(MI)),
12935 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12937 // Add the true and fallthrough blocks as its successors.
12938 BB->addSuccessor(copy0MBB);
12939 BB->addSuccessor(sinkMBB);
12941 // Create the conditional branch instruction.
12943 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12944 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12947 // %FalseValue = ...
12948 // # fallthrough to sinkMBB
12949 copy0MBB->addSuccessor(sinkMBB);
12952 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12954 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12955 TII->get(X86::PHI), MI->getOperand(0).getReg())
12956 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12957 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12959 MI->eraseFromParent(); // The pseudo instruction is gone now.
12963 MachineBasicBlock *
12964 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12965 bool Is64Bit) const {
12966 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12967 DebugLoc DL = MI->getDebugLoc();
12968 MachineFunction *MF = BB->getParent();
12969 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12971 assert(getTargetMachine().Options.EnableSegmentedStacks);
12973 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12974 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12977 // ... [Till the alloca]
12978 // If stacklet is not large enough, jump to mallocMBB
12981 // Allocate by subtracting from RSP
12982 // Jump to continueMBB
12985 // Allocate by call to runtime
12989 // [rest of original BB]
12992 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12993 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12994 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12996 MachineRegisterInfo &MRI = MF->getRegInfo();
12997 const TargetRegisterClass *AddrRegClass =
12998 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13000 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13001 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13002 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13003 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13004 sizeVReg = MI->getOperand(1).getReg(),
13005 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13007 MachineFunction::iterator MBBIter = BB;
13010 MF->insert(MBBIter, bumpMBB);
13011 MF->insert(MBBIter, mallocMBB);
13012 MF->insert(MBBIter, continueMBB);
13014 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13015 (MachineBasicBlock::iterator(MI)), BB->end());
13016 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13018 // Add code to the main basic block to check if the stack limit has been hit,
13019 // and if so, jump to mallocMBB otherwise to bumpMBB.
13020 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13021 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13022 .addReg(tmpSPVReg).addReg(sizeVReg);
13023 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13024 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13025 .addReg(SPLimitVReg);
13026 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13028 // bumpMBB simply decreases the stack pointer, since we know the current
13029 // stacklet has enough space.
13030 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13031 .addReg(SPLimitVReg);
13032 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13033 .addReg(SPLimitVReg);
13034 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13036 // Calls into a routine in libgcc to allocate more space from the heap.
13037 const uint32_t *RegMask =
13038 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13040 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13042 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13043 .addExternalSymbol("__morestack_allocate_stack_space")
13044 .addRegMask(RegMask)
13045 .addReg(X86::RDI, RegState::Implicit)
13046 .addReg(X86::RAX, RegState::ImplicitDefine);
13048 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13050 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13051 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13052 .addExternalSymbol("__morestack_allocate_stack_space")
13053 .addRegMask(RegMask)
13054 .addReg(X86::EAX, RegState::ImplicitDefine);
13058 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13061 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13062 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13063 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13065 // Set up the CFG correctly.
13066 BB->addSuccessor(bumpMBB);
13067 BB->addSuccessor(mallocMBB);
13068 mallocMBB->addSuccessor(continueMBB);
13069 bumpMBB->addSuccessor(continueMBB);
13071 // Take care of the PHI nodes.
13072 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13073 MI->getOperand(0).getReg())
13074 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13075 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13077 // Delete the original pseudo instruction.
13078 MI->eraseFromParent();
13081 return continueMBB;
13084 MachineBasicBlock *
13085 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13086 MachineBasicBlock *BB) const {
13087 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13088 DebugLoc DL = MI->getDebugLoc();
13090 assert(!Subtarget->isTargetEnvMacho());
13092 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13093 // non-trivial part is impdef of ESP.
13095 if (Subtarget->isTargetWin64()) {
13096 if (Subtarget->isTargetCygMing()) {
13097 // ___chkstk(Mingw64):
13098 // Clobbers R10, R11, RAX and EFLAGS.
13100 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13101 .addExternalSymbol("___chkstk")
13102 .addReg(X86::RAX, RegState::Implicit)
13103 .addReg(X86::RSP, RegState::Implicit)
13104 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13105 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13106 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13108 // __chkstk(MSVCRT): does not update stack pointer.
13109 // Clobbers R10, R11 and EFLAGS.
13110 // FIXME: RAX(allocated size) might be reused and not killed.
13111 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13112 .addExternalSymbol("__chkstk")
13113 .addReg(X86::RAX, RegState::Implicit)
13114 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13115 // RAX has the offset to subtracted from RSP.
13116 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13121 const char *StackProbeSymbol =
13122 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13124 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13125 .addExternalSymbol(StackProbeSymbol)
13126 .addReg(X86::EAX, RegState::Implicit)
13127 .addReg(X86::ESP, RegState::Implicit)
13128 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13129 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13130 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13133 MI->eraseFromParent(); // The pseudo instruction is gone now.
13137 MachineBasicBlock *
13138 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13139 MachineBasicBlock *BB) const {
13140 // This is pretty easy. We're taking the value that we received from
13141 // our load from the relocation, sticking it in either RDI (x86-64)
13142 // or EAX and doing an indirect call. The return value will then
13143 // be in the normal return register.
13144 const X86InstrInfo *TII
13145 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13146 DebugLoc DL = MI->getDebugLoc();
13147 MachineFunction *F = BB->getParent();
13149 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13150 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13152 // Get a register mask for the lowered call.
13153 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13154 // proper register mask.
13155 const uint32_t *RegMask =
13156 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13157 if (Subtarget->is64Bit()) {
13158 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13159 TII->get(X86::MOV64rm), X86::RDI)
13161 .addImm(0).addReg(0)
13162 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13163 MI->getOperand(3).getTargetFlags())
13165 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13166 addDirectMem(MIB, X86::RDI);
13167 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13168 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13169 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13170 TII->get(X86::MOV32rm), X86::EAX)
13172 .addImm(0).addReg(0)
13173 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13174 MI->getOperand(3).getTargetFlags())
13176 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13177 addDirectMem(MIB, X86::EAX);
13178 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13180 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13181 TII->get(X86::MOV32rm), X86::EAX)
13182 .addReg(TII->getGlobalBaseReg(F))
13183 .addImm(0).addReg(0)
13184 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13185 MI->getOperand(3).getTargetFlags())
13187 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13188 addDirectMem(MIB, X86::EAX);
13189 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13192 MI->eraseFromParent(); // The pseudo instruction is gone now.
13196 MachineBasicBlock *
13197 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13198 MachineBasicBlock *BB) const {
13199 switch (MI->getOpcode()) {
13200 default: llvm_unreachable("Unexpected instr type to insert");
13201 case X86::TAILJMPd64:
13202 case X86::TAILJMPr64:
13203 case X86::TAILJMPm64:
13204 llvm_unreachable("TAILJMP64 would not be touched here.");
13205 case X86::TCRETURNdi64:
13206 case X86::TCRETURNri64:
13207 case X86::TCRETURNmi64:
13209 case X86::WIN_ALLOCA:
13210 return EmitLoweredWinAlloca(MI, BB);
13211 case X86::SEG_ALLOCA_32:
13212 return EmitLoweredSegAlloca(MI, BB, false);
13213 case X86::SEG_ALLOCA_64:
13214 return EmitLoweredSegAlloca(MI, BB, true);
13215 case X86::TLSCall_32:
13216 case X86::TLSCall_64:
13217 return EmitLoweredTLSCall(MI, BB);
13218 case X86::CMOV_GR8:
13219 case X86::CMOV_FR32:
13220 case X86::CMOV_FR64:
13221 case X86::CMOV_V4F32:
13222 case X86::CMOV_V2F64:
13223 case X86::CMOV_V2I64:
13224 case X86::CMOV_V8F32:
13225 case X86::CMOV_V4F64:
13226 case X86::CMOV_V4I64:
13227 case X86::CMOV_GR16:
13228 case X86::CMOV_GR32:
13229 case X86::CMOV_RFP32:
13230 case X86::CMOV_RFP64:
13231 case X86::CMOV_RFP80:
13232 return EmitLoweredSelect(MI, BB);
13234 case X86::FP32_TO_INT16_IN_MEM:
13235 case X86::FP32_TO_INT32_IN_MEM:
13236 case X86::FP32_TO_INT64_IN_MEM:
13237 case X86::FP64_TO_INT16_IN_MEM:
13238 case X86::FP64_TO_INT32_IN_MEM:
13239 case X86::FP64_TO_INT64_IN_MEM:
13240 case X86::FP80_TO_INT16_IN_MEM:
13241 case X86::FP80_TO_INT32_IN_MEM:
13242 case X86::FP80_TO_INT64_IN_MEM: {
13243 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13244 DebugLoc DL = MI->getDebugLoc();
13246 // Change the floating point control register to use "round towards zero"
13247 // mode when truncating to an integer value.
13248 MachineFunction *F = BB->getParent();
13249 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13250 addFrameReference(BuildMI(*BB, MI, DL,
13251 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13253 // Load the old value of the high byte of the control word...
13255 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13256 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13259 // Set the high part to be round to zero...
13260 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13263 // Reload the modified control word now...
13264 addFrameReference(BuildMI(*BB, MI, DL,
13265 TII->get(X86::FLDCW16m)), CWFrameIdx);
13267 // Restore the memory image of control word to original value
13268 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13271 // Get the X86 opcode to use.
13273 switch (MI->getOpcode()) {
13274 default: llvm_unreachable("illegal opcode!");
13275 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13276 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13277 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13278 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13279 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13280 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13281 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13282 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13283 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13287 MachineOperand &Op = MI->getOperand(0);
13289 AM.BaseType = X86AddressMode::RegBase;
13290 AM.Base.Reg = Op.getReg();
13292 AM.BaseType = X86AddressMode::FrameIndexBase;
13293 AM.Base.FrameIndex = Op.getIndex();
13295 Op = MI->getOperand(1);
13297 AM.Scale = Op.getImm();
13298 Op = MI->getOperand(2);
13300 AM.IndexReg = Op.getImm();
13301 Op = MI->getOperand(3);
13302 if (Op.isGlobal()) {
13303 AM.GV = Op.getGlobal();
13305 AM.Disp = Op.getImm();
13307 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13308 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13310 // Reload the original control word now.
13311 addFrameReference(BuildMI(*BB, MI, DL,
13312 TII->get(X86::FLDCW16m)), CWFrameIdx);
13314 MI->eraseFromParent(); // The pseudo instruction is gone now.
13317 // String/text processing lowering.
13318 case X86::PCMPISTRM128REG:
13319 case X86::VPCMPISTRM128REG:
13320 case X86::PCMPISTRM128MEM:
13321 case X86::VPCMPISTRM128MEM:
13322 case X86::PCMPESTRM128REG:
13323 case X86::VPCMPESTRM128REG:
13324 case X86::PCMPESTRM128MEM:
13325 case X86::VPCMPESTRM128MEM: {
13328 switch (MI->getOpcode()) {
13329 default: llvm_unreachable("illegal opcode!");
13330 case X86::PCMPISTRM128REG:
13331 case X86::VPCMPISTRM128REG:
13332 NumArgs = 3; MemArg = false; break;
13333 case X86::PCMPISTRM128MEM:
13334 case X86::VPCMPISTRM128MEM:
13335 NumArgs = 3; MemArg = true; break;
13336 case X86::PCMPESTRM128REG:
13337 case X86::VPCMPESTRM128REG:
13338 NumArgs = 5; MemArg = false; break;
13339 case X86::PCMPESTRM128MEM:
13340 case X86::VPCMPESTRM128MEM:
13341 NumArgs = 5; MemArg = true; break;
13343 return EmitPCMP(MI, BB, NumArgs, MemArg);
13346 // Thread synchronization.
13348 return EmitMonitor(MI, BB);
13350 // Atomic Lowering.
13351 case X86::ATOMAND8:
13352 case X86::ATOMAND16:
13353 case X86::ATOMAND32:
13354 case X86::ATOMAND64:
13357 case X86::ATOMOR16:
13358 case X86::ATOMOR32:
13359 case X86::ATOMOR64:
13361 case X86::ATOMXOR16:
13362 case X86::ATOMXOR8:
13363 case X86::ATOMXOR32:
13364 case X86::ATOMXOR64:
13366 case X86::ATOMNAND8:
13367 case X86::ATOMNAND16:
13368 case X86::ATOMNAND32:
13369 case X86::ATOMNAND64:
13371 case X86::ATOMMAX8:
13372 case X86::ATOMMAX16:
13373 case X86::ATOMMAX32:
13374 case X86::ATOMMAX64:
13376 case X86::ATOMMIN8:
13377 case X86::ATOMMIN16:
13378 case X86::ATOMMIN32:
13379 case X86::ATOMMIN64:
13381 case X86::ATOMUMAX8:
13382 case X86::ATOMUMAX16:
13383 case X86::ATOMUMAX32:
13384 case X86::ATOMUMAX64:
13386 case X86::ATOMUMIN8:
13387 case X86::ATOMUMIN16:
13388 case X86::ATOMUMIN32:
13389 case X86::ATOMUMIN64:
13390 return EmitAtomicLoadArith(MI, BB);
13392 // This group does 64-bit operations on a 32-bit host.
13393 case X86::ATOMAND6432:
13394 case X86::ATOMOR6432:
13395 case X86::ATOMXOR6432:
13396 case X86::ATOMNAND6432:
13397 case X86::ATOMADD6432:
13398 case X86::ATOMSUB6432:
13399 case X86::ATOMMAX6432:
13400 case X86::ATOMMIN6432:
13401 case X86::ATOMUMAX6432:
13402 case X86::ATOMUMIN6432:
13403 case X86::ATOMSWAP6432:
13404 return EmitAtomicLoadArith6432(MI, BB);
13406 case X86::VASTART_SAVE_XMM_REGS:
13407 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13409 case X86::VAARG_64:
13410 return EmitVAARG64WithCustomInserter(MI, BB);
13414 //===----------------------------------------------------------------------===//
13415 // X86 Optimization Hooks
13416 //===----------------------------------------------------------------------===//
13418 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13421 const SelectionDAG &DAG,
13422 unsigned Depth) const {
13423 unsigned BitWidth = KnownZero.getBitWidth();
13424 unsigned Opc = Op.getOpcode();
13425 assert((Opc >= ISD::BUILTIN_OP_END ||
13426 Opc == ISD::INTRINSIC_WO_CHAIN ||
13427 Opc == ISD::INTRINSIC_W_CHAIN ||
13428 Opc == ISD::INTRINSIC_VOID) &&
13429 "Should use MaskedValueIsZero if you don't know whether Op"
13430 " is a target node!");
13432 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13446 // These nodes' second result is a boolean.
13447 if (Op.getResNo() == 0)
13450 case X86ISD::SETCC:
13451 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13453 case ISD::INTRINSIC_WO_CHAIN: {
13454 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13455 unsigned NumLoBits = 0;
13458 case Intrinsic::x86_sse_movmsk_ps:
13459 case Intrinsic::x86_avx_movmsk_ps_256:
13460 case Intrinsic::x86_sse2_movmsk_pd:
13461 case Intrinsic::x86_avx_movmsk_pd_256:
13462 case Intrinsic::x86_mmx_pmovmskb:
13463 case Intrinsic::x86_sse2_pmovmskb_128:
13464 case Intrinsic::x86_avx2_pmovmskb: {
13465 // High bits of movmskp{s|d}, pmovmskb are known zero.
13467 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13468 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13469 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13470 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13471 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13472 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13473 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13474 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13476 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13485 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13486 unsigned Depth) const {
13487 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13488 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13489 return Op.getValueType().getScalarType().getSizeInBits();
13495 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13496 /// node is a GlobalAddress + offset.
13497 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13498 const GlobalValue* &GA,
13499 int64_t &Offset) const {
13500 if (N->getOpcode() == X86ISD::Wrapper) {
13501 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13502 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13503 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13507 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13510 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13511 /// same as extracting the high 128-bit part of 256-bit vector and then
13512 /// inserting the result into the low part of a new 256-bit vector
13513 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13514 EVT VT = SVOp->getValueType(0);
13515 unsigned NumElems = VT.getVectorNumElements();
13517 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13518 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13519 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13520 SVOp->getMaskElt(j) >= 0)
13526 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13527 /// same as extracting the low 128-bit part of 256-bit vector and then
13528 /// inserting the result into the high part of a new 256-bit vector
13529 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13530 EVT VT = SVOp->getValueType(0);
13531 unsigned NumElems = VT.getVectorNumElements();
13533 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13534 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13535 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13536 SVOp->getMaskElt(j) >= 0)
13542 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13543 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13544 TargetLowering::DAGCombinerInfo &DCI,
13545 const X86Subtarget* Subtarget) {
13546 DebugLoc dl = N->getDebugLoc();
13547 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13548 SDValue V1 = SVOp->getOperand(0);
13549 SDValue V2 = SVOp->getOperand(1);
13550 EVT VT = SVOp->getValueType(0);
13551 unsigned NumElems = VT.getVectorNumElements();
13553 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13554 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13558 // V UNDEF BUILD_VECTOR UNDEF
13560 // CONCAT_VECTOR CONCAT_VECTOR
13563 // RESULT: V + zero extended
13565 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13566 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13567 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13570 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13573 // To match the shuffle mask, the first half of the mask should
13574 // be exactly the first vector, and all the rest a splat with the
13575 // first element of the second one.
13576 for (unsigned i = 0; i != NumElems/2; ++i)
13577 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13578 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13581 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13582 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13583 if (Ld->hasNUsesOfValue(1, 0)) {
13584 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13585 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13587 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13589 Ld->getPointerInfo(),
13590 Ld->getAlignment(),
13591 false/*isVolatile*/, true/*ReadMem*/,
13592 false/*WriteMem*/);
13593 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13597 // Emit a zeroed vector and insert the desired subvector on its
13599 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13600 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13601 return DCI.CombineTo(N, InsV);
13604 //===--------------------------------------------------------------------===//
13605 // Combine some shuffles into subvector extracts and inserts:
13608 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13609 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13610 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13611 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13612 return DCI.CombineTo(N, InsV);
13615 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13616 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13617 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13618 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13619 return DCI.CombineTo(N, InsV);
13625 /// PerformShuffleCombine - Performs several different shuffle combines.
13626 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13627 TargetLowering::DAGCombinerInfo &DCI,
13628 const X86Subtarget *Subtarget) {
13629 DebugLoc dl = N->getDebugLoc();
13630 EVT VT = N->getValueType(0);
13632 // Don't create instructions with illegal types after legalize types has run.
13633 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13634 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13637 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13638 if (Subtarget->hasAVX() && VT.is256BitVector() &&
13639 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13640 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13642 // Only handle 128 wide vector from here on.
13643 if (!VT.is128BitVector())
13646 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13647 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13648 // consecutive, non-overlapping, and in the right order.
13649 SmallVector<SDValue, 16> Elts;
13650 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13651 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13653 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13657 /// PerformTruncateCombine - Converts truncate operation to
13658 /// a sequence of vector shuffle operations.
13659 /// It is possible when we truncate 256-bit vector to 128-bit vector
13660 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13661 TargetLowering::DAGCombinerInfo &DCI,
13662 const X86Subtarget *Subtarget) {
13663 if (!DCI.isBeforeLegalizeOps())
13666 if (!Subtarget->hasAVX())
13669 EVT VT = N->getValueType(0);
13670 SDValue Op = N->getOperand(0);
13671 EVT OpVT = Op.getValueType();
13672 DebugLoc dl = N->getDebugLoc();
13674 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13676 if (Subtarget->hasAVX2()) {
13677 // AVX2: v4i64 -> v4i32
13680 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13682 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13683 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13686 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13687 DAG.getIntPtrConstant(0));
13690 // AVX: v4i64 -> v4i32
13691 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13692 DAG.getIntPtrConstant(0));
13694 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13695 DAG.getIntPtrConstant(2));
13697 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13698 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13701 static const int ShufMask1[] = {0, 2, 0, 0};
13703 SDValue Undef = DAG.getUNDEF(VT);
13704 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13705 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13708 static const int ShufMask2[] = {0, 1, 4, 5};
13710 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13713 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13715 if (Subtarget->hasAVX2()) {
13716 // AVX2: v8i32 -> v8i16
13718 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13721 SmallVector<SDValue,32> pshufbMask;
13722 for (unsigned i = 0; i < 2; ++i) {
13723 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13724 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13725 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13726 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13727 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13728 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13729 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13730 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13731 for (unsigned j = 0; j < 8; ++j)
13732 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13734 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13735 &pshufbMask[0], 32);
13736 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13738 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13740 static const int ShufMask[] = {0, 2, -1, -1};
13741 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13744 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13745 DAG.getIntPtrConstant(0));
13747 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13750 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13751 DAG.getIntPtrConstant(0));
13753 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13754 DAG.getIntPtrConstant(4));
13756 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13757 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13760 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13761 -1, -1, -1, -1, -1, -1, -1, -1};
13763 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13764 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13765 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13767 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13768 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13771 static const int ShufMask2[] = {0, 1, 4, 5};
13773 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13774 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13780 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13781 /// specific shuffle of a load can be folded into a single element load.
13782 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13783 /// shuffles have been customed lowered so we need to handle those here.
13784 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13785 TargetLowering::DAGCombinerInfo &DCI) {
13786 if (DCI.isBeforeLegalizeOps())
13789 SDValue InVec = N->getOperand(0);
13790 SDValue EltNo = N->getOperand(1);
13792 if (!isa<ConstantSDNode>(EltNo))
13795 EVT VT = InVec.getValueType();
13797 bool HasShuffleIntoBitcast = false;
13798 if (InVec.getOpcode() == ISD::BITCAST) {
13799 // Don't duplicate a load with other uses.
13800 if (!InVec.hasOneUse())
13802 EVT BCVT = InVec.getOperand(0).getValueType();
13803 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13805 InVec = InVec.getOperand(0);
13806 HasShuffleIntoBitcast = true;
13809 if (!isTargetShuffle(InVec.getOpcode()))
13812 // Don't duplicate a load with other uses.
13813 if (!InVec.hasOneUse())
13816 SmallVector<int, 16> ShuffleMask;
13818 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13822 // Select the input vector, guarding against out of range extract vector.
13823 unsigned NumElems = VT.getVectorNumElements();
13824 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13825 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13826 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13827 : InVec.getOperand(1);
13829 // If inputs to shuffle are the same for both ops, then allow 2 uses
13830 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13832 if (LdNode.getOpcode() == ISD::BITCAST) {
13833 // Don't duplicate a load with other uses.
13834 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13837 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13838 LdNode = LdNode.getOperand(0);
13841 if (!ISD::isNormalLoad(LdNode.getNode()))
13844 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13846 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13849 if (HasShuffleIntoBitcast) {
13850 // If there's a bitcast before the shuffle, check if the load type and
13851 // alignment is valid.
13852 unsigned Align = LN0->getAlignment();
13853 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13854 unsigned NewAlign = TLI.getDataLayout()->
13855 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13857 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13861 // All checks match so transform back to vector_shuffle so that DAG combiner
13862 // can finish the job
13863 DebugLoc dl = N->getDebugLoc();
13865 // Create shuffle node taking into account the case that its a unary shuffle
13866 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13867 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13868 InVec.getOperand(0), Shuffle,
13870 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13871 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13875 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13876 /// generation and convert it from being a bunch of shuffles and extracts
13877 /// to a simple store and scalar loads to extract the elements.
13878 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13879 TargetLowering::DAGCombinerInfo &DCI) {
13880 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13881 if (NewOp.getNode())
13884 SDValue InputVector = N->getOperand(0);
13886 // Only operate on vectors of 4 elements, where the alternative shuffling
13887 // gets to be more expensive.
13888 if (InputVector.getValueType() != MVT::v4i32)
13891 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13892 // single use which is a sign-extend or zero-extend, and all elements are
13894 SmallVector<SDNode *, 4> Uses;
13895 unsigned ExtractedElements = 0;
13896 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13897 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13898 if (UI.getUse().getResNo() != InputVector.getResNo())
13901 SDNode *Extract = *UI;
13902 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13905 if (Extract->getValueType(0) != MVT::i32)
13907 if (!Extract->hasOneUse())
13909 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13910 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13912 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13915 // Record which element was extracted.
13916 ExtractedElements |=
13917 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13919 Uses.push_back(Extract);
13922 // If not all the elements were used, this may not be worthwhile.
13923 if (ExtractedElements != 15)
13926 // Ok, we've now decided to do the transformation.
13927 DebugLoc dl = InputVector.getDebugLoc();
13929 // Store the value to a temporary stack slot.
13930 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13931 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13932 MachinePointerInfo(), false, false, 0);
13934 // Replace each use (extract) with a load of the appropriate element.
13935 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13936 UE = Uses.end(); UI != UE; ++UI) {
13937 SDNode *Extract = *UI;
13939 // cOMpute the element's address.
13940 SDValue Idx = Extract->getOperand(1);
13942 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13943 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13944 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13945 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13947 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13948 StackPtr, OffsetVal);
13950 // Load the scalar.
13951 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13952 ScalarAddr, MachinePointerInfo(),
13953 false, false, false, 0);
13955 // Replace the exact with the load.
13956 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13959 // The replacement was made in place; don't return anything.
13963 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13965 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13966 TargetLowering::DAGCombinerInfo &DCI,
13967 const X86Subtarget *Subtarget) {
13968 DebugLoc DL = N->getDebugLoc();
13969 SDValue Cond = N->getOperand(0);
13970 // Get the LHS/RHS of the select.
13971 SDValue LHS = N->getOperand(1);
13972 SDValue RHS = N->getOperand(2);
13973 EVT VT = LHS.getValueType();
13975 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13976 // instructions match the semantics of the common C idiom x<y?x:y but not
13977 // x<=y?x:y, because of how they handle negative zero (which can be
13978 // ignored in unsafe-math mode).
13979 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13980 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13981 (Subtarget->hasSSE2() ||
13982 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13983 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13985 unsigned Opcode = 0;
13986 // Check for x CC y ? x : y.
13987 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13988 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13992 // Converting this to a min would handle NaNs incorrectly, and swapping
13993 // the operands would cause it to handle comparisons between positive
13994 // and negative zero incorrectly.
13995 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13996 if (!DAG.getTarget().Options.UnsafeFPMath &&
13997 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13999 std::swap(LHS, RHS);
14001 Opcode = X86ISD::FMIN;
14004 // Converting this to a min would handle comparisons between positive
14005 // and negative zero incorrectly.
14006 if (!DAG.getTarget().Options.UnsafeFPMath &&
14007 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14009 Opcode = X86ISD::FMIN;
14012 // Converting this to a min would handle both negative zeros and NaNs
14013 // incorrectly, but we can swap the operands to fix both.
14014 std::swap(LHS, RHS);
14018 Opcode = X86ISD::FMIN;
14022 // Converting this to a max would handle comparisons between positive
14023 // and negative zero incorrectly.
14024 if (!DAG.getTarget().Options.UnsafeFPMath &&
14025 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14027 Opcode = X86ISD::FMAX;
14030 // Converting this to a max would handle NaNs incorrectly, and swapping
14031 // the operands would cause it to handle comparisons between positive
14032 // and negative zero incorrectly.
14033 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14034 if (!DAG.getTarget().Options.UnsafeFPMath &&
14035 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14037 std::swap(LHS, RHS);
14039 Opcode = X86ISD::FMAX;
14042 // Converting this to a max would handle both negative zeros and NaNs
14043 // incorrectly, but we can swap the operands to fix both.
14044 std::swap(LHS, RHS);
14048 Opcode = X86ISD::FMAX;
14051 // Check for x CC y ? y : x -- a min/max with reversed arms.
14052 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14053 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14057 // Converting this to a min would handle comparisons between positive
14058 // and negative zero incorrectly, and swapping the operands would
14059 // cause it to handle NaNs incorrectly.
14060 if (!DAG.getTarget().Options.UnsafeFPMath &&
14061 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14062 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14064 std::swap(LHS, RHS);
14066 Opcode = X86ISD::FMIN;
14069 // Converting this to a min would handle NaNs incorrectly.
14070 if (!DAG.getTarget().Options.UnsafeFPMath &&
14071 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14073 Opcode = X86ISD::FMIN;
14076 // Converting this to a min would handle both negative zeros and NaNs
14077 // incorrectly, but we can swap the operands to fix both.
14078 std::swap(LHS, RHS);
14082 Opcode = X86ISD::FMIN;
14086 // Converting this to a max would handle NaNs incorrectly.
14087 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14089 Opcode = X86ISD::FMAX;
14092 // Converting this to a max would handle comparisons between positive
14093 // and negative zero incorrectly, and swapping the operands would
14094 // cause it to handle NaNs incorrectly.
14095 if (!DAG.getTarget().Options.UnsafeFPMath &&
14096 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14097 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14099 std::swap(LHS, RHS);
14101 Opcode = X86ISD::FMAX;
14104 // Converting this to a max would handle both negative zeros and NaNs
14105 // incorrectly, but we can swap the operands to fix both.
14106 std::swap(LHS, RHS);
14110 Opcode = X86ISD::FMAX;
14116 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14119 // If this is a select between two integer constants, try to do some
14121 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14122 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14123 // Don't do this for crazy integer types.
14124 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14125 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14126 // so that TrueC (the true value) is larger than FalseC.
14127 bool NeedsCondInvert = false;
14129 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14130 // Efficiently invertible.
14131 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14132 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14133 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14134 NeedsCondInvert = true;
14135 std::swap(TrueC, FalseC);
14138 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14139 if (FalseC->getAPIntValue() == 0 &&
14140 TrueC->getAPIntValue().isPowerOf2()) {
14141 if (NeedsCondInvert) // Invert the condition if needed.
14142 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14143 DAG.getConstant(1, Cond.getValueType()));
14145 // Zero extend the condition if needed.
14146 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14148 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14149 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14150 DAG.getConstant(ShAmt, MVT::i8));
14153 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14154 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14155 if (NeedsCondInvert) // Invert the condition if needed.
14156 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14157 DAG.getConstant(1, Cond.getValueType()));
14159 // Zero extend the condition if needed.
14160 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14161 FalseC->getValueType(0), Cond);
14162 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14163 SDValue(FalseC, 0));
14166 // Optimize cases that will turn into an LEA instruction. This requires
14167 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14168 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14169 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14170 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14172 bool isFastMultiplier = false;
14174 switch ((unsigned char)Diff) {
14176 case 1: // result = add base, cond
14177 case 2: // result = lea base( , cond*2)
14178 case 3: // result = lea base(cond, cond*2)
14179 case 4: // result = lea base( , cond*4)
14180 case 5: // result = lea base(cond, cond*4)
14181 case 8: // result = lea base( , cond*8)
14182 case 9: // result = lea base(cond, cond*8)
14183 isFastMultiplier = true;
14188 if (isFastMultiplier) {
14189 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14190 if (NeedsCondInvert) // Invert the condition if needed.
14191 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14192 DAG.getConstant(1, Cond.getValueType()));
14194 // Zero extend the condition if needed.
14195 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14197 // Scale the condition by the difference.
14199 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14200 DAG.getConstant(Diff, Cond.getValueType()));
14202 // Add the base if non-zero.
14203 if (FalseC->getAPIntValue() != 0)
14204 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14205 SDValue(FalseC, 0));
14212 // Canonicalize max and min:
14213 // (x > y) ? x : y -> (x >= y) ? x : y
14214 // (x < y) ? x : y -> (x <= y) ? x : y
14215 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14216 // the need for an extra compare
14217 // against zero. e.g.
14218 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14220 // testl %edi, %edi
14222 // cmovgl %edi, %eax
14226 // cmovsl %eax, %edi
14227 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14228 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14229 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14230 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14235 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14236 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14237 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14238 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14243 // If we know that this node is legal then we know that it is going to be
14244 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14245 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14246 // to simplify previous instructions.
14247 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14248 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14249 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14250 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14252 // Don't optimize vector selects that map to mask-registers.
14256 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14257 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14259 APInt KnownZero, KnownOne;
14260 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14261 DCI.isBeforeLegalizeOps());
14262 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14263 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14264 DCI.CommitTargetLoweringOpt(TLO);
14270 // Check whether a boolean test is testing a boolean value generated by
14271 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14274 // Simplify the following patterns:
14275 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14276 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14277 // to (Op EFLAGS Cond)
14279 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14280 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14281 // to (Op EFLAGS !Cond)
14283 // where Op could be BRCOND or CMOV.
14285 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14286 // Quit if not CMP and SUB with its value result used.
14287 if (Cmp.getOpcode() != X86ISD::CMP &&
14288 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14291 // Quit if not used as a boolean value.
14292 if (CC != X86::COND_E && CC != X86::COND_NE)
14295 // Check CMP operands. One of them should be 0 or 1 and the other should be
14296 // an SetCC or extended from it.
14297 SDValue Op1 = Cmp.getOperand(0);
14298 SDValue Op2 = Cmp.getOperand(1);
14301 const ConstantSDNode* C = 0;
14302 bool needOppositeCond = (CC == X86::COND_E);
14304 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14306 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14308 else // Quit if all operands are not constants.
14311 if (C->getZExtValue() == 1)
14312 needOppositeCond = !needOppositeCond;
14313 else if (C->getZExtValue() != 0)
14314 // Quit if the constant is neither 0 or 1.
14317 // Skip 'zext' node.
14318 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14319 SetCC = SetCC.getOperand(0);
14321 switch (SetCC.getOpcode()) {
14322 case X86ISD::SETCC:
14323 // Set the condition code or opposite one if necessary.
14324 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14325 if (needOppositeCond)
14326 CC = X86::GetOppositeBranchCondition(CC);
14327 return SetCC.getOperand(1);
14328 case X86ISD::CMOV: {
14329 // Check whether false/true value has canonical one, i.e. 0 or 1.
14330 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14331 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14332 // Quit if true value is not a constant.
14335 // Quit if false value is not a constant.
14337 // A special case for rdrand, where 0 is set if false cond is found.
14338 SDValue Op = SetCC.getOperand(0);
14339 if (Op.getOpcode() != X86ISD::RDRAND)
14342 // Quit if false value is not the constant 0 or 1.
14343 bool FValIsFalse = true;
14344 if (FVal && FVal->getZExtValue() != 0) {
14345 if (FVal->getZExtValue() != 1)
14347 // If FVal is 1, opposite cond is needed.
14348 needOppositeCond = !needOppositeCond;
14349 FValIsFalse = false;
14351 // Quit if TVal is not the constant opposite of FVal.
14352 if (FValIsFalse && TVal->getZExtValue() != 1)
14354 if (!FValIsFalse && TVal->getZExtValue() != 0)
14356 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14357 if (needOppositeCond)
14358 CC = X86::GetOppositeBranchCondition(CC);
14359 return SetCC.getOperand(3);
14366 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14367 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14368 TargetLowering::DAGCombinerInfo &DCI,
14369 const X86Subtarget *Subtarget) {
14370 DebugLoc DL = N->getDebugLoc();
14372 // If the flag operand isn't dead, don't touch this CMOV.
14373 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14376 SDValue FalseOp = N->getOperand(0);
14377 SDValue TrueOp = N->getOperand(1);
14378 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14379 SDValue Cond = N->getOperand(3);
14381 if (CC == X86::COND_E || CC == X86::COND_NE) {
14382 switch (Cond.getOpcode()) {
14386 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14387 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14388 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14394 Flags = checkBoolTestSetCCCombine(Cond, CC);
14395 if (Flags.getNode() &&
14396 // Extra check as FCMOV only supports a subset of X86 cond.
14397 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14398 SDValue Ops[] = { FalseOp, TrueOp,
14399 DAG.getConstant(CC, MVT::i8), Flags };
14400 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14401 Ops, array_lengthof(Ops));
14404 // If this is a select between two integer constants, try to do some
14405 // optimizations. Note that the operands are ordered the opposite of SELECT
14407 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14408 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14409 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14410 // larger than FalseC (the false value).
14411 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14412 CC = X86::GetOppositeBranchCondition(CC);
14413 std::swap(TrueC, FalseC);
14416 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14417 // This is efficient for any integer data type (including i8/i16) and
14419 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14420 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14421 DAG.getConstant(CC, MVT::i8), Cond);
14423 // Zero extend the condition if needed.
14424 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14426 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14427 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14428 DAG.getConstant(ShAmt, MVT::i8));
14429 if (N->getNumValues() == 2) // Dead flag value?
14430 return DCI.CombineTo(N, Cond, SDValue());
14434 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14435 // for any integer data type, including i8/i16.
14436 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14437 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14438 DAG.getConstant(CC, MVT::i8), Cond);
14440 // Zero extend the condition if needed.
14441 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14442 FalseC->getValueType(0), Cond);
14443 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14444 SDValue(FalseC, 0));
14446 if (N->getNumValues() == 2) // Dead flag value?
14447 return DCI.CombineTo(N, Cond, SDValue());
14451 // Optimize cases that will turn into an LEA instruction. This requires
14452 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14453 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14454 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14455 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14457 bool isFastMultiplier = false;
14459 switch ((unsigned char)Diff) {
14461 case 1: // result = add base, cond
14462 case 2: // result = lea base( , cond*2)
14463 case 3: // result = lea base(cond, cond*2)
14464 case 4: // result = lea base( , cond*4)
14465 case 5: // result = lea base(cond, cond*4)
14466 case 8: // result = lea base( , cond*8)
14467 case 9: // result = lea base(cond, cond*8)
14468 isFastMultiplier = true;
14473 if (isFastMultiplier) {
14474 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14475 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14476 DAG.getConstant(CC, MVT::i8), Cond);
14477 // Zero extend the condition if needed.
14478 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14480 // Scale the condition by the difference.
14482 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14483 DAG.getConstant(Diff, Cond.getValueType()));
14485 // Add the base if non-zero.
14486 if (FalseC->getAPIntValue() != 0)
14487 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14488 SDValue(FalseC, 0));
14489 if (N->getNumValues() == 2) // Dead flag value?
14490 return DCI.CombineTo(N, Cond, SDValue());
14500 /// PerformMulCombine - Optimize a single multiply with constant into two
14501 /// in order to implement it with two cheaper instructions, e.g.
14502 /// LEA + SHL, LEA + LEA.
14503 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14504 TargetLowering::DAGCombinerInfo &DCI) {
14505 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14508 EVT VT = N->getValueType(0);
14509 if (VT != MVT::i64)
14512 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14515 uint64_t MulAmt = C->getZExtValue();
14516 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14519 uint64_t MulAmt1 = 0;
14520 uint64_t MulAmt2 = 0;
14521 if ((MulAmt % 9) == 0) {
14523 MulAmt2 = MulAmt / 9;
14524 } else if ((MulAmt % 5) == 0) {
14526 MulAmt2 = MulAmt / 5;
14527 } else if ((MulAmt % 3) == 0) {
14529 MulAmt2 = MulAmt / 3;
14532 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14533 DebugLoc DL = N->getDebugLoc();
14535 if (isPowerOf2_64(MulAmt2) &&
14536 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14537 // If second multiplifer is pow2, issue it first. We want the multiply by
14538 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14540 std::swap(MulAmt1, MulAmt2);
14543 if (isPowerOf2_64(MulAmt1))
14544 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14545 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14547 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14548 DAG.getConstant(MulAmt1, VT));
14550 if (isPowerOf2_64(MulAmt2))
14551 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14552 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14554 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14555 DAG.getConstant(MulAmt2, VT));
14557 // Do not add new nodes to DAG combiner worklist.
14558 DCI.CombineTo(N, NewMul, false);
14563 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14564 SDValue N0 = N->getOperand(0);
14565 SDValue N1 = N->getOperand(1);
14566 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14567 EVT VT = N0.getValueType();
14569 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14570 // since the result of setcc_c is all zero's or all ones.
14571 if (VT.isInteger() && !VT.isVector() &&
14572 N1C && N0.getOpcode() == ISD::AND &&
14573 N0.getOperand(1).getOpcode() == ISD::Constant) {
14574 SDValue N00 = N0.getOperand(0);
14575 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14576 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14577 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14578 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14579 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14580 APInt ShAmt = N1C->getAPIntValue();
14581 Mask = Mask.shl(ShAmt);
14583 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14584 N00, DAG.getConstant(Mask, VT));
14589 // Hardware support for vector shifts is sparse which makes us scalarize the
14590 // vector operations in many cases. Also, on sandybridge ADD is faster than
14592 // (shl V, 1) -> add V,V
14593 if (isSplatVector(N1.getNode())) {
14594 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14596 // We shift all of the values by one. In many cases we do not have
14597 // hardware support for this operation. This is better expressed as an ADD
14599 if (N1C && (1 == N1C->getZExtValue())) {
14600 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14607 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14609 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14610 TargetLowering::DAGCombinerInfo &DCI,
14611 const X86Subtarget *Subtarget) {
14612 EVT VT = N->getValueType(0);
14613 if (N->getOpcode() == ISD::SHL) {
14614 SDValue V = PerformSHLCombine(N, DAG);
14615 if (V.getNode()) return V;
14618 // On X86 with SSE2 support, we can transform this to a vector shift if
14619 // all elements are shifted by the same amount. We can't do this in legalize
14620 // because the a constant vector is typically transformed to a constant pool
14621 // so we have no knowledge of the shift amount.
14622 if (!Subtarget->hasSSE2())
14625 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14626 (!Subtarget->hasAVX2() ||
14627 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14630 SDValue ShAmtOp = N->getOperand(1);
14631 EVT EltVT = VT.getVectorElementType();
14632 DebugLoc DL = N->getDebugLoc();
14633 SDValue BaseShAmt = SDValue();
14634 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14635 unsigned NumElts = VT.getVectorNumElements();
14637 for (; i != NumElts; ++i) {
14638 SDValue Arg = ShAmtOp.getOperand(i);
14639 if (Arg.getOpcode() == ISD::UNDEF) continue;
14643 // Handle the case where the build_vector is all undef
14644 // FIXME: Should DAG allow this?
14648 for (; i != NumElts; ++i) {
14649 SDValue Arg = ShAmtOp.getOperand(i);
14650 if (Arg.getOpcode() == ISD::UNDEF) continue;
14651 if (Arg != BaseShAmt) {
14655 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14656 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14657 SDValue InVec = ShAmtOp.getOperand(0);
14658 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14659 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14661 for (; i != NumElts; ++i) {
14662 SDValue Arg = InVec.getOperand(i);
14663 if (Arg.getOpcode() == ISD::UNDEF) continue;
14667 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14668 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14669 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14670 if (C->getZExtValue() == SplatIdx)
14671 BaseShAmt = InVec.getOperand(1);
14674 if (BaseShAmt.getNode() == 0) {
14675 // Don't create instructions with illegal types after legalize
14677 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14678 !DCI.isBeforeLegalize())
14681 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14682 DAG.getIntPtrConstant(0));
14687 // The shift amount is an i32.
14688 if (EltVT.bitsGT(MVT::i32))
14689 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14690 else if (EltVT.bitsLT(MVT::i32))
14691 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14693 // The shift amount is identical so we can do a vector shift.
14694 SDValue ValOp = N->getOperand(0);
14695 switch (N->getOpcode()) {
14697 llvm_unreachable("Unknown shift opcode!");
14699 switch (VT.getSimpleVT().SimpleTy) {
14700 default: return SDValue();
14707 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14710 switch (VT.getSimpleVT().SimpleTy) {
14711 default: return SDValue();
14716 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14719 switch (VT.getSimpleVT().SimpleTy) {
14720 default: return SDValue();
14727 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14733 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14734 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14735 // and friends. Likewise for OR -> CMPNEQSS.
14736 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14737 TargetLowering::DAGCombinerInfo &DCI,
14738 const X86Subtarget *Subtarget) {
14741 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14742 // we're requiring SSE2 for both.
14743 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14744 SDValue N0 = N->getOperand(0);
14745 SDValue N1 = N->getOperand(1);
14746 SDValue CMP0 = N0->getOperand(1);
14747 SDValue CMP1 = N1->getOperand(1);
14748 DebugLoc DL = N->getDebugLoc();
14750 // The SETCCs should both refer to the same CMP.
14751 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14754 SDValue CMP00 = CMP0->getOperand(0);
14755 SDValue CMP01 = CMP0->getOperand(1);
14756 EVT VT = CMP00.getValueType();
14758 if (VT == MVT::f32 || VT == MVT::f64) {
14759 bool ExpectingFlags = false;
14760 // Check for any users that want flags:
14761 for (SDNode::use_iterator UI = N->use_begin(),
14763 !ExpectingFlags && UI != UE; ++UI)
14764 switch (UI->getOpcode()) {
14769 ExpectingFlags = true;
14771 case ISD::CopyToReg:
14772 case ISD::SIGN_EXTEND:
14773 case ISD::ZERO_EXTEND:
14774 case ISD::ANY_EXTEND:
14778 if (!ExpectingFlags) {
14779 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14780 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14782 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14783 X86::CondCode tmp = cc0;
14788 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14789 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14790 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14791 X86ISD::NodeType NTOperator = is64BitFP ?
14792 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14793 // FIXME: need symbolic constants for these magic numbers.
14794 // See X86ATTInstPrinter.cpp:printSSECC().
14795 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14796 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14797 DAG.getConstant(x86cc, MVT::i8));
14798 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14800 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14801 DAG.getConstant(1, MVT::i32));
14802 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14803 return OneBitOfTruth;
14811 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14812 /// so it can be folded inside ANDNP.
14813 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14814 EVT VT = N->getValueType(0);
14816 // Match direct AllOnes for 128 and 256-bit vectors
14817 if (ISD::isBuildVectorAllOnes(N))
14820 // Look through a bit convert.
14821 if (N->getOpcode() == ISD::BITCAST)
14822 N = N->getOperand(0).getNode();
14824 // Sometimes the operand may come from a insert_subvector building a 256-bit
14826 if (VT.is256BitVector() &&
14827 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14828 SDValue V1 = N->getOperand(0);
14829 SDValue V2 = N->getOperand(1);
14831 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14832 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14833 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14834 ISD::isBuildVectorAllOnes(V2.getNode()))
14841 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14842 TargetLowering::DAGCombinerInfo &DCI,
14843 const X86Subtarget *Subtarget) {
14844 if (DCI.isBeforeLegalizeOps())
14847 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14851 EVT VT = N->getValueType(0);
14853 // Create ANDN, BLSI, and BLSR instructions
14854 // BLSI is X & (-X)
14855 // BLSR is X & (X-1)
14856 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14857 SDValue N0 = N->getOperand(0);
14858 SDValue N1 = N->getOperand(1);
14859 DebugLoc DL = N->getDebugLoc();
14861 // Check LHS for not
14862 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14863 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14864 // Check RHS for not
14865 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14866 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14868 // Check LHS for neg
14869 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14870 isZero(N0.getOperand(0)))
14871 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14873 // Check RHS for neg
14874 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14875 isZero(N1.getOperand(0)))
14876 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14878 // Check LHS for X-1
14879 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14880 isAllOnes(N0.getOperand(1)))
14881 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14883 // Check RHS for X-1
14884 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14885 isAllOnes(N1.getOperand(1)))
14886 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14891 // Want to form ANDNP nodes:
14892 // 1) In the hopes of then easily combining them with OR and AND nodes
14893 // to form PBLEND/PSIGN.
14894 // 2) To match ANDN packed intrinsics
14895 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14898 SDValue N0 = N->getOperand(0);
14899 SDValue N1 = N->getOperand(1);
14900 DebugLoc DL = N->getDebugLoc();
14902 // Check LHS for vnot
14903 if (N0.getOpcode() == ISD::XOR &&
14904 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14905 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14906 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14908 // Check RHS for vnot
14909 if (N1.getOpcode() == ISD::XOR &&
14910 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14911 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14912 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14917 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14918 TargetLowering::DAGCombinerInfo &DCI,
14919 const X86Subtarget *Subtarget) {
14920 if (DCI.isBeforeLegalizeOps())
14923 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14927 EVT VT = N->getValueType(0);
14929 SDValue N0 = N->getOperand(0);
14930 SDValue N1 = N->getOperand(1);
14932 // look for psign/blend
14933 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14934 if (!Subtarget->hasSSSE3() ||
14935 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14938 // Canonicalize pandn to RHS
14939 if (N0.getOpcode() == X86ISD::ANDNP)
14941 // or (and (m, y), (pandn m, x))
14942 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14943 SDValue Mask = N1.getOperand(0);
14944 SDValue X = N1.getOperand(1);
14946 if (N0.getOperand(0) == Mask)
14947 Y = N0.getOperand(1);
14948 if (N0.getOperand(1) == Mask)
14949 Y = N0.getOperand(0);
14951 // Check to see if the mask appeared in both the AND and ANDNP and
14955 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14956 // Look through mask bitcast.
14957 if (Mask.getOpcode() == ISD::BITCAST)
14958 Mask = Mask.getOperand(0);
14959 if (X.getOpcode() == ISD::BITCAST)
14960 X = X.getOperand(0);
14961 if (Y.getOpcode() == ISD::BITCAST)
14962 Y = Y.getOperand(0);
14964 EVT MaskVT = Mask.getValueType();
14966 // Validate that the Mask operand is a vector sra node.
14967 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14968 // there is no psrai.b
14969 if (Mask.getOpcode() != X86ISD::VSRAI)
14972 // Check that the SRA is all signbits.
14973 SDValue SraC = Mask.getOperand(1);
14974 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14975 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14976 if ((SraAmt + 1) != EltBits)
14979 DebugLoc DL = N->getDebugLoc();
14981 // Now we know we at least have a plendvb with the mask val. See if
14982 // we can form a psignb/w/d.
14983 // psign = x.type == y.type == mask.type && y = sub(0, x);
14984 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14985 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14986 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14987 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14988 "Unsupported VT for PSIGN");
14989 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14990 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14992 // PBLENDVB only available on SSE 4.1
14993 if (!Subtarget->hasSSE41())
14996 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14998 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14999 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15000 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15001 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15002 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15006 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15009 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15010 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15012 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15014 if (!N0.hasOneUse() || !N1.hasOneUse())
15017 SDValue ShAmt0 = N0.getOperand(1);
15018 if (ShAmt0.getValueType() != MVT::i8)
15020 SDValue ShAmt1 = N1.getOperand(1);
15021 if (ShAmt1.getValueType() != MVT::i8)
15023 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15024 ShAmt0 = ShAmt0.getOperand(0);
15025 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15026 ShAmt1 = ShAmt1.getOperand(0);
15028 DebugLoc DL = N->getDebugLoc();
15029 unsigned Opc = X86ISD::SHLD;
15030 SDValue Op0 = N0.getOperand(0);
15031 SDValue Op1 = N1.getOperand(0);
15032 if (ShAmt0.getOpcode() == ISD::SUB) {
15033 Opc = X86ISD::SHRD;
15034 std::swap(Op0, Op1);
15035 std::swap(ShAmt0, ShAmt1);
15038 unsigned Bits = VT.getSizeInBits();
15039 if (ShAmt1.getOpcode() == ISD::SUB) {
15040 SDValue Sum = ShAmt1.getOperand(0);
15041 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15042 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15043 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15044 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15045 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15046 return DAG.getNode(Opc, DL, VT,
15048 DAG.getNode(ISD::TRUNCATE, DL,
15051 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15052 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15054 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15055 return DAG.getNode(Opc, DL, VT,
15056 N0.getOperand(0), N1.getOperand(0),
15057 DAG.getNode(ISD::TRUNCATE, DL,
15064 // Generate NEG and CMOV for integer abs.
15065 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15066 EVT VT = N->getValueType(0);
15068 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15069 // 8-bit integer abs to NEG and CMOV.
15070 if (VT.isInteger() && VT.getSizeInBits() == 8)
15073 SDValue N0 = N->getOperand(0);
15074 SDValue N1 = N->getOperand(1);
15075 DebugLoc DL = N->getDebugLoc();
15077 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15078 // and change it to SUB and CMOV.
15079 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15080 N0.getOpcode() == ISD::ADD &&
15081 N0.getOperand(1) == N1 &&
15082 N1.getOpcode() == ISD::SRA &&
15083 N1.getOperand(0) == N0.getOperand(0))
15084 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15085 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15086 // Generate SUB & CMOV.
15087 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15088 DAG.getConstant(0, VT), N0.getOperand(0));
15090 SDValue Ops[] = { N0.getOperand(0), Neg,
15091 DAG.getConstant(X86::COND_GE, MVT::i8),
15092 SDValue(Neg.getNode(), 1) };
15093 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15094 Ops, array_lengthof(Ops));
15099 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15100 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15101 TargetLowering::DAGCombinerInfo &DCI,
15102 const X86Subtarget *Subtarget) {
15103 if (DCI.isBeforeLegalizeOps())
15106 if (Subtarget->hasCMov()) {
15107 SDValue RV = performIntegerAbsCombine(N, DAG);
15112 // Try forming BMI if it is available.
15113 if (!Subtarget->hasBMI())
15116 EVT VT = N->getValueType(0);
15118 if (VT != MVT::i32 && VT != MVT::i64)
15121 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15123 // Create BLSMSK instructions by finding X ^ (X-1)
15124 SDValue N0 = N->getOperand(0);
15125 SDValue N1 = N->getOperand(1);
15126 DebugLoc DL = N->getDebugLoc();
15128 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15129 isAllOnes(N0.getOperand(1)))
15130 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15132 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15133 isAllOnes(N1.getOperand(1)))
15134 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15139 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15140 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15141 TargetLowering::DAGCombinerInfo &DCI,
15142 const X86Subtarget *Subtarget) {
15143 LoadSDNode *Ld = cast<LoadSDNode>(N);
15144 EVT RegVT = Ld->getValueType(0);
15145 EVT MemVT = Ld->getMemoryVT();
15146 DebugLoc dl = Ld->getDebugLoc();
15147 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15149 ISD::LoadExtType Ext = Ld->getExtensionType();
15151 // If this is a vector EXT Load then attempt to optimize it using a
15152 // shuffle. We need SSE4 for the shuffles.
15153 // TODO: It is possible to support ZExt by zeroing the undef values
15154 // during the shuffle phase or after the shuffle.
15155 if (RegVT.isVector() && RegVT.isInteger() &&
15156 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15157 assert(MemVT != RegVT && "Cannot extend to the same type");
15158 assert(MemVT.isVector() && "Must load a vector from memory");
15160 unsigned NumElems = RegVT.getVectorNumElements();
15161 unsigned RegSz = RegVT.getSizeInBits();
15162 unsigned MemSz = MemVT.getSizeInBits();
15163 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15165 // All sizes must be a power of two.
15166 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15169 // Attempt to load the original value using scalar loads.
15170 // Find the largest scalar type that divides the total loaded size.
15171 MVT SclrLoadTy = MVT::i8;
15172 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15173 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15174 MVT Tp = (MVT::SimpleValueType)tp;
15175 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15180 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15181 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15183 SclrLoadTy = MVT::f64;
15185 // Calculate the number of scalar loads that we need to perform
15186 // in order to load our vector from memory.
15187 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15189 // Represent our vector as a sequence of elements which are the
15190 // largest scalar that we can load.
15191 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15192 RegSz/SclrLoadTy.getSizeInBits());
15194 // Represent the data using the same element type that is stored in
15195 // memory. In practice, we ''widen'' MemVT.
15196 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15197 RegSz/MemVT.getScalarType().getSizeInBits());
15199 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15200 "Invalid vector type");
15202 // We can't shuffle using an illegal type.
15203 if (!TLI.isTypeLegal(WideVecVT))
15206 SmallVector<SDValue, 8> Chains;
15207 SDValue Ptr = Ld->getBasePtr();
15208 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15209 TLI.getPointerTy());
15210 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15212 for (unsigned i = 0; i < NumLoads; ++i) {
15213 // Perform a single load.
15214 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15215 Ptr, Ld->getPointerInfo(),
15216 Ld->isVolatile(), Ld->isNonTemporal(),
15217 Ld->isInvariant(), Ld->getAlignment());
15218 Chains.push_back(ScalarLoad.getValue(1));
15219 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15220 // another round of DAGCombining.
15222 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15224 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15225 ScalarLoad, DAG.getIntPtrConstant(i));
15227 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15230 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15233 // Bitcast the loaded value to a vector of the original element type, in
15234 // the size of the target vector type.
15235 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15236 unsigned SizeRatio = RegSz/MemSz;
15238 // Redistribute the loaded elements into the different locations.
15239 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15240 for (unsigned i = 0; i != NumElems; ++i)
15241 ShuffleVec[i*SizeRatio] = i;
15243 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15244 DAG.getUNDEF(WideVecVT),
15247 // Bitcast to the requested type.
15248 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15249 // Replace the original load with the new sequence
15250 // and return the new chain.
15251 return DCI.CombineTo(N, Shuff, TF, true);
15257 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15258 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15259 const X86Subtarget *Subtarget) {
15260 StoreSDNode *St = cast<StoreSDNode>(N);
15261 EVT VT = St->getValue().getValueType();
15262 EVT StVT = St->getMemoryVT();
15263 DebugLoc dl = St->getDebugLoc();
15264 SDValue StoredVal = St->getOperand(1);
15265 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15267 // If we are saving a concatenation of two XMM registers, perform two stores.
15268 // On Sandy Bridge, 256-bit memory operations are executed by two
15269 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15270 // memory operation.
15271 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15272 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15273 StoredVal.getNumOperands() == 2) {
15274 SDValue Value0 = StoredVal.getOperand(0);
15275 SDValue Value1 = StoredVal.getOperand(1);
15277 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15278 SDValue Ptr0 = St->getBasePtr();
15279 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15281 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15282 St->getPointerInfo(), St->isVolatile(),
15283 St->isNonTemporal(), St->getAlignment());
15284 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15285 St->getPointerInfo(), St->isVolatile(),
15286 St->isNonTemporal(), St->getAlignment());
15287 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15290 // Optimize trunc store (of multiple scalars) to shuffle and store.
15291 // First, pack all of the elements in one place. Next, store to memory
15292 // in fewer chunks.
15293 if (St->isTruncatingStore() && VT.isVector()) {
15294 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15295 unsigned NumElems = VT.getVectorNumElements();
15296 assert(StVT != VT && "Cannot truncate to the same type");
15297 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15298 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15300 // From, To sizes and ElemCount must be pow of two
15301 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15302 // We are going to use the original vector elt for storing.
15303 // Accumulated smaller vector elements must be a multiple of the store size.
15304 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15306 unsigned SizeRatio = FromSz / ToSz;
15308 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15310 // Create a type on which we perform the shuffle
15311 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15312 StVT.getScalarType(), NumElems*SizeRatio);
15314 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15316 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15317 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15318 for (unsigned i = 0; i != NumElems; ++i)
15319 ShuffleVec[i] = i * SizeRatio;
15321 // Can't shuffle using an illegal type.
15322 if (!TLI.isTypeLegal(WideVecVT))
15325 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15326 DAG.getUNDEF(WideVecVT),
15328 // At this point all of the data is stored at the bottom of the
15329 // register. We now need to save it to mem.
15331 // Find the largest store unit
15332 MVT StoreType = MVT::i8;
15333 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15334 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15335 MVT Tp = (MVT::SimpleValueType)tp;
15336 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15340 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15341 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15342 (64 <= NumElems * ToSz))
15343 StoreType = MVT::f64;
15345 // Bitcast the original vector into a vector of store-size units
15346 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15347 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15348 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15349 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15350 SmallVector<SDValue, 8> Chains;
15351 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15352 TLI.getPointerTy());
15353 SDValue Ptr = St->getBasePtr();
15355 // Perform one or more big stores into memory.
15356 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15357 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15358 StoreType, ShuffWide,
15359 DAG.getIntPtrConstant(i));
15360 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15361 St->getPointerInfo(), St->isVolatile(),
15362 St->isNonTemporal(), St->getAlignment());
15363 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15364 Chains.push_back(Ch);
15367 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15372 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15373 // the FP state in cases where an emms may be missing.
15374 // A preferable solution to the general problem is to figure out the right
15375 // places to insert EMMS. This qualifies as a quick hack.
15377 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15378 if (VT.getSizeInBits() != 64)
15381 const Function *F = DAG.getMachineFunction().getFunction();
15382 bool NoImplicitFloatOps = F->getFnAttributes().
15383 hasAttribute(Attributes::NoImplicitFloat);
15384 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15385 && Subtarget->hasSSE2();
15386 if ((VT.isVector() ||
15387 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15388 isa<LoadSDNode>(St->getValue()) &&
15389 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15390 St->getChain().hasOneUse() && !St->isVolatile()) {
15391 SDNode* LdVal = St->getValue().getNode();
15392 LoadSDNode *Ld = 0;
15393 int TokenFactorIndex = -1;
15394 SmallVector<SDValue, 8> Ops;
15395 SDNode* ChainVal = St->getChain().getNode();
15396 // Must be a store of a load. We currently handle two cases: the load
15397 // is a direct child, and it's under an intervening TokenFactor. It is
15398 // possible to dig deeper under nested TokenFactors.
15399 if (ChainVal == LdVal)
15400 Ld = cast<LoadSDNode>(St->getChain());
15401 else if (St->getValue().hasOneUse() &&
15402 ChainVal->getOpcode() == ISD::TokenFactor) {
15403 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15404 if (ChainVal->getOperand(i).getNode() == LdVal) {
15405 TokenFactorIndex = i;
15406 Ld = cast<LoadSDNode>(St->getValue());
15408 Ops.push_back(ChainVal->getOperand(i));
15412 if (!Ld || !ISD::isNormalLoad(Ld))
15415 // If this is not the MMX case, i.e. we are just turning i64 load/store
15416 // into f64 load/store, avoid the transformation if there are multiple
15417 // uses of the loaded value.
15418 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15421 DebugLoc LdDL = Ld->getDebugLoc();
15422 DebugLoc StDL = N->getDebugLoc();
15423 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15424 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15426 if (Subtarget->is64Bit() || F64IsLegal) {
15427 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15428 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15429 Ld->getPointerInfo(), Ld->isVolatile(),
15430 Ld->isNonTemporal(), Ld->isInvariant(),
15431 Ld->getAlignment());
15432 SDValue NewChain = NewLd.getValue(1);
15433 if (TokenFactorIndex != -1) {
15434 Ops.push_back(NewChain);
15435 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15438 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15439 St->getPointerInfo(),
15440 St->isVolatile(), St->isNonTemporal(),
15441 St->getAlignment());
15444 // Otherwise, lower to two pairs of 32-bit loads / stores.
15445 SDValue LoAddr = Ld->getBasePtr();
15446 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15447 DAG.getConstant(4, MVT::i32));
15449 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15450 Ld->getPointerInfo(),
15451 Ld->isVolatile(), Ld->isNonTemporal(),
15452 Ld->isInvariant(), Ld->getAlignment());
15453 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15454 Ld->getPointerInfo().getWithOffset(4),
15455 Ld->isVolatile(), Ld->isNonTemporal(),
15457 MinAlign(Ld->getAlignment(), 4));
15459 SDValue NewChain = LoLd.getValue(1);
15460 if (TokenFactorIndex != -1) {
15461 Ops.push_back(LoLd);
15462 Ops.push_back(HiLd);
15463 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15467 LoAddr = St->getBasePtr();
15468 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15469 DAG.getConstant(4, MVT::i32));
15471 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15472 St->getPointerInfo(),
15473 St->isVolatile(), St->isNonTemporal(),
15474 St->getAlignment());
15475 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15476 St->getPointerInfo().getWithOffset(4),
15478 St->isNonTemporal(),
15479 MinAlign(St->getAlignment(), 4));
15480 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15485 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15486 /// and return the operands for the horizontal operation in LHS and RHS. A
15487 /// horizontal operation performs the binary operation on successive elements
15488 /// of its first operand, then on successive elements of its second operand,
15489 /// returning the resulting values in a vector. For example, if
15490 /// A = < float a0, float a1, float a2, float a3 >
15492 /// B = < float b0, float b1, float b2, float b3 >
15493 /// then the result of doing a horizontal operation on A and B is
15494 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15495 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15496 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15497 /// set to A, RHS to B, and the routine returns 'true'.
15498 /// Note that the binary operation should have the property that if one of the
15499 /// operands is UNDEF then the result is UNDEF.
15500 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15501 // Look for the following pattern: if
15502 // A = < float a0, float a1, float a2, float a3 >
15503 // B = < float b0, float b1, float b2, float b3 >
15505 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15506 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15507 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15508 // which is A horizontal-op B.
15510 // At least one of the operands should be a vector shuffle.
15511 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15512 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15515 EVT VT = LHS.getValueType();
15517 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15518 "Unsupported vector type for horizontal add/sub");
15520 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15521 // operate independently on 128-bit lanes.
15522 unsigned NumElts = VT.getVectorNumElements();
15523 unsigned NumLanes = VT.getSizeInBits()/128;
15524 unsigned NumLaneElts = NumElts / NumLanes;
15525 assert((NumLaneElts % 2 == 0) &&
15526 "Vector type should have an even number of elements in each lane");
15527 unsigned HalfLaneElts = NumLaneElts/2;
15529 // View LHS in the form
15530 // LHS = VECTOR_SHUFFLE A, B, LMask
15531 // If LHS is not a shuffle then pretend it is the shuffle
15532 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15533 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15536 SmallVector<int, 16> LMask(NumElts);
15537 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15538 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15539 A = LHS.getOperand(0);
15540 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15541 B = LHS.getOperand(1);
15542 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15543 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15545 if (LHS.getOpcode() != ISD::UNDEF)
15547 for (unsigned i = 0; i != NumElts; ++i)
15551 // Likewise, view RHS in the form
15552 // RHS = VECTOR_SHUFFLE C, D, RMask
15554 SmallVector<int, 16> RMask(NumElts);
15555 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15556 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15557 C = RHS.getOperand(0);
15558 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15559 D = RHS.getOperand(1);
15560 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15561 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15563 if (RHS.getOpcode() != ISD::UNDEF)
15565 for (unsigned i = 0; i != NumElts; ++i)
15569 // Check that the shuffles are both shuffling the same vectors.
15570 if (!(A == C && B == D) && !(A == D && B == C))
15573 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15574 if (!A.getNode() && !B.getNode())
15577 // If A and B occur in reverse order in RHS, then "swap" them (which means
15578 // rewriting the mask).
15580 CommuteVectorShuffleMask(RMask, NumElts);
15582 // At this point LHS and RHS are equivalent to
15583 // LHS = VECTOR_SHUFFLE A, B, LMask
15584 // RHS = VECTOR_SHUFFLE A, B, RMask
15585 // Check that the masks correspond to performing a horizontal operation.
15586 for (unsigned i = 0; i != NumElts; ++i) {
15587 int LIdx = LMask[i], RIdx = RMask[i];
15589 // Ignore any UNDEF components.
15590 if (LIdx < 0 || RIdx < 0 ||
15591 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15592 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15595 // Check that successive elements are being operated on. If not, this is
15596 // not a horizontal operation.
15597 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15598 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15599 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15600 if (!(LIdx == Index && RIdx == Index + 1) &&
15601 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15605 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15606 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15610 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15611 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15612 const X86Subtarget *Subtarget) {
15613 EVT VT = N->getValueType(0);
15614 SDValue LHS = N->getOperand(0);
15615 SDValue RHS = N->getOperand(1);
15617 // Try to synthesize horizontal adds from adds of shuffles.
15618 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15619 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15620 isHorizontalBinOp(LHS, RHS, true))
15621 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15625 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15626 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15627 const X86Subtarget *Subtarget) {
15628 EVT VT = N->getValueType(0);
15629 SDValue LHS = N->getOperand(0);
15630 SDValue RHS = N->getOperand(1);
15632 // Try to synthesize horizontal subs from subs of shuffles.
15633 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15634 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15635 isHorizontalBinOp(LHS, RHS, false))
15636 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15640 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15641 /// X86ISD::FXOR nodes.
15642 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15643 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15644 // F[X]OR(0.0, x) -> x
15645 // F[X]OR(x, 0.0) -> x
15646 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15647 if (C->getValueAPF().isPosZero())
15648 return N->getOperand(1);
15649 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15650 if (C->getValueAPF().isPosZero())
15651 return N->getOperand(0);
15655 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15656 /// X86ISD::FMAX nodes.
15657 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15658 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15660 // Only perform optimizations if UnsafeMath is used.
15661 if (!DAG.getTarget().Options.UnsafeFPMath)
15664 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15665 // into FMINC and FMAXC, which are Commutative operations.
15666 unsigned NewOp = 0;
15667 switch (N->getOpcode()) {
15668 default: llvm_unreachable("unknown opcode");
15669 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
15670 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
15673 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15674 N->getOperand(0), N->getOperand(1));
15678 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15679 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15680 // FAND(0.0, x) -> 0.0
15681 // FAND(x, 0.0) -> 0.0
15682 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15683 if (C->getValueAPF().isPosZero())
15684 return N->getOperand(0);
15685 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15686 if (C->getValueAPF().isPosZero())
15687 return N->getOperand(1);
15691 static SDValue PerformBTCombine(SDNode *N,
15693 TargetLowering::DAGCombinerInfo &DCI) {
15694 // BT ignores high bits in the bit index operand.
15695 SDValue Op1 = N->getOperand(1);
15696 if (Op1.hasOneUse()) {
15697 unsigned BitWidth = Op1.getValueSizeInBits();
15698 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15699 APInt KnownZero, KnownOne;
15700 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15701 !DCI.isBeforeLegalizeOps());
15702 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15703 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15704 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15705 DCI.CommitTargetLoweringOpt(TLO);
15710 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15711 SDValue Op = N->getOperand(0);
15712 if (Op.getOpcode() == ISD::BITCAST)
15713 Op = Op.getOperand(0);
15714 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15715 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15716 VT.getVectorElementType().getSizeInBits() ==
15717 OpVT.getVectorElementType().getSizeInBits()) {
15718 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15723 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15724 TargetLowering::DAGCombinerInfo &DCI,
15725 const X86Subtarget *Subtarget) {
15726 if (!DCI.isBeforeLegalizeOps())
15729 if (!Subtarget->hasAVX())
15732 EVT VT = N->getValueType(0);
15733 SDValue Op = N->getOperand(0);
15734 EVT OpVT = Op.getValueType();
15735 DebugLoc dl = N->getDebugLoc();
15737 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15738 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15740 if (Subtarget->hasAVX2())
15741 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15743 // Optimize vectors in AVX mode
15744 // Sign extend v8i16 to v8i32 and
15747 // Divide input vector into two parts
15748 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15749 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15750 // concat the vectors to original VT
15752 unsigned NumElems = OpVT.getVectorNumElements();
15753 SDValue Undef = DAG.getUNDEF(OpVT);
15755 SmallVector<int,8> ShufMask1(NumElems, -1);
15756 for (unsigned i = 0; i != NumElems/2; ++i)
15759 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15761 SmallVector<int,8> ShufMask2(NumElems, -1);
15762 for (unsigned i = 0; i != NumElems/2; ++i)
15763 ShufMask2[i] = i + NumElems/2;
15765 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15767 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15768 VT.getVectorNumElements()/2);
15770 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15771 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15773 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15778 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15779 const X86Subtarget* Subtarget) {
15780 DebugLoc dl = N->getDebugLoc();
15781 EVT VT = N->getValueType(0);
15783 // Let legalize expand this if it isn't a legal type yet.
15784 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15787 EVT ScalarVT = VT.getScalarType();
15788 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15789 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15792 SDValue A = N->getOperand(0);
15793 SDValue B = N->getOperand(1);
15794 SDValue C = N->getOperand(2);
15796 bool NegA = (A.getOpcode() == ISD::FNEG);
15797 bool NegB = (B.getOpcode() == ISD::FNEG);
15798 bool NegC = (C.getOpcode() == ISD::FNEG);
15800 // Negative multiplication when NegA xor NegB
15801 bool NegMul = (NegA != NegB);
15803 A = A.getOperand(0);
15805 B = B.getOperand(0);
15807 C = C.getOperand(0);
15811 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15813 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15815 return DAG.getNode(Opcode, dl, VT, A, B, C);
15818 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15819 TargetLowering::DAGCombinerInfo &DCI,
15820 const X86Subtarget *Subtarget) {
15821 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15822 // (and (i32 x86isd::setcc_carry), 1)
15823 // This eliminates the zext. This transformation is necessary because
15824 // ISD::SETCC is always legalized to i8.
15825 DebugLoc dl = N->getDebugLoc();
15826 SDValue N0 = N->getOperand(0);
15827 EVT VT = N->getValueType(0);
15828 EVT OpVT = N0.getValueType();
15830 if (N0.getOpcode() == ISD::AND &&
15832 N0.getOperand(0).hasOneUse()) {
15833 SDValue N00 = N0.getOperand(0);
15834 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15836 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15837 if (!C || C->getZExtValue() != 1)
15839 return DAG.getNode(ISD::AND, dl, VT,
15840 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15841 N00.getOperand(0), N00.getOperand(1)),
15842 DAG.getConstant(1, VT));
15845 // Optimize vectors in AVX mode:
15848 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15849 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15850 // Concat upper and lower parts.
15853 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15854 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15855 // Concat upper and lower parts.
15857 if (!DCI.isBeforeLegalizeOps())
15860 if (!Subtarget->hasAVX())
15863 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15864 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15866 if (Subtarget->hasAVX2())
15867 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15869 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15870 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15871 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15873 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15874 VT.getVectorNumElements()/2);
15876 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15877 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15879 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15885 // Optimize x == -y --> x+y == 0
15886 // x != -y --> x+y != 0
15887 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15888 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15889 SDValue LHS = N->getOperand(0);
15890 SDValue RHS = N->getOperand(1);
15892 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15893 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15894 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15895 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15896 LHS.getValueType(), RHS, LHS.getOperand(1));
15897 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15898 addV, DAG.getConstant(0, addV.getValueType()), CC);
15900 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15901 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15902 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15903 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15904 RHS.getValueType(), LHS, RHS.getOperand(1));
15905 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15906 addV, DAG.getConstant(0, addV.getValueType()), CC);
15911 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15912 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15913 TargetLowering::DAGCombinerInfo &DCI,
15914 const X86Subtarget *Subtarget) {
15915 DebugLoc DL = N->getDebugLoc();
15916 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15917 SDValue EFLAGS = N->getOperand(1);
15919 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15920 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15922 if (CC == X86::COND_B)
15923 return DAG.getNode(ISD::AND, DL, MVT::i8,
15924 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15925 DAG.getConstant(CC, MVT::i8), EFLAGS),
15926 DAG.getConstant(1, MVT::i8));
15930 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15931 if (Flags.getNode()) {
15932 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15933 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15939 // Optimize branch condition evaluation.
15941 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15942 TargetLowering::DAGCombinerInfo &DCI,
15943 const X86Subtarget *Subtarget) {
15944 DebugLoc DL = N->getDebugLoc();
15945 SDValue Chain = N->getOperand(0);
15946 SDValue Dest = N->getOperand(1);
15947 SDValue EFLAGS = N->getOperand(3);
15948 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15952 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15953 if (Flags.getNode()) {
15954 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15955 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15962 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15963 SDValue Op0 = N->getOperand(0);
15964 EVT InVT = Op0->getValueType(0);
15966 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15967 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15968 DebugLoc dl = N->getDebugLoc();
15969 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15970 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15971 // Notice that we use SINT_TO_FP because we know that the high bits
15972 // are zero and SINT_TO_FP is better supported by the hardware.
15973 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15979 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15980 const X86TargetLowering *XTLI) {
15981 SDValue Op0 = N->getOperand(0);
15982 EVT InVT = Op0->getValueType(0);
15984 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15985 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15986 DebugLoc dl = N->getDebugLoc();
15987 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15988 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15989 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15992 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15993 // a 32-bit target where SSE doesn't support i64->FP operations.
15994 if (Op0.getOpcode() == ISD::LOAD) {
15995 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15996 EVT VT = Ld->getValueType(0);
15997 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15998 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15999 !XTLI->getSubtarget()->is64Bit() &&
16000 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16001 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16002 Ld->getChain(), Op0, DAG);
16003 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16010 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
16011 EVT VT = N->getValueType(0);
16013 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
16014 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
16015 DebugLoc dl = N->getDebugLoc();
16016 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16017 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
16018 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
16024 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16025 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16026 X86TargetLowering::DAGCombinerInfo &DCI) {
16027 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16028 // the result is either zero or one (depending on the input carry bit).
16029 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16030 if (X86::isZeroNode(N->getOperand(0)) &&
16031 X86::isZeroNode(N->getOperand(1)) &&
16032 // We don't have a good way to replace an EFLAGS use, so only do this when
16034 SDValue(N, 1).use_empty()) {
16035 DebugLoc DL = N->getDebugLoc();
16036 EVT VT = N->getValueType(0);
16037 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16038 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16039 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16040 DAG.getConstant(X86::COND_B,MVT::i8),
16042 DAG.getConstant(1, VT));
16043 return DCI.CombineTo(N, Res1, CarryOut);
16049 // fold (add Y, (sete X, 0)) -> adc 0, Y
16050 // (add Y, (setne X, 0)) -> sbb -1, Y
16051 // (sub (sete X, 0), Y) -> sbb 0, Y
16052 // (sub (setne X, 0), Y) -> adc -1, Y
16053 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16054 DebugLoc DL = N->getDebugLoc();
16056 // Look through ZExts.
16057 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16058 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16061 SDValue SetCC = Ext.getOperand(0);
16062 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16065 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16066 if (CC != X86::COND_E && CC != X86::COND_NE)
16069 SDValue Cmp = SetCC.getOperand(1);
16070 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16071 !X86::isZeroNode(Cmp.getOperand(1)) ||
16072 !Cmp.getOperand(0).getValueType().isInteger())
16075 SDValue CmpOp0 = Cmp.getOperand(0);
16076 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16077 DAG.getConstant(1, CmpOp0.getValueType()));
16079 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16080 if (CC == X86::COND_NE)
16081 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16082 DL, OtherVal.getValueType(), OtherVal,
16083 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16084 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16085 DL, OtherVal.getValueType(), OtherVal,
16086 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16089 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16090 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16091 const X86Subtarget *Subtarget) {
16092 EVT VT = N->getValueType(0);
16093 SDValue Op0 = N->getOperand(0);
16094 SDValue Op1 = N->getOperand(1);
16096 // Try to synthesize horizontal adds from adds of shuffles.
16097 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16098 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16099 isHorizontalBinOp(Op0, Op1, true))
16100 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16102 return OptimizeConditionalInDecrement(N, DAG);
16105 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16106 const X86Subtarget *Subtarget) {
16107 SDValue Op0 = N->getOperand(0);
16108 SDValue Op1 = N->getOperand(1);
16110 // X86 can't encode an immediate LHS of a sub. See if we can push the
16111 // negation into a preceding instruction.
16112 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16113 // If the RHS of the sub is a XOR with one use and a constant, invert the
16114 // immediate. Then add one to the LHS of the sub so we can turn
16115 // X-Y -> X+~Y+1, saving one register.
16116 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16117 isa<ConstantSDNode>(Op1.getOperand(1))) {
16118 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16119 EVT VT = Op0.getValueType();
16120 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16122 DAG.getConstant(~XorC, VT));
16123 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16124 DAG.getConstant(C->getAPIntValue()+1, VT));
16128 // Try to synthesize horizontal adds from adds of shuffles.
16129 EVT VT = N->getValueType(0);
16130 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16131 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16132 isHorizontalBinOp(Op0, Op1, true))
16133 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16135 return OptimizeConditionalInDecrement(N, DAG);
16138 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16139 DAGCombinerInfo &DCI) const {
16140 SelectionDAG &DAG = DCI.DAG;
16141 switch (N->getOpcode()) {
16143 case ISD::EXTRACT_VECTOR_ELT:
16144 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16146 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16147 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16148 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16149 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16150 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16151 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16154 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16155 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16156 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16157 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16158 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16159 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16160 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16161 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16162 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
16163 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16164 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16166 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16168 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16169 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16170 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16171 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16172 case ISD::ANY_EXTEND:
16173 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16174 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16175 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16176 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16177 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16178 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16179 case X86ISD::SHUFP: // Handle all target specific shuffles
16180 case X86ISD::PALIGN:
16181 case X86ISD::UNPCKH:
16182 case X86ISD::UNPCKL:
16183 case X86ISD::MOVHLPS:
16184 case X86ISD::MOVLHPS:
16185 case X86ISD::PSHUFD:
16186 case X86ISD::PSHUFHW:
16187 case X86ISD::PSHUFLW:
16188 case X86ISD::MOVSS:
16189 case X86ISD::MOVSD:
16190 case X86ISD::VPERMILP:
16191 case X86ISD::VPERM2X128:
16192 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16193 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16199 /// isTypeDesirableForOp - Return true if the target has native support for
16200 /// the specified value type and it is 'desirable' to use the type for the
16201 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16202 /// instruction encodings are longer and some i16 instructions are slow.
16203 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16204 if (!isTypeLegal(VT))
16206 if (VT != MVT::i16)
16213 case ISD::SIGN_EXTEND:
16214 case ISD::ZERO_EXTEND:
16215 case ISD::ANY_EXTEND:
16228 /// IsDesirableToPromoteOp - This method query the target whether it is
16229 /// beneficial for dag combiner to promote the specified node. If true, it
16230 /// should return the desired promotion type by reference.
16231 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16232 EVT VT = Op.getValueType();
16233 if (VT != MVT::i16)
16236 bool Promote = false;
16237 bool Commute = false;
16238 switch (Op.getOpcode()) {
16241 LoadSDNode *LD = cast<LoadSDNode>(Op);
16242 // If the non-extending load has a single use and it's not live out, then it
16243 // might be folded.
16244 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16245 Op.hasOneUse()*/) {
16246 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16247 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16248 // The only case where we'd want to promote LOAD (rather then it being
16249 // promoted as an operand is when it's only use is liveout.
16250 if (UI->getOpcode() != ISD::CopyToReg)
16257 case ISD::SIGN_EXTEND:
16258 case ISD::ZERO_EXTEND:
16259 case ISD::ANY_EXTEND:
16264 SDValue N0 = Op.getOperand(0);
16265 // Look out for (store (shl (load), x)).
16266 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16279 SDValue N0 = Op.getOperand(0);
16280 SDValue N1 = Op.getOperand(1);
16281 if (!Commute && MayFoldLoad(N1))
16283 // Avoid disabling potential load folding opportunities.
16284 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16286 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16296 //===----------------------------------------------------------------------===//
16297 // X86 Inline Assembly Support
16298 //===----------------------------------------------------------------------===//
16301 // Helper to match a string separated by whitespace.
16302 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16303 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16305 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16306 StringRef piece(*args[i]);
16307 if (!s.startswith(piece)) // Check if the piece matches.
16310 s = s.substr(piece.size());
16311 StringRef::size_type pos = s.find_first_not_of(" \t");
16312 if (pos == 0) // We matched a prefix.
16320 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16323 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16324 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16326 std::string AsmStr = IA->getAsmString();
16328 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16329 if (!Ty || Ty->getBitWidth() % 16 != 0)
16332 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16333 SmallVector<StringRef, 4> AsmPieces;
16334 SplitString(AsmStr, AsmPieces, ";\n");
16336 switch (AsmPieces.size()) {
16337 default: return false;
16339 // FIXME: this should verify that we are targeting a 486 or better. If not,
16340 // we will turn this bswap into something that will be lowered to logical
16341 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16342 // lower so don't worry about this.
16344 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16345 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16346 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16347 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16348 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16349 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16350 // No need to check constraints, nothing other than the equivalent of
16351 // "=r,0" would be valid here.
16352 return IntrinsicLowering::LowerToByteSwap(CI);
16355 // rorw $$8, ${0:w} --> llvm.bswap.i16
16356 if (CI->getType()->isIntegerTy(16) &&
16357 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16358 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16359 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16361 const std::string &ConstraintsStr = IA->getConstraintString();
16362 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16363 std::sort(AsmPieces.begin(), AsmPieces.end());
16364 if (AsmPieces.size() == 4 &&
16365 AsmPieces[0] == "~{cc}" &&
16366 AsmPieces[1] == "~{dirflag}" &&
16367 AsmPieces[2] == "~{flags}" &&
16368 AsmPieces[3] == "~{fpsr}")
16369 return IntrinsicLowering::LowerToByteSwap(CI);
16373 if (CI->getType()->isIntegerTy(32) &&
16374 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16375 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16376 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16377 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16379 const std::string &ConstraintsStr = IA->getConstraintString();
16380 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16381 std::sort(AsmPieces.begin(), AsmPieces.end());
16382 if (AsmPieces.size() == 4 &&
16383 AsmPieces[0] == "~{cc}" &&
16384 AsmPieces[1] == "~{dirflag}" &&
16385 AsmPieces[2] == "~{flags}" &&
16386 AsmPieces[3] == "~{fpsr}")
16387 return IntrinsicLowering::LowerToByteSwap(CI);
16390 if (CI->getType()->isIntegerTy(64)) {
16391 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16392 if (Constraints.size() >= 2 &&
16393 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16394 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16395 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16396 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16397 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16398 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16399 return IntrinsicLowering::LowerToByteSwap(CI);
16409 /// getConstraintType - Given a constraint letter, return the type of
16410 /// constraint it is for this target.
16411 X86TargetLowering::ConstraintType
16412 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16413 if (Constraint.size() == 1) {
16414 switch (Constraint[0]) {
16425 return C_RegisterClass;
16449 return TargetLowering::getConstraintType(Constraint);
16452 /// Examine constraint type and operand type and determine a weight value.
16453 /// This object must already have been set up with the operand type
16454 /// and the current alternative constraint selected.
16455 TargetLowering::ConstraintWeight
16456 X86TargetLowering::getSingleConstraintMatchWeight(
16457 AsmOperandInfo &info, const char *constraint) const {
16458 ConstraintWeight weight = CW_Invalid;
16459 Value *CallOperandVal = info.CallOperandVal;
16460 // If we don't have a value, we can't do a match,
16461 // but allow it at the lowest weight.
16462 if (CallOperandVal == NULL)
16464 Type *type = CallOperandVal->getType();
16465 // Look at the constraint type.
16466 switch (*constraint) {
16468 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16479 if (CallOperandVal->getType()->isIntegerTy())
16480 weight = CW_SpecificReg;
16485 if (type->isFloatingPointTy())
16486 weight = CW_SpecificReg;
16489 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16490 weight = CW_SpecificReg;
16494 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16495 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16496 weight = CW_Register;
16499 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16500 if (C->getZExtValue() <= 31)
16501 weight = CW_Constant;
16505 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16506 if (C->getZExtValue() <= 63)
16507 weight = CW_Constant;
16511 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16512 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16513 weight = CW_Constant;
16517 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16518 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16519 weight = CW_Constant;
16523 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16524 if (C->getZExtValue() <= 3)
16525 weight = CW_Constant;
16529 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16530 if (C->getZExtValue() <= 0xff)
16531 weight = CW_Constant;
16536 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16537 weight = CW_Constant;
16541 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16542 if ((C->getSExtValue() >= -0x80000000LL) &&
16543 (C->getSExtValue() <= 0x7fffffffLL))
16544 weight = CW_Constant;
16548 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16549 if (C->getZExtValue() <= 0xffffffff)
16550 weight = CW_Constant;
16557 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16558 /// with another that has more specific requirements based on the type of the
16559 /// corresponding operand.
16560 const char *X86TargetLowering::
16561 LowerXConstraint(EVT ConstraintVT) const {
16562 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16563 // 'f' like normal targets.
16564 if (ConstraintVT.isFloatingPoint()) {
16565 if (Subtarget->hasSSE2())
16567 if (Subtarget->hasSSE1())
16571 return TargetLowering::LowerXConstraint(ConstraintVT);
16574 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16575 /// vector. If it is invalid, don't add anything to Ops.
16576 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16577 std::string &Constraint,
16578 std::vector<SDValue>&Ops,
16579 SelectionDAG &DAG) const {
16580 SDValue Result(0, 0);
16582 // Only support length 1 constraints for now.
16583 if (Constraint.length() > 1) return;
16585 char ConstraintLetter = Constraint[0];
16586 switch (ConstraintLetter) {
16589 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16590 if (C->getZExtValue() <= 31) {
16591 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16597 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16598 if (C->getZExtValue() <= 63) {
16599 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16606 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16607 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16613 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16614 if (C->getZExtValue() <= 255) {
16615 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16621 // 32-bit signed value
16622 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16623 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16624 C->getSExtValue())) {
16625 // Widen to 64 bits here to get it sign extended.
16626 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16629 // FIXME gcc accepts some relocatable values here too, but only in certain
16630 // memory models; it's complicated.
16635 // 32-bit unsigned value
16636 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16637 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16638 C->getZExtValue())) {
16639 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16643 // FIXME gcc accepts some relocatable values here too, but only in certain
16644 // memory models; it's complicated.
16648 // Literal immediates are always ok.
16649 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16650 // Widen to 64 bits here to get it sign extended.
16651 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16655 // In any sort of PIC mode addresses need to be computed at runtime by
16656 // adding in a register or some sort of table lookup. These can't
16657 // be used as immediates.
16658 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16661 // If we are in non-pic codegen mode, we allow the address of a global (with
16662 // an optional displacement) to be used with 'i'.
16663 GlobalAddressSDNode *GA = 0;
16664 int64_t Offset = 0;
16666 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16668 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16669 Offset += GA->getOffset();
16671 } else if (Op.getOpcode() == ISD::ADD) {
16672 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16673 Offset += C->getZExtValue();
16674 Op = Op.getOperand(0);
16677 } else if (Op.getOpcode() == ISD::SUB) {
16678 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16679 Offset += -C->getZExtValue();
16680 Op = Op.getOperand(0);
16685 // Otherwise, this isn't something we can handle, reject it.
16689 const GlobalValue *GV = GA->getGlobal();
16690 // If we require an extra load to get this address, as in PIC mode, we
16691 // can't accept it.
16692 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16693 getTargetMachine())))
16696 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16697 GA->getValueType(0), Offset);
16702 if (Result.getNode()) {
16703 Ops.push_back(Result);
16706 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16709 std::pair<unsigned, const TargetRegisterClass*>
16710 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16712 // First, see if this is a constraint that directly corresponds to an LLVM
16714 if (Constraint.size() == 1) {
16715 // GCC Constraint Letters
16716 switch (Constraint[0]) {
16718 // TODO: Slight differences here in allocation order and leaving
16719 // RIP in the class. Do they matter any more here than they do
16720 // in the normal allocation?
16721 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16722 if (Subtarget->is64Bit()) {
16723 if (VT == MVT::i32 || VT == MVT::f32)
16724 return std::make_pair(0U, &X86::GR32RegClass);
16725 if (VT == MVT::i16)
16726 return std::make_pair(0U, &X86::GR16RegClass);
16727 if (VT == MVT::i8 || VT == MVT::i1)
16728 return std::make_pair(0U, &X86::GR8RegClass);
16729 if (VT == MVT::i64 || VT == MVT::f64)
16730 return std::make_pair(0U, &X86::GR64RegClass);
16733 // 32-bit fallthrough
16734 case 'Q': // Q_REGS
16735 if (VT == MVT::i32 || VT == MVT::f32)
16736 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16737 if (VT == MVT::i16)
16738 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16739 if (VT == MVT::i8 || VT == MVT::i1)
16740 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16741 if (VT == MVT::i64)
16742 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16744 case 'r': // GENERAL_REGS
16745 case 'l': // INDEX_REGS
16746 if (VT == MVT::i8 || VT == MVT::i1)
16747 return std::make_pair(0U, &X86::GR8RegClass);
16748 if (VT == MVT::i16)
16749 return std::make_pair(0U, &X86::GR16RegClass);
16750 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16751 return std::make_pair(0U, &X86::GR32RegClass);
16752 return std::make_pair(0U, &X86::GR64RegClass);
16753 case 'R': // LEGACY_REGS
16754 if (VT == MVT::i8 || VT == MVT::i1)
16755 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16756 if (VT == MVT::i16)
16757 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16758 if (VT == MVT::i32 || !Subtarget->is64Bit())
16759 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16760 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16761 case 'f': // FP Stack registers.
16762 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16763 // value to the correct fpstack register class.
16764 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16765 return std::make_pair(0U, &X86::RFP32RegClass);
16766 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16767 return std::make_pair(0U, &X86::RFP64RegClass);
16768 return std::make_pair(0U, &X86::RFP80RegClass);
16769 case 'y': // MMX_REGS if MMX allowed.
16770 if (!Subtarget->hasMMX()) break;
16771 return std::make_pair(0U, &X86::VR64RegClass);
16772 case 'Y': // SSE_REGS if SSE2 allowed
16773 if (!Subtarget->hasSSE2()) break;
16775 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16776 if (!Subtarget->hasSSE1()) break;
16778 switch (VT.getSimpleVT().SimpleTy) {
16780 // Scalar SSE types.
16783 return std::make_pair(0U, &X86::FR32RegClass);
16786 return std::make_pair(0U, &X86::FR64RegClass);
16794 return std::make_pair(0U, &X86::VR128RegClass);
16802 return std::make_pair(0U, &X86::VR256RegClass);
16808 // Use the default implementation in TargetLowering to convert the register
16809 // constraint into a member of a register class.
16810 std::pair<unsigned, const TargetRegisterClass*> Res;
16811 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16813 // Not found as a standard register?
16814 if (Res.second == 0) {
16815 // Map st(0) -> st(7) -> ST0
16816 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16817 tolower(Constraint[1]) == 's' &&
16818 tolower(Constraint[2]) == 't' &&
16819 Constraint[3] == '(' &&
16820 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16821 Constraint[5] == ')' &&
16822 Constraint[6] == '}') {
16824 Res.first = X86::ST0+Constraint[4]-'0';
16825 Res.second = &X86::RFP80RegClass;
16829 // GCC allows "st(0)" to be called just plain "st".
16830 if (StringRef("{st}").equals_lower(Constraint)) {
16831 Res.first = X86::ST0;
16832 Res.second = &X86::RFP80RegClass;
16837 if (StringRef("{flags}").equals_lower(Constraint)) {
16838 Res.first = X86::EFLAGS;
16839 Res.second = &X86::CCRRegClass;
16843 // 'A' means EAX + EDX.
16844 if (Constraint == "A") {
16845 Res.first = X86::EAX;
16846 Res.second = &X86::GR32_ADRegClass;
16852 // Otherwise, check to see if this is a register class of the wrong value
16853 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16854 // turn into {ax},{dx}.
16855 if (Res.second->hasType(VT))
16856 return Res; // Correct type already, nothing to do.
16858 // All of the single-register GCC register classes map their values onto
16859 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16860 // really want an 8-bit or 32-bit register, map to the appropriate register
16861 // class and return the appropriate register.
16862 if (Res.second == &X86::GR16RegClass) {
16863 if (VT == MVT::i8) {
16864 unsigned DestReg = 0;
16865 switch (Res.first) {
16867 case X86::AX: DestReg = X86::AL; break;
16868 case X86::DX: DestReg = X86::DL; break;
16869 case X86::CX: DestReg = X86::CL; break;
16870 case X86::BX: DestReg = X86::BL; break;
16873 Res.first = DestReg;
16874 Res.second = &X86::GR8RegClass;
16876 } else if (VT == MVT::i32) {
16877 unsigned DestReg = 0;
16878 switch (Res.first) {
16880 case X86::AX: DestReg = X86::EAX; break;
16881 case X86::DX: DestReg = X86::EDX; break;
16882 case X86::CX: DestReg = X86::ECX; break;
16883 case X86::BX: DestReg = X86::EBX; break;
16884 case X86::SI: DestReg = X86::ESI; break;
16885 case X86::DI: DestReg = X86::EDI; break;
16886 case X86::BP: DestReg = X86::EBP; break;
16887 case X86::SP: DestReg = X86::ESP; break;
16890 Res.first = DestReg;
16891 Res.second = &X86::GR32RegClass;
16893 } else if (VT == MVT::i64) {
16894 unsigned DestReg = 0;
16895 switch (Res.first) {
16897 case X86::AX: DestReg = X86::RAX; break;
16898 case X86::DX: DestReg = X86::RDX; break;
16899 case X86::CX: DestReg = X86::RCX; break;
16900 case X86::BX: DestReg = X86::RBX; break;
16901 case X86::SI: DestReg = X86::RSI; break;
16902 case X86::DI: DestReg = X86::RDI; break;
16903 case X86::BP: DestReg = X86::RBP; break;
16904 case X86::SP: DestReg = X86::RSP; break;
16907 Res.first = DestReg;
16908 Res.second = &X86::GR64RegClass;
16911 } else if (Res.second == &X86::FR32RegClass ||
16912 Res.second == &X86::FR64RegClass ||
16913 Res.second == &X86::VR128RegClass) {
16914 // Handle references to XMM physical registers that got mapped into the
16915 // wrong class. This can happen with constraints like {xmm0} where the
16916 // target independent register mapper will just pick the first match it can
16917 // find, ignoring the required type.
16919 if (VT == MVT::f32 || VT == MVT::i32)
16920 Res.second = &X86::FR32RegClass;
16921 else if (VT == MVT::f64 || VT == MVT::i64)
16922 Res.second = &X86::FR64RegClass;
16923 else if (X86::VR128RegClass.hasType(VT))
16924 Res.second = &X86::VR128RegClass;
16925 else if (X86::VR256RegClass.hasType(VT))
16926 Res.second = &X86::VR256RegClass;