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 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71 "x86-recip-refinement-steps", cl::init(1),
72 cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73 "result of the hardware reciprocal estimate instruction."),
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81 const X86Subtarget &STI)
82 : TargetLowering(TM), Subtarget(&STI) {
83 X86ScalarSSEf64 = Subtarget->hasSSE2();
84 X86ScalarSSEf32 = Subtarget->hasSSE1();
87 // Set up the TargetLowering object.
88 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
90 // X86 is weird. It always uses i8 for shift amounts and setcc results.
91 setBooleanContents(ZeroOrOneBooleanContent);
92 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
95 // For 64-bit, since we have so many registers, use the ILP scheduler.
96 // For 32-bit, use the register pressure specific scheduling.
97 // For Atom, always use ILP scheduling.
98 if (Subtarget->isAtom())
99 setSchedulingPreference(Sched::ILP);
100 else if (Subtarget->is64Bit())
101 setSchedulingPreference(Sched::ILP);
103 setSchedulingPreference(Sched::RegPressure);
104 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
107 // Bypass expensive divides on Atom when compiling with O2.
108 if (TM.getOptLevel() >= CodeGenOpt::Default) {
109 if (Subtarget->hasSlowDivide32())
110 addBypassSlowDiv(32, 8);
111 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112 addBypassSlowDiv(64, 16);
115 if (Subtarget->isTargetKnownWindowsMSVC()) {
116 // Setup Windows compiler runtime calls.
117 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119 setLibcallName(RTLIB::SREM_I64, "_allrem");
120 setLibcallName(RTLIB::UREM_I64, "_aullrem");
121 setLibcallName(RTLIB::MUL_I64, "_allmul");
122 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
128 // The _ftol2 runtime function has an unusual calling conv, which
129 // is modeled by a special pseudo-instruction.
130 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
136 if (Subtarget->isTargetDarwin()) {
137 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138 setUseUnderscoreSetJmp(false);
139 setUseUnderscoreLongJmp(false);
140 } else if (Subtarget->isTargetWindowsGNU()) {
141 // MS runtime is weird: it exports _setjmp, but longjmp!
142 setUseUnderscoreSetJmp(true);
143 setUseUnderscoreLongJmp(false);
145 setUseUnderscoreSetJmp(true);
146 setUseUnderscoreLongJmp(true);
149 // Set up the register classes.
150 addRegisterClass(MVT::i8, &X86::GR8RegClass);
151 addRegisterClass(MVT::i16, &X86::GR16RegClass);
152 addRegisterClass(MVT::i32, &X86::GR32RegClass);
153 if (Subtarget->is64Bit())
154 addRegisterClass(MVT::i64, &X86::GR64RegClass);
156 for (MVT VT : MVT::integer_valuetypes())
157 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
159 // We don't accept any truncstore of integer registers.
160 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
167 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
169 // SETOEQ and SETUNE require checking two conditions.
170 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
177 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
179 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
180 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
181 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
183 if (Subtarget->is64Bit()) {
184 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
185 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
186 } else if (!Subtarget->useSoftFloat()) {
187 // We have an algorithm for SSE2->double, and we turn this into a
188 // 64-bit FILD followed by conditional FADD for other targets.
189 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
190 // We have an algorithm for SSE2, and we turn this into a 64-bit
191 // FILD for other targets.
192 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
195 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
197 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
200 if (!Subtarget->useSoftFloat()) {
201 // SSE has no i16 to fp conversion, only i32
202 if (X86ScalarSSEf32) {
203 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
204 // f32 and f64 cases are Legal, f80 case is not
205 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
207 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
208 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
211 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
212 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
215 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
216 // are Legal, f80 is custom lowered.
217 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
218 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
220 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
222 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
223 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
225 if (X86ScalarSSEf32) {
226 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
227 // f32 and f64 cases are Legal, f80 case is not
228 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
230 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
231 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
234 // Handle FP_TO_UINT by promoting the destination to a larger signed
236 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
237 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
238 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
240 if (Subtarget->is64Bit()) {
241 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
242 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
243 } else if (!Subtarget->useSoftFloat()) {
244 // Since AVX is a superset of SSE3, only check for SSE here.
245 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246 // Expand FP_TO_UINT into a select.
247 // FIXME: We would like to use a Custom expander here eventually to do
248 // the optimal thing for SSE vs. the default expansion in the legalizer.
249 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
251 // With SSE3 we can use fisttpll to convert to a signed i64; without
252 // SSE, we're stuck with a fistpll.
253 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
256 if (isTargetFTOL()) {
257 // Use the _ftol2 runtime function, which has a pseudo-instruction
258 // to handle its weird calling convention.
259 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
262 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263 if (!X86ScalarSSEf64) {
264 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
265 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
266 if (Subtarget->is64Bit()) {
267 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
268 // Without SSE, i64->f64 goes through memory.
269 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
273 // Scalar integer divide and remainder are lowered to use operations that
274 // produce two results, to match the available instructions. This exposes
275 // the two-result form to trivial CSE, which is able to combine x/y and x%y
276 // into a single instruction.
278 // Scalar integer multiply-high is also lowered to use two-result
279 // operations, to match the available instructions. However, plain multiply
280 // (low) operations are left as Legal, as there are single-result
281 // instructions for this in x86. Using the two-result multiply instructions
282 // when both high and low results are needed must be arranged by dagcombine.
283 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
285 setOperationAction(ISD::MULHS, VT, Expand);
286 setOperationAction(ISD::MULHU, VT, Expand);
287 setOperationAction(ISD::SDIV, VT, Expand);
288 setOperationAction(ISD::UDIV, VT, Expand);
289 setOperationAction(ISD::SREM, VT, Expand);
290 setOperationAction(ISD::UREM, VT, Expand);
292 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293 setOperationAction(ISD::ADDC, VT, Custom);
294 setOperationAction(ISD::ADDE, VT, Custom);
295 setOperationAction(ISD::SUBC, VT, Custom);
296 setOperationAction(ISD::SUBE, VT, Custom);
299 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
300 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
301 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
302 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
303 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
304 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
305 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
306 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
307 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
309 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
310 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
311 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
312 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
313 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
314 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
315 if (Subtarget->is64Bit())
316 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
318 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
319 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
320 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
321 setOperationAction(ISD::FREM , MVT::f32 , Expand);
322 setOperationAction(ISD::FREM , MVT::f64 , Expand);
323 setOperationAction(ISD::FREM , MVT::f80 , Expand);
324 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
326 // Promote the i8 variants and force them on up to i32 which has a shorter
328 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
329 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
331 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
332 if (Subtarget->hasBMI()) {
333 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
334 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
335 if (Subtarget->is64Bit())
336 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
338 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
339 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
340 if (Subtarget->is64Bit())
341 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
344 if (Subtarget->hasLZCNT()) {
345 // When promoting the i8 variants, force them to i32 for a shorter
347 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
348 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
350 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
351 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
352 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
353 if (Subtarget->is64Bit())
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
356 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
357 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
358 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
362 if (Subtarget->is64Bit()) {
363 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
364 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
368 // Special handling for half-precision floating point conversions.
369 // If we don't have F16C support, then lower half float conversions
370 // into library calls.
371 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
376 // There's never any support for operations beyond MVT::f32.
377 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
382 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
389 if (Subtarget->hasPOPCNT()) {
390 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
392 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
393 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
394 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
395 if (Subtarget->is64Bit())
396 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
399 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
401 if (!Subtarget->hasMOVBE())
402 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
404 // These should be promoted to a larger select which is supported.
405 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
406 // X86 wants to expand cmov itself.
407 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
408 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
409 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
410 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
411 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
412 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
413 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
414 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
416 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
417 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
418 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
419 if (Subtarget->is64Bit()) {
420 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
421 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
423 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
424 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426 // support continuation, user-level threading, and etc.. As a result, no
427 // other SjLj exception interfaces are implemented and please don't build
428 // your own exception handling based on them.
429 // LLVM/Clang supports zero-cost DWARF exception handling.
430 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
434 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
435 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
436 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
437 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
438 if (Subtarget->is64Bit())
439 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
442 if (Subtarget->is64Bit()) {
443 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
444 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
445 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
446 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
447 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
449 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
451 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
452 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
455 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
456 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
459 if (Subtarget->hasSSE1())
460 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
462 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
464 // Expand certain atomics
465 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
472 if (Subtarget->hasCmpxchg16b()) {
473 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
476 // FIXME - use subtarget debug flags
477 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
482 if (Subtarget->is64Bit()) {
483 setExceptionPointerRegister(X86::RAX);
484 setExceptionSelectorRegister(X86::RDX);
486 setExceptionPointerRegister(X86::EAX);
487 setExceptionSelectorRegister(X86::EDX);
489 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
492 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
495 setOperationAction(ISD::TRAP, MVT::Other, Legal);
496 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
498 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499 setOperationAction(ISD::VASTART , MVT::Other, Custom);
500 setOperationAction(ISD::VAEND , MVT::Other, Expand);
501 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502 // TargetInfo::X86_64ABIBuiltinVaList
503 setOperationAction(ISD::VAARG , MVT::Other, Custom);
504 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
506 // TargetInfo::CharPtrBuiltinVaList
507 setOperationAction(ISD::VAARG , MVT::Other, Expand);
508 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
511 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
512 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
514 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
516 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
520 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
521 // f32 and f64 use SSE.
522 // Set up the FP register classes.
523 addRegisterClass(MVT::f32, &X86::FR32RegClass);
524 addRegisterClass(MVT::f64, &X86::FR64RegClass);
526 // Use ANDPD to simulate FABS.
527 setOperationAction(ISD::FABS , MVT::f64, Custom);
528 setOperationAction(ISD::FABS , MVT::f32, Custom);
530 // Use XORP to simulate FNEG.
531 setOperationAction(ISD::FNEG , MVT::f64, Custom);
532 setOperationAction(ISD::FNEG , MVT::f32, Custom);
534 // Use ANDPD and ORPD to simulate FCOPYSIGN.
535 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
538 // Lower this to FGETSIGNx86 plus an AND.
539 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
542 // We don't support sin/cos/fmod
543 setOperationAction(ISD::FSIN , MVT::f64, Expand);
544 setOperationAction(ISD::FCOS , MVT::f64, Expand);
545 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546 setOperationAction(ISD::FSIN , MVT::f32, Expand);
547 setOperationAction(ISD::FCOS , MVT::f32, Expand);
548 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
550 // Expand FP immediates into loads from the stack, except for the special
552 addLegalFPImmediate(APFloat(+0.0)); // xorpd
553 addLegalFPImmediate(APFloat(+0.0f)); // xorps
554 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
555 // Use SSE for f32, x87 for f64.
556 // Set up the FP register classes.
557 addRegisterClass(MVT::f32, &X86::FR32RegClass);
558 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
560 // Use ANDPS to simulate FABS.
561 setOperationAction(ISD::FABS , MVT::f32, Custom);
563 // Use XORP to simulate FNEG.
564 setOperationAction(ISD::FNEG , MVT::f32, Custom);
566 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
568 // Use ANDPS and ORPS to simulate FCOPYSIGN.
569 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
572 // We don't support sin/cos/fmod
573 setOperationAction(ISD::FSIN , MVT::f32, Expand);
574 setOperationAction(ISD::FCOS , MVT::f32, Expand);
575 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
577 // Special cases we handle for FP constants.
578 addLegalFPImmediate(APFloat(+0.0f)); // xorps
579 addLegalFPImmediate(APFloat(+0.0)); // FLD0
580 addLegalFPImmediate(APFloat(+1.0)); // FLD1
581 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
584 if (!TM.Options.UnsafeFPMath) {
585 setOperationAction(ISD::FSIN , MVT::f64, Expand);
586 setOperationAction(ISD::FCOS , MVT::f64, Expand);
587 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
589 } else if (!Subtarget->useSoftFloat()) {
590 // f32 and f64 in x87.
591 // Set up the FP register classes.
592 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
595 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
596 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
600 if (!TM.Options.UnsafeFPMath) {
601 setOperationAction(ISD::FSIN , MVT::f64, Expand);
602 setOperationAction(ISD::FSIN , MVT::f32, Expand);
603 setOperationAction(ISD::FCOS , MVT::f64, Expand);
604 setOperationAction(ISD::FCOS , MVT::f32, Expand);
605 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
608 addLegalFPImmediate(APFloat(+0.0)); // FLD0
609 addLegalFPImmediate(APFloat(+1.0)); // FLD1
610 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
618 // We don't support FMA.
619 setOperationAction(ISD::FMA, MVT::f64, Expand);
620 setOperationAction(ISD::FMA, MVT::f32, Expand);
622 // Long double always uses X87.
623 if (!Subtarget->useSoftFloat()) {
624 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
626 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
628 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629 addLegalFPImmediate(TmpFlt); // FLD0
631 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
634 APFloat TmpFlt2(+1.0);
635 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
637 addLegalFPImmediate(TmpFlt2); // FLD1
638 TmpFlt2.changeSign();
639 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
642 if (!TM.Options.UnsafeFPMath) {
643 setOperationAction(ISD::FSIN , MVT::f80, Expand);
644 setOperationAction(ISD::FCOS , MVT::f80, Expand);
645 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
648 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
650 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651 setOperationAction(ISD::FRINT, MVT::f80, Expand);
652 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653 setOperationAction(ISD::FMA, MVT::f80, Expand);
656 // Always use a library call for pow.
657 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
658 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
659 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
661 setOperationAction(ISD::FLOG, MVT::f80, Expand);
662 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664 setOperationAction(ISD::FEXP, MVT::f80, Expand);
665 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
669 // First set operation action for all vector types to either promote
670 // (for widening) or expand (for scalarization). Then we will selectively
671 // turn on ones that can be effectively codegen'd.
672 for (MVT VT : MVT::vector_valuetypes()) {
673 setOperationAction(ISD::ADD , VT, Expand);
674 setOperationAction(ISD::SUB , VT, Expand);
675 setOperationAction(ISD::FADD, VT, Expand);
676 setOperationAction(ISD::FNEG, VT, Expand);
677 setOperationAction(ISD::FSUB, VT, Expand);
678 setOperationAction(ISD::MUL , VT, Expand);
679 setOperationAction(ISD::FMUL, VT, Expand);
680 setOperationAction(ISD::SDIV, VT, Expand);
681 setOperationAction(ISD::UDIV, VT, Expand);
682 setOperationAction(ISD::FDIV, VT, Expand);
683 setOperationAction(ISD::SREM, VT, Expand);
684 setOperationAction(ISD::UREM, VT, Expand);
685 setOperationAction(ISD::LOAD, VT, Expand);
686 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691 setOperationAction(ISD::FABS, VT, Expand);
692 setOperationAction(ISD::FSIN, VT, Expand);
693 setOperationAction(ISD::FSINCOS, VT, Expand);
694 setOperationAction(ISD::FCOS, VT, Expand);
695 setOperationAction(ISD::FSINCOS, VT, Expand);
696 setOperationAction(ISD::FREM, VT, Expand);
697 setOperationAction(ISD::FMA, VT, Expand);
698 setOperationAction(ISD::FPOWI, VT, Expand);
699 setOperationAction(ISD::FSQRT, VT, Expand);
700 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701 setOperationAction(ISD::FFLOOR, VT, Expand);
702 setOperationAction(ISD::FCEIL, VT, Expand);
703 setOperationAction(ISD::FTRUNC, VT, Expand);
704 setOperationAction(ISD::FRINT, VT, Expand);
705 setOperationAction(ISD::FNEARBYINT, VT, Expand);
706 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707 setOperationAction(ISD::MULHS, VT, Expand);
708 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709 setOperationAction(ISD::MULHU, VT, Expand);
710 setOperationAction(ISD::SDIVREM, VT, Expand);
711 setOperationAction(ISD::UDIVREM, VT, Expand);
712 setOperationAction(ISD::FPOW, VT, Expand);
713 setOperationAction(ISD::CTPOP, VT, Expand);
714 setOperationAction(ISD::CTTZ, VT, Expand);
715 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716 setOperationAction(ISD::CTLZ, VT, Expand);
717 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718 setOperationAction(ISD::SHL, VT, Expand);
719 setOperationAction(ISD::SRA, VT, Expand);
720 setOperationAction(ISD::SRL, VT, Expand);
721 setOperationAction(ISD::ROTL, VT, Expand);
722 setOperationAction(ISD::ROTR, VT, Expand);
723 setOperationAction(ISD::BSWAP, VT, Expand);
724 setOperationAction(ISD::SETCC, VT, Expand);
725 setOperationAction(ISD::FLOG, VT, Expand);
726 setOperationAction(ISD::FLOG2, VT, Expand);
727 setOperationAction(ISD::FLOG10, VT, Expand);
728 setOperationAction(ISD::FEXP, VT, Expand);
729 setOperationAction(ISD::FEXP2, VT, Expand);
730 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735 setOperationAction(ISD::TRUNCATE, VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739 setOperationAction(ISD::VSELECT, VT, Expand);
740 setOperationAction(ISD::SELECT_CC, VT, Expand);
741 for (MVT InnerVT : MVT::vector_valuetypes()) {
742 setTruncStoreAction(InnerVT, VT, Expand);
744 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
747 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748 // types, we have to deal with them whether we ask for Expansion or not.
749 // Setting Expand causes its own optimisation problems though, so leave
751 if (VT.getVectorElementType() == MVT::i1)
752 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
754 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755 // split/scalarized right now.
756 if (VT.getVectorElementType() == MVT::f16)
757 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
761 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762 // with -msoft-float, disable use of MMX as well.
763 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765 // No operations on x86mmx supported, everything uses intrinsics.
768 // MMX-sized vectors (other than x86mmx) are expected to be expanded
769 // into smaller operations.
770 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771 setOperationAction(ISD::MULHS, MMXTy, Expand);
772 setOperationAction(ISD::AND, MMXTy, Expand);
773 setOperationAction(ISD::OR, MMXTy, Expand);
774 setOperationAction(ISD::XOR, MMXTy, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
776 setOperationAction(ISD::SELECT, MMXTy, Expand);
777 setOperationAction(ISD::BITCAST, MMXTy, Expand);
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
781 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
784 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
785 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
786 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
787 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
788 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
789 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
790 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
791 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
792 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
793 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
794 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
797 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
800 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
803 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804 // registers cannot be used even for integer operations.
805 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
810 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
811 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
812 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
813 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
814 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
815 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
816 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
817 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
818 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
819 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
820 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
821 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
822 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
823 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
824 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
825 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
826 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
827 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
828 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
829 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
831 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
832 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
834 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
835 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
836 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
837 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
840 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
843 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
845 // Only provide customized ctpop vector bit twiddling for vector types we
846 // know to perform better than using the popcnt instructions on each vector
847 // element. If popcnt isn't supported, always provide the custom version.
848 if (!Subtarget->hasPOPCNT()) {
849 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
850 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
853 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
854 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
855 MVT VT = (MVT::SimpleValueType)i;
856 // Do not attempt to custom lower non-power-of-2 vectors
857 if (!isPowerOf2_32(VT.getVectorNumElements()))
859 // Do not attempt to custom lower non-128-bit vectors
860 if (!VT.is128BitVector())
862 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
863 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
864 setOperationAction(ISD::VSELECT, VT, Custom);
865 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
868 // We support custom legalizing of sext and anyext loads for specific
869 // memory vector types which we can load as a scalar (or sequence of
870 // scalars) and extend in-register to a legal 128-bit vector type. For sext
871 // loads these must work with a single scalar load.
872 for (MVT VT : MVT::integer_vector_valuetypes()) {
873 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
884 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
885 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
887 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
888 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
889 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
893 if (Subtarget->is64Bit()) {
894 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
895 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
898 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900 MVT VT = (MVT::SimpleValueType)i;
902 // Do not attempt to promote non-128-bit vectors
903 if (!VT.is128BitVector())
906 setOperationAction(ISD::AND, VT, Promote);
907 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
908 setOperationAction(ISD::OR, VT, Promote);
909 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
910 setOperationAction(ISD::XOR, VT, Promote);
911 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
912 setOperationAction(ISD::LOAD, VT, Promote);
913 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
914 setOperationAction(ISD::SELECT, VT, Promote);
915 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
918 // Custom lower v2i64 and v2f64 selects.
919 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
920 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
921 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
922 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
924 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
925 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
927 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
928 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
929 // As there is no 64-bit GPR available, we need build a special custom
930 // sequence to convert from v2i32 to v2f32.
931 if (!Subtarget->is64Bit())
932 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
934 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
935 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
937 for (MVT VT : MVT::fp_vector_valuetypes())
938 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
940 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
941 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
942 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
945 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
948 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
949 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
950 setOperationAction(ISD::FRINT, RoundedTy, Legal);
951 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
954 // FIXME: Do we need to handle scalar-to-vector here?
955 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
957 // We directly match byte blends in the backend as they match the VSELECT
959 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
961 // SSE41 brings specific instructions for doing vector sign extend even in
962 // cases where we don't have SRA.
963 for (MVT VT : MVT::integer_vector_valuetypes()) {
964 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
965 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
966 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
969 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
970 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
971 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
972 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
973 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
974 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
975 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
977 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
978 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
979 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
980 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
984 // i8 and i16 vectors are custom because the source register and source
985 // source memory operand types are not the same width. f32 vectors are
986 // custom since the immediate controlling the insert encodes additional
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
990 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
998 // FIXME: these should be Legal, but that's only for the case where
999 // the index is constant. For now custom expand to deal with that.
1000 if (Subtarget->is64Bit()) {
1001 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1006 if (Subtarget->hasSSE2()) {
1007 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1008 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1010 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1011 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1013 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1014 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1016 // In the customized shift lowering, the legal cases in AVX2 will be
1018 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1019 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1021 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1022 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1024 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1027 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1028 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1029 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1030 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1031 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1032 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1033 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1035 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1036 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1037 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1039 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1040 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1041 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1042 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1043 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1044 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1045 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1046 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1047 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1050 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1052 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1053 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1054 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1055 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1056 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1059 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1060 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1063 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1065 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1066 // even though v8i16 is a legal type.
1067 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1068 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1069 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1071 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1072 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1073 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1075 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1076 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1078 for (MVT VT : MVT::fp_vector_valuetypes())
1079 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1081 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1082 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1084 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1085 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1087 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1088 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1090 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1091 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1092 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1093 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1095 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1096 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1097 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1099 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1100 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1101 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1102 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1103 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1104 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1105 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1106 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1107 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1108 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1109 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1110 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1112 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1113 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1114 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1115 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1116 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1117 setOperationAction(ISD::FMA, MVT::f32, Legal);
1118 setOperationAction(ISD::FMA, MVT::f64, Legal);
1121 if (Subtarget->hasInt256()) {
1122 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1123 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1124 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1125 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1127 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1128 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1129 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1130 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1132 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1133 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1134 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1135 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1137 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1138 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1139 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1140 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1142 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1143 // when we have a 256bit-wide blend with immediate.
1144 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1146 // Only provide customized ctpop vector bit twiddling for vector types we
1147 // know to perform better than using the popcnt instructions on each
1148 // vector element. If popcnt isn't supported, always provide the custom
1150 if (!Subtarget->hasPOPCNT())
1151 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1153 // Custom CTPOP always performs better on natively supported v8i32
1154 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1156 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1157 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1158 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1159 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1160 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1161 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1162 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1164 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1165 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1166 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1167 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1168 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1169 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1171 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1172 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1173 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1174 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1176 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1177 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1178 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1181 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1182 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1183 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1184 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1187 // In the customized shift lowering, the legal cases in AVX2 will be
1189 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1190 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1192 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1193 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1195 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1197 // Custom lower several nodes for 256-bit types.
1198 for (MVT VT : MVT::vector_valuetypes()) {
1199 if (VT.getScalarSizeInBits() >= 32) {
1200 setOperationAction(ISD::MLOAD, VT, Legal);
1201 setOperationAction(ISD::MSTORE, VT, Legal);
1203 // Extract subvector is special because the value type
1204 // (result) is 128-bit but the source is 256-bit wide.
1205 if (VT.is128BitVector()) {
1206 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1208 // Do not attempt to custom lower other non-256-bit vectors
1209 if (!VT.is256BitVector())
1212 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1213 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1214 setOperationAction(ISD::VSELECT, VT, Custom);
1215 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1216 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1217 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1218 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1219 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1222 if (Subtarget->hasInt256())
1223 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1226 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1227 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1228 MVT VT = (MVT::SimpleValueType)i;
1230 // Do not attempt to promote non-256-bit vectors
1231 if (!VT.is256BitVector())
1234 setOperationAction(ISD::AND, VT, Promote);
1235 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1236 setOperationAction(ISD::OR, VT, Promote);
1237 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1238 setOperationAction(ISD::XOR, VT, Promote);
1239 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1240 setOperationAction(ISD::LOAD, VT, Promote);
1241 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1242 setOperationAction(ISD::SELECT, VT, Promote);
1243 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1247 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1248 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1249 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1250 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1251 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1253 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1254 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1255 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1257 for (MVT VT : MVT::fp_vector_valuetypes())
1258 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1260 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1261 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1262 setOperationAction(ISD::XOR, MVT::i1, Legal);
1263 setOperationAction(ISD::OR, MVT::i1, Legal);
1264 setOperationAction(ISD::AND, MVT::i1, Legal);
1265 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1266 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1267 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1268 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1269 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1271 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1272 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1273 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1274 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1275 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1276 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1278 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1279 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1280 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1281 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1282 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1283 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1284 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1285 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1287 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1288 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1289 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1290 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1291 if (Subtarget->is64Bit()) {
1292 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1293 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1294 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1295 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1297 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1298 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1299 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1300 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1301 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1302 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1303 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1304 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1305 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1306 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1307 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1308 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1309 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1310 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1311 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1312 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1314 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1315 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1316 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1317 if (Subtarget->hasDQI()) {
1318 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1319 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1321 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1322 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1323 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1324 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1325 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1326 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1327 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1328 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1329 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1330 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1331 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1332 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1333 if (Subtarget->hasDQI()) {
1334 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1335 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1337 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1338 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1339 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1340 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1341 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1342 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1344 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1348 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1349 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1350 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1351 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1352 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1354 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1355 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1357 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1359 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1360 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1361 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1362 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1363 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1364 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1365 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1366 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1367 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1369 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1370 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1372 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1373 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1375 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1377 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1378 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1380 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1381 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1383 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1384 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1386 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1387 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1388 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1389 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1390 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1391 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1393 if (Subtarget->hasCDI()) {
1394 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1395 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1397 if (Subtarget->hasDQI()) {
1398 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1399 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1400 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1402 // Custom lower several nodes.
1403 for (MVT VT : MVT::vector_valuetypes()) {
1404 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1406 setOperationAction(ISD::AND, VT, Legal);
1407 setOperationAction(ISD::OR, VT, Legal);
1408 setOperationAction(ISD::XOR, VT, Legal);
1410 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1411 setOperationAction(ISD::MGATHER, VT, Custom);
1412 setOperationAction(ISD::MSCATTER, VT, Custom);
1414 // Extract subvector is special because the value type
1415 // (result) is 256/128-bit but the source is 512-bit wide.
1416 if (VT.is128BitVector() || VT.is256BitVector()) {
1417 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1419 if (VT.getVectorElementType() == MVT::i1)
1420 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1422 // Do not attempt to custom lower other non-512-bit vectors
1423 if (!VT.is512BitVector())
1426 if (EltSize >= 32) {
1427 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1428 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1429 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1430 setOperationAction(ISD::VSELECT, VT, Legal);
1431 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1432 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1433 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1434 setOperationAction(ISD::MLOAD, VT, Legal);
1435 setOperationAction(ISD::MSTORE, VT, Legal);
1438 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1439 MVT VT = (MVT::SimpleValueType)i;
1441 // Do not attempt to promote non-512-bit vectors.
1442 if (!VT.is512BitVector())
1445 setOperationAction(ISD::SELECT, VT, Promote);
1446 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1450 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1451 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1452 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1454 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1455 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1457 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1458 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1459 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1460 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1461 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1462 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1463 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1464 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1465 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1466 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1467 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1468 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1469 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1471 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1472 const MVT VT = (MVT::SimpleValueType)i;
1474 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1476 // Do not attempt to promote non-512-bit vectors.
1477 if (!VT.is512BitVector())
1481 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1482 setOperationAction(ISD::VSELECT, VT, Legal);
1487 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1488 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1489 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1491 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1492 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1493 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1494 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1495 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1496 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1498 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1499 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1500 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1501 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1502 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1503 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1506 // We want to custom lower some of our intrinsics.
1507 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1508 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1509 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1510 if (!Subtarget->is64Bit())
1511 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1513 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1514 // handle type legalization for these operations here.
1516 // FIXME: We really should do custom legalization for addition and
1517 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1518 // than generic legalization for 64-bit multiplication-with-overflow, though.
1519 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1520 // Add/Sub/Mul with overflow operations are custom lowered.
1522 setOperationAction(ISD::SADDO, VT, Custom);
1523 setOperationAction(ISD::UADDO, VT, Custom);
1524 setOperationAction(ISD::SSUBO, VT, Custom);
1525 setOperationAction(ISD::USUBO, VT, Custom);
1526 setOperationAction(ISD::SMULO, VT, Custom);
1527 setOperationAction(ISD::UMULO, VT, Custom);
1531 if (!Subtarget->is64Bit()) {
1532 // These libcalls are not available in 32-bit.
1533 setLibcallName(RTLIB::SHL_I128, nullptr);
1534 setLibcallName(RTLIB::SRL_I128, nullptr);
1535 setLibcallName(RTLIB::SRA_I128, nullptr);
1538 // Combine sin / cos into one node or libcall if possible.
1539 if (Subtarget->hasSinCos()) {
1540 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1541 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1542 if (Subtarget->isTargetDarwin()) {
1543 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1544 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1545 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1546 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1550 if (Subtarget->isTargetWin64()) {
1551 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1552 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1553 setOperationAction(ISD::SREM, MVT::i128, Custom);
1554 setOperationAction(ISD::UREM, MVT::i128, Custom);
1555 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1556 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1559 // We have target-specific dag combine patterns for the following nodes:
1560 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1561 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1562 setTargetDAGCombine(ISD::BITCAST);
1563 setTargetDAGCombine(ISD::VSELECT);
1564 setTargetDAGCombine(ISD::SELECT);
1565 setTargetDAGCombine(ISD::SHL);
1566 setTargetDAGCombine(ISD::SRA);
1567 setTargetDAGCombine(ISD::SRL);
1568 setTargetDAGCombine(ISD::OR);
1569 setTargetDAGCombine(ISD::AND);
1570 setTargetDAGCombine(ISD::ADD);
1571 setTargetDAGCombine(ISD::FADD);
1572 setTargetDAGCombine(ISD::FSUB);
1573 setTargetDAGCombine(ISD::FMA);
1574 setTargetDAGCombine(ISD::SUB);
1575 setTargetDAGCombine(ISD::LOAD);
1576 setTargetDAGCombine(ISD::MLOAD);
1577 setTargetDAGCombine(ISD::STORE);
1578 setTargetDAGCombine(ISD::MSTORE);
1579 setTargetDAGCombine(ISD::ZERO_EXTEND);
1580 setTargetDAGCombine(ISD::ANY_EXTEND);
1581 setTargetDAGCombine(ISD::SIGN_EXTEND);
1582 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1583 setTargetDAGCombine(ISD::TRUNCATE);
1584 setTargetDAGCombine(ISD::SINT_TO_FP);
1585 setTargetDAGCombine(ISD::SETCC);
1586 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1587 setTargetDAGCombine(ISD::BUILD_VECTOR);
1588 setTargetDAGCombine(ISD::MUL);
1589 setTargetDAGCombine(ISD::XOR);
1591 computeRegisterProperties(Subtarget->getRegisterInfo());
1593 // On Darwin, -Os means optimize for size without hurting performance,
1594 // do not reduce the limit.
1595 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1596 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1597 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1598 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1599 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1600 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1601 setPrefLoopAlignment(4); // 2^4 bytes.
1603 // Predictable cmov don't hurt on atom because it's in-order.
1604 PredictableSelectIsExpensive = !Subtarget->isAtom();
1605 EnableExtLdPromotion = true;
1606 setPrefFunctionAlignment(4); // 2^4 bytes.
1608 verifyIntrinsicTables();
1611 // This has so far only been implemented for 64-bit MachO.
1612 bool X86TargetLowering::useLoadStackGuardNode() const {
1613 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1616 TargetLoweringBase::LegalizeTypeAction
1617 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1618 if (ExperimentalVectorWideningLegalization &&
1619 VT.getVectorNumElements() != 1 &&
1620 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1621 return TypeWidenVector;
1623 return TargetLoweringBase::getPreferredVectorAction(VT);
1626 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1628 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1630 const unsigned NumElts = VT.getVectorNumElements();
1631 const EVT EltVT = VT.getVectorElementType();
1632 if (VT.is512BitVector()) {
1633 if (Subtarget->hasAVX512())
1634 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1635 EltVT == MVT::f32 || EltVT == MVT::f64)
1637 case 8: return MVT::v8i1;
1638 case 16: return MVT::v16i1;
1640 if (Subtarget->hasBWI())
1641 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1643 case 32: return MVT::v32i1;
1644 case 64: return MVT::v64i1;
1648 if (VT.is256BitVector() || VT.is128BitVector()) {
1649 if (Subtarget->hasVLX())
1650 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1651 EltVT == MVT::f32 || EltVT == MVT::f64)
1653 case 2: return MVT::v2i1;
1654 case 4: return MVT::v4i1;
1655 case 8: return MVT::v8i1;
1657 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1658 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1660 case 8: return MVT::v8i1;
1661 case 16: return MVT::v16i1;
1662 case 32: return MVT::v32i1;
1666 return VT.changeVectorElementTypeToInteger();
1669 /// Helper for getByValTypeAlignment to determine
1670 /// the desired ByVal argument alignment.
1671 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1674 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1675 if (VTy->getBitWidth() == 128)
1677 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1678 unsigned EltAlign = 0;
1679 getMaxByValAlign(ATy->getElementType(), EltAlign);
1680 if (EltAlign > MaxAlign)
1681 MaxAlign = EltAlign;
1682 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1683 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1684 unsigned EltAlign = 0;
1685 getMaxByValAlign(STy->getElementType(i), EltAlign);
1686 if (EltAlign > MaxAlign)
1687 MaxAlign = EltAlign;
1694 /// Return the desired alignment for ByVal aggregate
1695 /// function arguments in the caller parameter area. For X86, aggregates
1696 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1697 /// are at 4-byte boundaries.
1698 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1699 if (Subtarget->is64Bit()) {
1700 // Max of 8 and alignment of type.
1701 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1708 if (Subtarget->hasSSE1())
1709 getMaxByValAlign(Ty, Align);
1713 /// Returns the target specific optimal type for load
1714 /// and store operations as a result of memset, memcpy, and memmove
1715 /// lowering. If DstAlign is zero that means it's safe to destination
1716 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1717 /// means there isn't a need to check it against alignment requirement,
1718 /// probably because the source does not need to be loaded. If 'IsMemset' is
1719 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1720 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1721 /// source is constant so it does not need to be loaded.
1722 /// It returns EVT::Other if the type should be determined using generic
1723 /// target-independent logic.
1725 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1726 unsigned DstAlign, unsigned SrcAlign,
1727 bool IsMemset, bool ZeroMemset,
1729 MachineFunction &MF) const {
1730 const Function *F = MF.getFunction();
1731 if ((!IsMemset || ZeroMemset) &&
1732 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1734 (Subtarget->isUnalignedMemAccessFast() ||
1735 ((DstAlign == 0 || DstAlign >= 16) &&
1736 (SrcAlign == 0 || SrcAlign >= 16)))) {
1738 if (Subtarget->hasInt256())
1740 if (Subtarget->hasFp256())
1743 if (Subtarget->hasSSE2())
1745 if (Subtarget->hasSSE1())
1747 } else if (!MemcpyStrSrc && Size >= 8 &&
1748 !Subtarget->is64Bit() &&
1749 Subtarget->hasSSE2()) {
1750 // Do not use f64 to lower memcpy if source is string constant. It's
1751 // better to use i32 to avoid the loads.
1755 if (Subtarget->is64Bit() && Size >= 8)
1760 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1762 return X86ScalarSSEf32;
1763 else if (VT == MVT::f64)
1764 return X86ScalarSSEf64;
1769 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1774 *Fast = Subtarget->isUnalignedMemAccessFast();
1778 /// Return the entry encoding for a jump table in the
1779 /// current function. The returned value is a member of the
1780 /// MachineJumpTableInfo::JTEntryKind enum.
1781 unsigned X86TargetLowering::getJumpTableEncoding() const {
1782 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1784 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1785 Subtarget->isPICStyleGOT())
1786 return MachineJumpTableInfo::EK_Custom32;
1788 // Otherwise, use the normal jump table encoding heuristics.
1789 return TargetLowering::getJumpTableEncoding();
1792 bool X86TargetLowering::useSoftFloat() const {
1793 return Subtarget->useSoftFloat();
1797 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1798 const MachineBasicBlock *MBB,
1799 unsigned uid,MCContext &Ctx) const{
1800 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1801 Subtarget->isPICStyleGOT());
1802 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1804 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1805 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1808 /// Returns relocation base for the given PIC jumptable.
1809 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1810 SelectionDAG &DAG) const {
1811 if (!Subtarget->is64Bit())
1812 // This doesn't have SDLoc associated with it, but is not really the
1813 // same as a Register.
1814 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1818 /// This returns the relocation base for the given PIC jumptable,
1819 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1820 const MCExpr *X86TargetLowering::
1821 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1822 MCContext &Ctx) const {
1823 // X86-64 uses RIP relative addressing based on the jump table label.
1824 if (Subtarget->isPICStyleRIPRel())
1825 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1827 // Otherwise, the reference is relative to the PIC base.
1828 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1831 std::pair<const TargetRegisterClass *, uint8_t>
1832 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1834 const TargetRegisterClass *RRC = nullptr;
1836 switch (VT.SimpleTy) {
1838 return TargetLowering::findRepresentativeClass(TRI, VT);
1839 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1840 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1843 RRC = &X86::VR64RegClass;
1845 case MVT::f32: case MVT::f64:
1846 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1847 case MVT::v4f32: case MVT::v2f64:
1848 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1850 RRC = &X86::VR128RegClass;
1853 return std::make_pair(RRC, Cost);
1856 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1857 unsigned &Offset) const {
1858 if (!Subtarget->isTargetLinux())
1861 if (Subtarget->is64Bit()) {
1862 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1864 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1876 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1877 unsigned DestAS) const {
1878 assert(SrcAS != DestAS && "Expected different address spaces!");
1880 return SrcAS < 256 && DestAS < 256;
1883 //===----------------------------------------------------------------------===//
1884 // Return Value Calling Convention Implementation
1885 //===----------------------------------------------------------------------===//
1887 #include "X86GenCallingConv.inc"
1890 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1891 MachineFunction &MF, bool isVarArg,
1892 const SmallVectorImpl<ISD::OutputArg> &Outs,
1893 LLVMContext &Context) const {
1894 SmallVector<CCValAssign, 16> RVLocs;
1895 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1896 return CCInfo.CheckReturn(Outs, RetCC_X86);
1899 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1900 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1905 X86TargetLowering::LowerReturn(SDValue Chain,
1906 CallingConv::ID CallConv, bool isVarArg,
1907 const SmallVectorImpl<ISD::OutputArg> &Outs,
1908 const SmallVectorImpl<SDValue> &OutVals,
1909 SDLoc dl, SelectionDAG &DAG) const {
1910 MachineFunction &MF = DAG.getMachineFunction();
1911 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1913 SmallVector<CCValAssign, 16> RVLocs;
1914 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1915 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1918 SmallVector<SDValue, 6> RetOps;
1919 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1920 // Operand #1 = Bytes To Pop
1921 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1924 // Copy the result values into the output registers.
1925 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1926 CCValAssign &VA = RVLocs[i];
1927 assert(VA.isRegLoc() && "Can only return in registers!");
1928 SDValue ValToCopy = OutVals[i];
1929 EVT ValVT = ValToCopy.getValueType();
1931 // Promote values to the appropriate types.
1932 if (VA.getLocInfo() == CCValAssign::SExt)
1933 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1934 else if (VA.getLocInfo() == CCValAssign::ZExt)
1935 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1936 else if (VA.getLocInfo() == CCValAssign::AExt) {
1937 if (ValVT.getScalarType() == MVT::i1)
1938 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1940 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1942 else if (VA.getLocInfo() == CCValAssign::BCvt)
1943 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1945 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1946 "Unexpected FP-extend for return value.");
1948 // If this is x86-64, and we disabled SSE, we can't return FP values,
1949 // or SSE or MMX vectors.
1950 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1951 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1952 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1953 report_fatal_error("SSE register return with SSE disabled");
1955 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1956 // llvm-gcc has never done it right and no one has noticed, so this
1957 // should be OK for now.
1958 if (ValVT == MVT::f64 &&
1959 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1960 report_fatal_error("SSE2 register return with SSE2 disabled");
1962 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1963 // the RET instruction and handled by the FP Stackifier.
1964 if (VA.getLocReg() == X86::FP0 ||
1965 VA.getLocReg() == X86::FP1) {
1966 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1967 // change the value to the FP stack register class.
1968 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1969 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1970 RetOps.push_back(ValToCopy);
1971 // Don't emit a copytoreg.
1975 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1976 // which is returned in RAX / RDX.
1977 if (Subtarget->is64Bit()) {
1978 if (ValVT == MVT::x86mmx) {
1979 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1980 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1981 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1983 // If we don't have SSE2 available, convert to v4f32 so the generated
1984 // register is legal.
1985 if (!Subtarget->hasSSE2())
1986 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1991 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1992 Flag = Chain.getValue(1);
1993 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1996 // The x86-64 ABIs require that for returning structs by value we copy
1997 // the sret argument into %rax/%eax (depending on ABI) for the return.
1998 // Win32 requires us to put the sret argument to %eax as well.
1999 // We saved the argument into a virtual register in the entry block,
2000 // so now we copy the value out and into %rax/%eax.
2002 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2003 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2004 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2005 // either case FuncInfo->setSRetReturnReg() will have been called.
2006 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2007 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
2008 "No need for an sret register");
2009 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2012 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2013 X86::RAX : X86::EAX;
2014 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2015 Flag = Chain.getValue(1);
2017 // RAX/EAX now acts like a return value.
2018 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2021 RetOps[0] = Chain; // Update chain.
2023 // Add the flag if we have it.
2025 RetOps.push_back(Flag);
2027 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2030 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2031 if (N->getNumValues() != 1)
2033 if (!N->hasNUsesOfValue(1, 0))
2036 SDValue TCChain = Chain;
2037 SDNode *Copy = *N->use_begin();
2038 if (Copy->getOpcode() == ISD::CopyToReg) {
2039 // If the copy has a glue operand, we conservatively assume it isn't safe to
2040 // perform a tail call.
2041 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2043 TCChain = Copy->getOperand(0);
2044 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2047 bool HasRet = false;
2048 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2050 if (UI->getOpcode() != X86ISD::RET_FLAG)
2052 // If we are returning more than one value, we can definitely
2053 // not make a tail call see PR19530
2054 if (UI->getNumOperands() > 4)
2056 if (UI->getNumOperands() == 4 &&
2057 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2070 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2071 ISD::NodeType ExtendKind) const {
2073 // TODO: Is this also valid on 32-bit?
2074 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2075 ReturnMVT = MVT::i8;
2077 ReturnMVT = MVT::i32;
2079 EVT MinVT = getRegisterType(Context, ReturnMVT);
2080 return VT.bitsLT(MinVT) ? MinVT : VT;
2083 /// Lower the result values of a call into the
2084 /// appropriate copies out of appropriate physical registers.
2087 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2088 CallingConv::ID CallConv, bool isVarArg,
2089 const SmallVectorImpl<ISD::InputArg> &Ins,
2090 SDLoc dl, SelectionDAG &DAG,
2091 SmallVectorImpl<SDValue> &InVals) const {
2093 // Assign locations to each value returned by this call.
2094 SmallVector<CCValAssign, 16> RVLocs;
2095 bool Is64Bit = Subtarget->is64Bit();
2096 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2098 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2100 // Copy all of the result registers out of their specified physreg.
2101 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2102 CCValAssign &VA = RVLocs[i];
2103 EVT CopyVT = VA.getLocVT();
2105 // If this is x86-64, and we disabled SSE, we can't return FP values
2106 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2107 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2108 report_fatal_error("SSE register return with SSE disabled");
2111 // If we prefer to use the value in xmm registers, copy it out as f80 and
2112 // use a truncate to move it from fp stack reg to xmm reg.
2113 bool RoundAfterCopy = false;
2114 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2115 isScalarFPTypeInSSEReg(VA.getValVT())) {
2117 RoundAfterCopy = (CopyVT != VA.getLocVT());
2120 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2121 CopyVT, InFlag).getValue(1);
2122 SDValue Val = Chain.getValue(0);
2125 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2126 // This truncation won't change the value.
2127 DAG.getIntPtrConstant(1, dl));
2129 InFlag = Chain.getValue(2);
2130 InVals.push_back(Val);
2136 //===----------------------------------------------------------------------===//
2137 // C & StdCall & Fast Calling Convention implementation
2138 //===----------------------------------------------------------------------===//
2139 // StdCall calling convention seems to be standard for many Windows' API
2140 // routines and around. It differs from C calling convention just a little:
2141 // callee should clean up the stack, not caller. Symbols should be also
2142 // decorated in some fancy way :) It doesn't support any vector arguments.
2143 // For info on fast calling convention see Fast Calling Convention (tail call)
2144 // implementation LowerX86_32FastCCCallTo.
2146 /// CallIsStructReturn - Determines whether a call uses struct return
2148 enum StructReturnType {
2153 static StructReturnType
2154 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2156 return NotStructReturn;
2158 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2159 if (!Flags.isSRet())
2160 return NotStructReturn;
2161 if (Flags.isInReg())
2162 return RegStructReturn;
2163 return StackStructReturn;
2166 /// Determines whether a function uses struct return semantics.
2167 static StructReturnType
2168 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2170 return NotStructReturn;
2172 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2173 if (!Flags.isSRet())
2174 return NotStructReturn;
2175 if (Flags.isInReg())
2176 return RegStructReturn;
2177 return StackStructReturn;
2180 /// Make a copy of an aggregate at address specified by "Src" to address
2181 /// "Dst" with size and alignment information specified by the specific
2182 /// parameter attribute. The copy will be passed as a byval function parameter.
2184 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2185 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2187 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2189 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2190 /*isVolatile*/false, /*AlwaysInline=*/true,
2191 /*isTailCall*/false,
2192 MachinePointerInfo(), MachinePointerInfo());
2195 /// Return true if the calling convention is one that
2196 /// supports tail call optimization.
2197 static bool IsTailCallConvention(CallingConv::ID CC) {
2198 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2199 CC == CallingConv::HiPE);
2202 /// \brief Return true if the calling convention is a C calling convention.
2203 static bool IsCCallConvention(CallingConv::ID CC) {
2204 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2205 CC == CallingConv::X86_64_SysV);
2208 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2209 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2213 CallingConv::ID CalleeCC = CS.getCallingConv();
2214 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2220 /// Return true if the function is being made into
2221 /// a tailcall target by changing its ABI.
2222 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2223 bool GuaranteedTailCallOpt) {
2224 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2228 X86TargetLowering::LowerMemArgument(SDValue Chain,
2229 CallingConv::ID CallConv,
2230 const SmallVectorImpl<ISD::InputArg> &Ins,
2231 SDLoc dl, SelectionDAG &DAG,
2232 const CCValAssign &VA,
2233 MachineFrameInfo *MFI,
2235 // Create the nodes corresponding to a load from this parameter slot.
2236 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2237 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2238 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2239 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2242 // If value is passed by pointer we have address passed instead of the value
2244 if (VA.getLocInfo() == CCValAssign::Indirect)
2245 ValVT = VA.getLocVT();
2247 ValVT = VA.getValVT();
2249 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2250 // changed with more analysis.
2251 // In case of tail call optimization mark all arguments mutable. Since they
2252 // could be overwritten by lowering of arguments in case of a tail call.
2253 if (Flags.isByVal()) {
2254 unsigned Bytes = Flags.getByValSize();
2255 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2256 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2257 return DAG.getFrameIndex(FI, getPointerTy());
2259 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2260 VA.getLocMemOffset(), isImmutable);
2261 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2262 return DAG.getLoad(ValVT, dl, Chain, FIN,
2263 MachinePointerInfo::getFixedStack(FI),
2264 false, false, false, 0);
2268 // FIXME: Get this from tablegen.
2269 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2270 const X86Subtarget *Subtarget) {
2271 assert(Subtarget->is64Bit());
2273 if (Subtarget->isCallingConvWin64(CallConv)) {
2274 static const MCPhysReg GPR64ArgRegsWin64[] = {
2275 X86::RCX, X86::RDX, X86::R8, X86::R9
2277 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2280 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2281 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2283 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2286 // FIXME: Get this from tablegen.
2287 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2288 CallingConv::ID CallConv,
2289 const X86Subtarget *Subtarget) {
2290 assert(Subtarget->is64Bit());
2291 if (Subtarget->isCallingConvWin64(CallConv)) {
2292 // The XMM registers which might contain var arg parameters are shadowed
2293 // in their paired GPR. So we only need to save the GPR to their home
2295 // TODO: __vectorcall will change this.
2299 const Function *Fn = MF.getFunction();
2300 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2301 bool isSoftFloat = Subtarget->useSoftFloat();
2302 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2303 "SSE register cannot be used when SSE is disabled!");
2304 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2305 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2309 static const MCPhysReg XMMArgRegs64Bit[] = {
2310 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2311 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2313 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2317 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2318 CallingConv::ID CallConv,
2320 const SmallVectorImpl<ISD::InputArg> &Ins,
2323 SmallVectorImpl<SDValue> &InVals)
2325 MachineFunction &MF = DAG.getMachineFunction();
2326 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2327 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2329 const Function* Fn = MF.getFunction();
2330 if (Fn->hasExternalLinkage() &&
2331 Subtarget->isTargetCygMing() &&
2332 Fn->getName() == "main")
2333 FuncInfo->setForceFramePointer(true);
2335 MachineFrameInfo *MFI = MF.getFrameInfo();
2336 bool Is64Bit = Subtarget->is64Bit();
2337 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2339 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2340 "Var args not supported with calling convention fastcc, ghc or hipe");
2342 // Assign locations to all of the incoming arguments.
2343 SmallVector<CCValAssign, 16> ArgLocs;
2344 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2346 // Allocate shadow area for Win64
2348 CCInfo.AllocateStack(32, 8);
2350 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2352 unsigned LastVal = ~0U;
2354 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2355 CCValAssign &VA = ArgLocs[i];
2356 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2358 assert(VA.getValNo() != LastVal &&
2359 "Don't support value assigned to multiple locs yet");
2361 LastVal = VA.getValNo();
2363 if (VA.isRegLoc()) {
2364 EVT RegVT = VA.getLocVT();
2365 const TargetRegisterClass *RC;
2366 if (RegVT == MVT::i32)
2367 RC = &X86::GR32RegClass;
2368 else if (Is64Bit && RegVT == MVT::i64)
2369 RC = &X86::GR64RegClass;
2370 else if (RegVT == MVT::f32)
2371 RC = &X86::FR32RegClass;
2372 else if (RegVT == MVT::f64)
2373 RC = &X86::FR64RegClass;
2374 else if (RegVT.is512BitVector())
2375 RC = &X86::VR512RegClass;
2376 else if (RegVT.is256BitVector())
2377 RC = &X86::VR256RegClass;
2378 else if (RegVT.is128BitVector())
2379 RC = &X86::VR128RegClass;
2380 else if (RegVT == MVT::x86mmx)
2381 RC = &X86::VR64RegClass;
2382 else if (RegVT == MVT::i1)
2383 RC = &X86::VK1RegClass;
2384 else if (RegVT == MVT::v8i1)
2385 RC = &X86::VK8RegClass;
2386 else if (RegVT == MVT::v16i1)
2387 RC = &X86::VK16RegClass;
2388 else if (RegVT == MVT::v32i1)
2389 RC = &X86::VK32RegClass;
2390 else if (RegVT == MVT::v64i1)
2391 RC = &X86::VK64RegClass;
2393 llvm_unreachable("Unknown argument type!");
2395 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2396 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2398 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2399 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2401 if (VA.getLocInfo() == CCValAssign::SExt)
2402 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2403 DAG.getValueType(VA.getValVT()));
2404 else if (VA.getLocInfo() == CCValAssign::ZExt)
2405 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2406 DAG.getValueType(VA.getValVT()));
2407 else if (VA.getLocInfo() == CCValAssign::BCvt)
2408 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2410 if (VA.isExtInLoc()) {
2411 // Handle MMX values passed in XMM regs.
2412 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2413 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2415 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2418 assert(VA.isMemLoc());
2419 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2422 // If value is passed via pointer - do a load.
2423 if (VA.getLocInfo() == CCValAssign::Indirect)
2424 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2425 MachinePointerInfo(), false, false, false, 0);
2427 InVals.push_back(ArgValue);
2430 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2431 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2432 // The x86-64 ABIs require that for returning structs by value we copy
2433 // the sret argument into %rax/%eax (depending on ABI) for the return.
2434 // Win32 requires us to put the sret argument to %eax as well.
2435 // Save the argument into a virtual register so that we can access it
2436 // from the return points.
2437 if (Ins[i].Flags.isSRet()) {
2438 unsigned Reg = FuncInfo->getSRetReturnReg();
2440 MVT PtrTy = getPointerTy();
2441 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2442 FuncInfo->setSRetReturnReg(Reg);
2444 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2445 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2451 unsigned StackSize = CCInfo.getNextStackOffset();
2452 // Align stack specially for tail calls.
2453 if (FuncIsMadeTailCallSafe(CallConv,
2454 MF.getTarget().Options.GuaranteedTailCallOpt))
2455 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2457 // If the function takes variable number of arguments, make a frame index for
2458 // the start of the first vararg value... for expansion of llvm.va_start. We
2459 // can skip this if there are no va_start calls.
2460 if (MFI->hasVAStart() &&
2461 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2462 CallConv != CallingConv::X86_ThisCall))) {
2463 FuncInfo->setVarArgsFrameIndex(
2464 MFI->CreateFixedObject(1, StackSize, true));
2467 MachineModuleInfo &MMI = MF.getMMI();
2468 const Function *WinEHParent = nullptr;
2469 if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2470 WinEHParent = MMI.getWinEHParent(Fn);
2471 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2472 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2474 // Figure out if XMM registers are in use.
2475 assert(!(Subtarget->useSoftFloat() &&
2476 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2477 "SSE register cannot be used when SSE is disabled!");
2479 // 64-bit calling conventions support varargs and register parameters, so we
2480 // have to do extra work to spill them in the prologue.
2481 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2482 // Find the first unallocated argument registers.
2483 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2484 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2485 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2486 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2487 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2488 "SSE register cannot be used when SSE is disabled!");
2490 // Gather all the live in physical registers.
2491 SmallVector<SDValue, 6> LiveGPRs;
2492 SmallVector<SDValue, 8> LiveXMMRegs;
2494 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2495 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2497 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2499 if (!ArgXMMs.empty()) {
2500 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2501 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2502 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2503 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2504 LiveXMMRegs.push_back(
2505 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2510 // Get to the caller-allocated home save location. Add 8 to account
2511 // for the return address.
2512 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2513 FuncInfo->setRegSaveFrameIndex(
2514 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2515 // Fixup to set vararg frame on shadow area (4 x i64).
2517 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2519 // For X86-64, if there are vararg parameters that are passed via
2520 // registers, then we must store them to their spots on the stack so
2521 // they may be loaded by deferencing the result of va_next.
2522 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2523 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2524 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2525 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2528 // Store the integer parameter registers.
2529 SmallVector<SDValue, 8> MemOps;
2530 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2532 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2533 for (SDValue Val : LiveGPRs) {
2534 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2535 DAG.getIntPtrConstant(Offset, dl));
2537 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2538 MachinePointerInfo::getFixedStack(
2539 FuncInfo->getRegSaveFrameIndex(), Offset),
2541 MemOps.push_back(Store);
2545 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2546 // Now store the XMM (fp + vector) parameter registers.
2547 SmallVector<SDValue, 12> SaveXMMOps;
2548 SaveXMMOps.push_back(Chain);
2549 SaveXMMOps.push_back(ALVal);
2550 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2551 FuncInfo->getRegSaveFrameIndex(), dl));
2552 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2553 FuncInfo->getVarArgsFPOffset(), dl));
2554 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2556 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2557 MVT::Other, SaveXMMOps));
2560 if (!MemOps.empty())
2561 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2562 } else if (IsWinEHOutlined) {
2563 // Get to the caller-allocated home save location. Add 8 to account
2564 // for the return address.
2565 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2566 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2567 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2569 MMI.getWinEHFuncInfo(Fn)
2570 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2571 FuncInfo->getRegSaveFrameIndex();
2573 // Store the second integer parameter (rdx) into rsp+16 relative to the
2574 // stack pointer at the entry of the function.
2576 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2577 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2578 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2579 Chain = DAG.getStore(
2580 Val.getValue(1), dl, Val, RSFIN,
2581 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2582 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2585 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2586 // Find the largest legal vector type.
2587 MVT VecVT = MVT::Other;
2588 // FIXME: Only some x86_32 calling conventions support AVX512.
2589 if (Subtarget->hasAVX512() &&
2590 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2591 CallConv == CallingConv::Intel_OCL_BI)))
2592 VecVT = MVT::v16f32;
2593 else if (Subtarget->hasAVX())
2595 else if (Subtarget->hasSSE2())
2598 // We forward some GPRs and some vector types.
2599 SmallVector<MVT, 2> RegParmTypes;
2600 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2601 RegParmTypes.push_back(IntVT);
2602 if (VecVT != MVT::Other)
2603 RegParmTypes.push_back(VecVT);
2605 // Compute the set of forwarded registers. The rest are scratch.
2606 SmallVectorImpl<ForwardedRegister> &Forwards =
2607 FuncInfo->getForwardedMustTailRegParms();
2608 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2610 // Conservatively forward AL on x86_64, since it might be used for varargs.
2611 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2612 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2613 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2616 // Copy all forwards from physical to virtual registers.
2617 for (ForwardedRegister &F : Forwards) {
2618 // FIXME: Can we use a less constrained schedule?
2619 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2620 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2621 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2625 // Some CCs need callee pop.
2626 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2627 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2628 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2630 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2631 // If this is an sret function, the return should pop the hidden pointer.
2632 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2633 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2634 argsAreStructReturn(Ins) == StackStructReturn)
2635 FuncInfo->setBytesToPopOnReturn(4);
2639 // RegSaveFrameIndex is X86-64 only.
2640 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2641 if (CallConv == CallingConv::X86_FastCall ||
2642 CallConv == CallingConv::X86_ThisCall)
2643 // fastcc functions can't have varargs.
2644 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2647 FuncInfo->setArgumentStackSize(StackSize);
2649 if (IsWinEHParent) {
2650 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2651 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2652 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2653 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2654 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2655 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2656 /*isVolatile=*/true,
2657 /*isNonTemporal=*/false, /*Alignment=*/0);
2664 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2665 SDValue StackPtr, SDValue Arg,
2666 SDLoc dl, SelectionDAG &DAG,
2667 const CCValAssign &VA,
2668 ISD::ArgFlagsTy Flags) const {
2669 unsigned LocMemOffset = VA.getLocMemOffset();
2670 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2671 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2672 if (Flags.isByVal())
2673 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2675 return DAG.getStore(Chain, dl, Arg, PtrOff,
2676 MachinePointerInfo::getStack(LocMemOffset),
2680 /// Emit a load of return address if tail call
2681 /// optimization is performed and it is required.
2683 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2684 SDValue &OutRetAddr, SDValue Chain,
2685 bool IsTailCall, bool Is64Bit,
2686 int FPDiff, SDLoc dl) const {
2687 // Adjust the Return address stack slot.
2688 EVT VT = getPointerTy();
2689 OutRetAddr = getReturnAddressFrameIndex(DAG);
2691 // Load the "old" Return address.
2692 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2693 false, false, false, 0);
2694 return SDValue(OutRetAddr.getNode(), 1);
2697 /// Emit a store of the return address if tail call
2698 /// optimization is performed and it is required (FPDiff!=0).
2699 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2700 SDValue Chain, SDValue RetAddrFrIdx,
2701 EVT PtrVT, unsigned SlotSize,
2702 int FPDiff, SDLoc dl) {
2703 // Store the return address to the appropriate stack slot.
2704 if (!FPDiff) return Chain;
2705 // Calculate the new stack slot for the return address.
2706 int NewReturnAddrFI =
2707 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2709 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2710 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2711 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2717 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2718 SmallVectorImpl<SDValue> &InVals) const {
2719 SelectionDAG &DAG = CLI.DAG;
2721 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2722 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2723 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2724 SDValue Chain = CLI.Chain;
2725 SDValue Callee = CLI.Callee;
2726 CallingConv::ID CallConv = CLI.CallConv;
2727 bool &isTailCall = CLI.IsTailCall;
2728 bool isVarArg = CLI.IsVarArg;
2730 MachineFunction &MF = DAG.getMachineFunction();
2731 bool Is64Bit = Subtarget->is64Bit();
2732 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2733 StructReturnType SR = callIsStructReturn(Outs);
2734 bool IsSibcall = false;
2735 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2737 if (MF.getTarget().Options.DisableTailCalls)
2740 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2742 // Force this to be a tail call. The verifier rules are enough to ensure
2743 // that we can lower this successfully without moving the return address
2746 } else if (isTailCall) {
2747 // Check if it's really possible to do a tail call.
2748 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2749 isVarArg, SR != NotStructReturn,
2750 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2751 Outs, OutVals, Ins, DAG);
2753 // Sibcalls are automatically detected tailcalls which do not require
2755 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2762 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2763 "Var args not supported with calling convention fastcc, ghc or hipe");
2765 // Analyze operands of the call, assigning locations to each operand.
2766 SmallVector<CCValAssign, 16> ArgLocs;
2767 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2769 // Allocate shadow area for Win64
2771 CCInfo.AllocateStack(32, 8);
2773 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2775 // Get a count of how many bytes are to be pushed on the stack.
2776 unsigned NumBytes = CCInfo.getNextStackOffset();
2778 // This is a sibcall. The memory operands are available in caller's
2779 // own caller's stack.
2781 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2782 IsTailCallConvention(CallConv))
2783 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2786 if (isTailCall && !IsSibcall && !IsMustTail) {
2787 // Lower arguments at fp - stackoffset + fpdiff.
2788 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2790 FPDiff = NumBytesCallerPushed - NumBytes;
2792 // Set the delta of movement of the returnaddr stackslot.
2793 // But only set if delta is greater than previous delta.
2794 if (FPDiff < X86Info->getTCReturnAddrDelta())
2795 X86Info->setTCReturnAddrDelta(FPDiff);
2798 unsigned NumBytesToPush = NumBytes;
2799 unsigned NumBytesToPop = NumBytes;
2801 // If we have an inalloca argument, all stack space has already been allocated
2802 // for us and be right at the top of the stack. We don't support multiple
2803 // arguments passed in memory when using inalloca.
2804 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2806 if (!ArgLocs.back().isMemLoc())
2807 report_fatal_error("cannot use inalloca attribute on a register "
2809 if (ArgLocs.back().getLocMemOffset() != 0)
2810 report_fatal_error("any parameter with the inalloca attribute must be "
2811 "the only memory argument");
2815 Chain = DAG.getCALLSEQ_START(
2816 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2818 SDValue RetAddrFrIdx;
2819 // Load return address for tail calls.
2820 if (isTailCall && FPDiff)
2821 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2822 Is64Bit, FPDiff, dl);
2824 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2825 SmallVector<SDValue, 8> MemOpChains;
2828 // Walk the register/memloc assignments, inserting copies/loads. In the case
2829 // of tail call optimization arguments are handle later.
2830 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2831 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2832 // Skip inalloca arguments, they have already been written.
2833 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2834 if (Flags.isInAlloca())
2837 CCValAssign &VA = ArgLocs[i];
2838 EVT RegVT = VA.getLocVT();
2839 SDValue Arg = OutVals[i];
2840 bool isByVal = Flags.isByVal();
2842 // Promote the value if needed.
2843 switch (VA.getLocInfo()) {
2844 default: llvm_unreachable("Unknown loc info!");
2845 case CCValAssign::Full: break;
2846 case CCValAssign::SExt:
2847 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2849 case CCValAssign::ZExt:
2850 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2852 case CCValAssign::AExt:
2853 if (Arg.getValueType().getScalarType() == MVT::i1)
2854 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2855 else if (RegVT.is128BitVector()) {
2856 // Special case: passing MMX values in XMM registers.
2857 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2858 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2859 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2861 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2863 case CCValAssign::BCvt:
2864 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2866 case CCValAssign::Indirect: {
2867 // Store the argument.
2868 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2869 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2870 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2871 MachinePointerInfo::getFixedStack(FI),
2878 if (VA.isRegLoc()) {
2879 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2880 if (isVarArg && IsWin64) {
2881 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2882 // shadow reg if callee is a varargs function.
2883 unsigned ShadowReg = 0;
2884 switch (VA.getLocReg()) {
2885 case X86::XMM0: ShadowReg = X86::RCX; break;
2886 case X86::XMM1: ShadowReg = X86::RDX; break;
2887 case X86::XMM2: ShadowReg = X86::R8; break;
2888 case X86::XMM3: ShadowReg = X86::R9; break;
2891 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2893 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2894 assert(VA.isMemLoc());
2895 if (!StackPtr.getNode())
2896 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2898 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2899 dl, DAG, VA, Flags));
2903 if (!MemOpChains.empty())
2904 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2906 if (Subtarget->isPICStyleGOT()) {
2907 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2910 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2911 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2913 // If we are tail calling and generating PIC/GOT style code load the
2914 // address of the callee into ECX. The value in ecx is used as target of
2915 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2916 // for tail calls on PIC/GOT architectures. Normally we would just put the
2917 // address of GOT into ebx and then call target@PLT. But for tail calls
2918 // ebx would be restored (since ebx is callee saved) before jumping to the
2921 // Note: The actual moving to ECX is done further down.
2922 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2923 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2924 !G->getGlobal()->hasProtectedVisibility())
2925 Callee = LowerGlobalAddress(Callee, DAG);
2926 else if (isa<ExternalSymbolSDNode>(Callee))
2927 Callee = LowerExternalSymbol(Callee, DAG);
2931 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2932 // From AMD64 ABI document:
2933 // For calls that may call functions that use varargs or stdargs
2934 // (prototype-less calls or calls to functions containing ellipsis (...) in
2935 // the declaration) %al is used as hidden argument to specify the number
2936 // of SSE registers used. The contents of %al do not need to match exactly
2937 // the number of registers, but must be an ubound on the number of SSE
2938 // registers used and is in the range 0 - 8 inclusive.
2940 // Count the number of XMM registers allocated.
2941 static const MCPhysReg XMMArgRegs[] = {
2942 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2943 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2945 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2946 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2947 && "SSE registers cannot be used when SSE is disabled");
2949 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2950 DAG.getConstant(NumXMMRegs, dl,
2954 if (isVarArg && IsMustTail) {
2955 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2956 for (const auto &F : Forwards) {
2957 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2958 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2962 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2963 // don't need this because the eligibility check rejects calls that require
2964 // shuffling arguments passed in memory.
2965 if (!IsSibcall && isTailCall) {
2966 // Force all the incoming stack arguments to be loaded from the stack
2967 // before any new outgoing arguments are stored to the stack, because the
2968 // outgoing stack slots may alias the incoming argument stack slots, and
2969 // the alias isn't otherwise explicit. This is slightly more conservative
2970 // than necessary, because it means that each store effectively depends
2971 // on every argument instead of just those arguments it would clobber.
2972 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2974 SmallVector<SDValue, 8> MemOpChains2;
2977 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2978 CCValAssign &VA = ArgLocs[i];
2981 assert(VA.isMemLoc());
2982 SDValue Arg = OutVals[i];
2983 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2984 // Skip inalloca arguments. They don't require any work.
2985 if (Flags.isInAlloca())
2987 // Create frame index.
2988 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2989 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2990 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2991 FIN = DAG.getFrameIndex(FI, getPointerTy());
2993 if (Flags.isByVal()) {
2994 // Copy relative to framepointer.
2995 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
2996 if (!StackPtr.getNode())
2997 StackPtr = DAG.getCopyFromReg(Chain, dl,
2998 RegInfo->getStackRegister(),
3000 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3002 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3006 // Store relative to framepointer.
3007 MemOpChains2.push_back(
3008 DAG.getStore(ArgChain, dl, Arg, FIN,
3009 MachinePointerInfo::getFixedStack(FI),
3014 if (!MemOpChains2.empty())
3015 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3017 // Store the return address to the appropriate stack slot.
3018 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3019 getPointerTy(), RegInfo->getSlotSize(),
3023 // Build a sequence of copy-to-reg nodes chained together with token chain
3024 // and flag operands which copy the outgoing args into registers.
3026 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3027 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3028 RegsToPass[i].second, InFlag);
3029 InFlag = Chain.getValue(1);
3032 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3033 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3034 // In the 64-bit large code model, we have to make all calls
3035 // through a register, since the call instruction's 32-bit
3036 // pc-relative offset may not be large enough to hold the whole
3038 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3039 // If the callee is a GlobalAddress node (quite common, every direct call
3040 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3042 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3044 // We should use extra load for direct calls to dllimported functions in
3046 const GlobalValue *GV = G->getGlobal();
3047 if (!GV->hasDLLImportStorageClass()) {
3048 unsigned char OpFlags = 0;
3049 bool ExtraLoad = false;
3050 unsigned WrapperKind = ISD::DELETED_NODE;
3052 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3053 // external symbols most go through the PLT in PIC mode. If the symbol
3054 // has hidden or protected visibility, or if it is static or local, then
3055 // we don't need to use the PLT - we can directly call it.
3056 if (Subtarget->isTargetELF() &&
3057 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3058 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3059 OpFlags = X86II::MO_PLT;
3060 } else if (Subtarget->isPICStyleStubAny() &&
3061 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3062 (!Subtarget->getTargetTriple().isMacOSX() ||
3063 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3064 // PC-relative references to external symbols should go through $stub,
3065 // unless we're building with the leopard linker or later, which
3066 // automatically synthesizes these stubs.
3067 OpFlags = X86II::MO_DARWIN_STUB;
3068 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3069 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3070 // If the function is marked as non-lazy, generate an indirect call
3071 // which loads from the GOT directly. This avoids runtime overhead
3072 // at the cost of eager binding (and one extra byte of encoding).
3073 OpFlags = X86II::MO_GOTPCREL;
3074 WrapperKind = X86ISD::WrapperRIP;
3078 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3079 G->getOffset(), OpFlags);
3081 // Add a wrapper if needed.
3082 if (WrapperKind != ISD::DELETED_NODE)
3083 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3084 // Add extra indirection if needed.
3086 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3087 MachinePointerInfo::getGOT(),
3088 false, false, false, 0);
3090 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3091 unsigned char OpFlags = 0;
3093 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3094 // external symbols should go through the PLT.
3095 if (Subtarget->isTargetELF() &&
3096 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3097 OpFlags = X86II::MO_PLT;
3098 } else if (Subtarget->isPICStyleStubAny() &&
3099 (!Subtarget->getTargetTriple().isMacOSX() ||
3100 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3101 // PC-relative references to external symbols should go through $stub,
3102 // unless we're building with the leopard linker or later, which
3103 // automatically synthesizes these stubs.
3104 OpFlags = X86II::MO_DARWIN_STUB;
3107 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3109 } else if (Subtarget->isTarget64BitILP32() &&
3110 Callee->getValueType(0) == MVT::i32) {
3111 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3112 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3115 // Returns a chain & a flag for retval copy to use.
3116 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3117 SmallVector<SDValue, 8> Ops;
3119 if (!IsSibcall && isTailCall) {
3120 Chain = DAG.getCALLSEQ_END(Chain,
3121 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3122 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3123 InFlag = Chain.getValue(1);
3126 Ops.push_back(Chain);
3127 Ops.push_back(Callee);
3130 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3132 // Add argument registers to the end of the list so that they are known live
3134 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3135 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3136 RegsToPass[i].second.getValueType()));
3138 // Add a register mask operand representing the call-preserved registers.
3139 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3140 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3141 assert(Mask && "Missing call preserved mask for calling convention");
3142 Ops.push_back(DAG.getRegisterMask(Mask));
3144 if (InFlag.getNode())
3145 Ops.push_back(InFlag);
3149 //// If this is the first return lowered for this function, add the regs
3150 //// to the liveout set for the function.
3151 // This isn't right, although it's probably harmless on x86; liveouts
3152 // should be computed from returns not tail calls. Consider a void
3153 // function making a tail call to a function returning int.
3154 MF.getFrameInfo()->setHasTailCall();
3155 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3158 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3159 InFlag = Chain.getValue(1);
3161 // Create the CALLSEQ_END node.
3162 unsigned NumBytesForCalleeToPop;
3163 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3164 DAG.getTarget().Options.GuaranteedTailCallOpt))
3165 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3166 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3167 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3168 SR == StackStructReturn)
3169 // If this is a call to a struct-return function, the callee
3170 // pops the hidden struct pointer, so we have to push it back.
3171 // This is common for Darwin/X86, Linux & Mingw32 targets.
3172 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3173 NumBytesForCalleeToPop = 4;
3175 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3177 // Returns a flag for retval copy to use.
3179 Chain = DAG.getCALLSEQ_END(Chain,
3180 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3181 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3184 InFlag = Chain.getValue(1);
3187 // Handle result values, copying them out of physregs into vregs that we
3189 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3190 Ins, dl, DAG, InVals);
3193 //===----------------------------------------------------------------------===//
3194 // Fast Calling Convention (tail call) implementation
3195 //===----------------------------------------------------------------------===//
3197 // Like std call, callee cleans arguments, convention except that ECX is
3198 // reserved for storing the tail called function address. Only 2 registers are
3199 // free for argument passing (inreg). Tail call optimization is performed
3201 // * tailcallopt is enabled
3202 // * caller/callee are fastcc
3203 // On X86_64 architecture with GOT-style position independent code only local
3204 // (within module) calls are supported at the moment.
3205 // To keep the stack aligned according to platform abi the function
3206 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3207 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3208 // If a tail called function callee has more arguments than the caller the
3209 // caller needs to make sure that there is room to move the RETADDR to. This is
3210 // achieved by reserving an area the size of the argument delta right after the
3211 // original RETADDR, but before the saved framepointer or the spilled registers
3212 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3224 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3225 /// for a 16 byte align requirement.
3227 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3228 SelectionDAG& DAG) const {
3229 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3230 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3231 unsigned StackAlignment = TFI.getStackAlignment();
3232 uint64_t AlignMask = StackAlignment - 1;
3233 int64_t Offset = StackSize;
3234 unsigned SlotSize = RegInfo->getSlotSize();
3235 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3236 // Number smaller than 12 so just add the difference.
3237 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3239 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3240 Offset = ((~AlignMask) & Offset) + StackAlignment +
3241 (StackAlignment-SlotSize);
3246 /// MatchingStackOffset - Return true if the given stack call argument is
3247 /// already available in the same position (relatively) of the caller's
3248 /// incoming argument stack.
3250 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3251 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3252 const X86InstrInfo *TII) {
3253 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3255 if (Arg.getOpcode() == ISD::CopyFromReg) {
3256 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3257 if (!TargetRegisterInfo::isVirtualRegister(VR))
3259 MachineInstr *Def = MRI->getVRegDef(VR);
3262 if (!Flags.isByVal()) {
3263 if (!TII->isLoadFromStackSlot(Def, FI))
3266 unsigned Opcode = Def->getOpcode();
3267 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3268 Opcode == X86::LEA64_32r) &&
3269 Def->getOperand(1).isFI()) {
3270 FI = Def->getOperand(1).getIndex();
3271 Bytes = Flags.getByValSize();
3275 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3276 if (Flags.isByVal())
3277 // ByVal argument is passed in as a pointer but it's now being
3278 // dereferenced. e.g.
3279 // define @foo(%struct.X* %A) {
3280 // tail call @bar(%struct.X* byval %A)
3283 SDValue Ptr = Ld->getBasePtr();
3284 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3287 FI = FINode->getIndex();
3288 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3289 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3290 FI = FINode->getIndex();
3291 Bytes = Flags.getByValSize();
3295 assert(FI != INT_MAX);
3296 if (!MFI->isFixedObjectIndex(FI))
3298 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3301 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3302 /// for tail call optimization. Targets which want to do tail call
3303 /// optimization should implement this function.
3305 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3306 CallingConv::ID CalleeCC,
3308 bool isCalleeStructRet,
3309 bool isCallerStructRet,
3311 const SmallVectorImpl<ISD::OutputArg> &Outs,
3312 const SmallVectorImpl<SDValue> &OutVals,
3313 const SmallVectorImpl<ISD::InputArg> &Ins,
3314 SelectionDAG &DAG) const {
3315 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3318 // If -tailcallopt is specified, make fastcc functions tail-callable.
3319 const MachineFunction &MF = DAG.getMachineFunction();
3320 const Function *CallerF = MF.getFunction();
3322 // If the function return type is x86_fp80 and the callee return type is not,
3323 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3324 // perform a tailcall optimization here.
3325 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3328 CallingConv::ID CallerCC = CallerF->getCallingConv();
3329 bool CCMatch = CallerCC == CalleeCC;
3330 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3331 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3333 // Win64 functions have extra shadow space for argument homing. Don't do the
3334 // sibcall if the caller and callee have mismatched expectations for this
3336 if (IsCalleeWin64 != IsCallerWin64)
3339 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3340 if (IsTailCallConvention(CalleeCC) && CCMatch)
3345 // Look for obvious safe cases to perform tail call optimization that do not
3346 // require ABI changes. This is what gcc calls sibcall.
3348 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3349 // emit a special epilogue.
3350 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3351 if (RegInfo->needsStackRealignment(MF))
3354 // Also avoid sibcall optimization if either caller or callee uses struct
3355 // return semantics.
3356 if (isCalleeStructRet || isCallerStructRet)
3359 // An stdcall/thiscall caller is expected to clean up its arguments; the
3360 // callee isn't going to do that.
3361 // FIXME: this is more restrictive than needed. We could produce a tailcall
3362 // when the stack adjustment matches. For example, with a thiscall that takes
3363 // only one argument.
3364 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3365 CallerCC == CallingConv::X86_ThisCall))
3368 // Do not sibcall optimize vararg calls unless all arguments are passed via
3370 if (isVarArg && !Outs.empty()) {
3372 // Optimizing for varargs on Win64 is unlikely to be safe without
3373 // additional testing.
3374 if (IsCalleeWin64 || IsCallerWin64)
3377 SmallVector<CCValAssign, 16> ArgLocs;
3378 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3381 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3382 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3383 if (!ArgLocs[i].isRegLoc())
3387 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3388 // stack. Therefore, if it's not used by the call it is not safe to optimize
3389 // this into a sibcall.
3390 bool Unused = false;
3391 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3398 SmallVector<CCValAssign, 16> RVLocs;
3399 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3401 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3402 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3403 CCValAssign &VA = RVLocs[i];
3404 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3409 // If the calling conventions do not match, then we'd better make sure the
3410 // results are returned in the same way as what the caller expects.
3412 SmallVector<CCValAssign, 16> RVLocs1;
3413 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3415 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3417 SmallVector<CCValAssign, 16> RVLocs2;
3418 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3420 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3422 if (RVLocs1.size() != RVLocs2.size())
3424 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3425 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3427 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3429 if (RVLocs1[i].isRegLoc()) {
3430 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3433 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3439 // If the callee takes no arguments then go on to check the results of the
3441 if (!Outs.empty()) {
3442 // Check if stack adjustment is needed. For now, do not do this if any
3443 // argument is passed on the stack.
3444 SmallVector<CCValAssign, 16> ArgLocs;
3445 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3448 // Allocate shadow area for Win64
3450 CCInfo.AllocateStack(32, 8);
3452 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3453 if (CCInfo.getNextStackOffset()) {
3454 MachineFunction &MF = DAG.getMachineFunction();
3455 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3458 // Check if the arguments are already laid out in the right way as
3459 // the caller's fixed stack objects.
3460 MachineFrameInfo *MFI = MF.getFrameInfo();
3461 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3462 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3463 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3464 CCValAssign &VA = ArgLocs[i];
3465 SDValue Arg = OutVals[i];
3466 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3467 if (VA.getLocInfo() == CCValAssign::Indirect)
3469 if (!VA.isRegLoc()) {
3470 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3477 // If the tailcall address may be in a register, then make sure it's
3478 // possible to register allocate for it. In 32-bit, the call address can
3479 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3480 // callee-saved registers are restored. These happen to be the same
3481 // registers used to pass 'inreg' arguments so watch out for those.
3482 if (!Subtarget->is64Bit() &&
3483 ((!isa<GlobalAddressSDNode>(Callee) &&
3484 !isa<ExternalSymbolSDNode>(Callee)) ||
3485 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3486 unsigned NumInRegs = 0;
3487 // In PIC we need an extra register to formulate the address computation
3489 unsigned MaxInRegs =
3490 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3492 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3493 CCValAssign &VA = ArgLocs[i];
3496 unsigned Reg = VA.getLocReg();
3499 case X86::EAX: case X86::EDX: case X86::ECX:
3500 if (++NumInRegs == MaxInRegs)
3512 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3513 const TargetLibraryInfo *libInfo) const {
3514 return X86::createFastISel(funcInfo, libInfo);
3517 //===----------------------------------------------------------------------===//
3518 // Other Lowering Hooks
3519 //===----------------------------------------------------------------------===//
3521 static bool MayFoldLoad(SDValue Op) {
3522 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3525 static bool MayFoldIntoStore(SDValue Op) {
3526 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3529 static bool isTargetShuffle(unsigned Opcode) {
3531 default: return false;
3532 case X86ISD::BLENDI:
3533 case X86ISD::PSHUFB:
3534 case X86ISD::PSHUFD:
3535 case X86ISD::PSHUFHW:
3536 case X86ISD::PSHUFLW:
3538 case X86ISD::PALIGNR:
3539 case X86ISD::MOVLHPS:
3540 case X86ISD::MOVLHPD:
3541 case X86ISD::MOVHLPS:
3542 case X86ISD::MOVLPS:
3543 case X86ISD::MOVLPD:
3544 case X86ISD::MOVSHDUP:
3545 case X86ISD::MOVSLDUP:
3546 case X86ISD::MOVDDUP:
3549 case X86ISD::UNPCKL:
3550 case X86ISD::UNPCKH:
3551 case X86ISD::VPERMILPI:
3552 case X86ISD::VPERM2X128:
3553 case X86ISD::VPERMI:
3558 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3559 SDValue V1, unsigned TargetMask,
3560 SelectionDAG &DAG) {
3562 default: llvm_unreachable("Unknown x86 shuffle node");
3563 case X86ISD::PSHUFD:
3564 case X86ISD::PSHUFHW:
3565 case X86ISD::PSHUFLW:
3566 case X86ISD::VPERMILPI:
3567 case X86ISD::VPERMI:
3568 return DAG.getNode(Opc, dl, VT, V1,
3569 DAG.getConstant(TargetMask, dl, MVT::i8));
3573 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3574 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3576 default: llvm_unreachable("Unknown x86 shuffle node");
3577 case X86ISD::MOVLHPS:
3578 case X86ISD::MOVLHPD:
3579 case X86ISD::MOVHLPS:
3580 case X86ISD::MOVLPS:
3581 case X86ISD::MOVLPD:
3584 case X86ISD::UNPCKL:
3585 case X86ISD::UNPCKH:
3586 return DAG.getNode(Opc, dl, VT, V1, V2);
3590 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3591 MachineFunction &MF = DAG.getMachineFunction();
3592 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3593 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3594 int ReturnAddrIndex = FuncInfo->getRAIndex();
3596 if (ReturnAddrIndex == 0) {
3597 // Set up a frame object for the return address.
3598 unsigned SlotSize = RegInfo->getSlotSize();
3599 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3602 FuncInfo->setRAIndex(ReturnAddrIndex);
3605 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3608 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3609 bool hasSymbolicDisplacement) {
3610 // Offset should fit into 32 bit immediate field.
3611 if (!isInt<32>(Offset))
3614 // If we don't have a symbolic displacement - we don't have any extra
3616 if (!hasSymbolicDisplacement)
3619 // FIXME: Some tweaks might be needed for medium code model.
3620 if (M != CodeModel::Small && M != CodeModel::Kernel)
3623 // For small code model we assume that latest object is 16MB before end of 31
3624 // bits boundary. We may also accept pretty large negative constants knowing
3625 // that all objects are in the positive half of address space.
3626 if (M == CodeModel::Small && Offset < 16*1024*1024)
3629 // For kernel code model we know that all object resist in the negative half
3630 // of 32bits address space. We may not accept negative offsets, since they may
3631 // be just off and we may accept pretty large positive ones.
3632 if (M == CodeModel::Kernel && Offset >= 0)
3638 /// isCalleePop - Determines whether the callee is required to pop its
3639 /// own arguments. Callee pop is necessary to support tail calls.
3640 bool X86::isCalleePop(CallingConv::ID CallingConv,
3641 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3642 switch (CallingConv) {
3645 case CallingConv::X86_StdCall:
3646 case CallingConv::X86_FastCall:
3647 case CallingConv::X86_ThisCall:
3649 case CallingConv::Fast:
3650 case CallingConv::GHC:
3651 case CallingConv::HiPE:
3658 /// \brief Return true if the condition is an unsigned comparison operation.
3659 static bool isX86CCUnsigned(unsigned X86CC) {
3661 default: llvm_unreachable("Invalid integer condition!");
3662 case X86::COND_E: return true;
3663 case X86::COND_G: return false;
3664 case X86::COND_GE: return false;
3665 case X86::COND_L: return false;
3666 case X86::COND_LE: return false;
3667 case X86::COND_NE: return true;
3668 case X86::COND_B: return true;
3669 case X86::COND_A: return true;
3670 case X86::COND_BE: return true;
3671 case X86::COND_AE: return true;
3673 llvm_unreachable("covered switch fell through?!");
3676 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3677 /// specific condition code, returning the condition code and the LHS/RHS of the
3678 /// comparison to make.
3679 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3680 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3682 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3683 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3684 // X > -1 -> X == 0, jump !sign.
3685 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3686 return X86::COND_NS;
3688 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3689 // X < 0 -> X == 0, jump on sign.
3692 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3694 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3695 return X86::COND_LE;
3699 switch (SetCCOpcode) {
3700 default: llvm_unreachable("Invalid integer condition!");
3701 case ISD::SETEQ: return X86::COND_E;
3702 case ISD::SETGT: return X86::COND_G;
3703 case ISD::SETGE: return X86::COND_GE;
3704 case ISD::SETLT: return X86::COND_L;
3705 case ISD::SETLE: return X86::COND_LE;
3706 case ISD::SETNE: return X86::COND_NE;
3707 case ISD::SETULT: return X86::COND_B;
3708 case ISD::SETUGT: return X86::COND_A;
3709 case ISD::SETULE: return X86::COND_BE;
3710 case ISD::SETUGE: return X86::COND_AE;
3714 // First determine if it is required or is profitable to flip the operands.
3716 // If LHS is a foldable load, but RHS is not, flip the condition.
3717 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3718 !ISD::isNON_EXTLoad(RHS.getNode())) {
3719 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3720 std::swap(LHS, RHS);
3723 switch (SetCCOpcode) {
3729 std::swap(LHS, RHS);
3733 // On a floating point condition, the flags are set as follows:
3735 // 0 | 0 | 0 | X > Y
3736 // 0 | 0 | 1 | X < Y
3737 // 1 | 0 | 0 | X == Y
3738 // 1 | 1 | 1 | unordered
3739 switch (SetCCOpcode) {
3740 default: llvm_unreachable("Condcode should be pre-legalized away");
3742 case ISD::SETEQ: return X86::COND_E;
3743 case ISD::SETOLT: // flipped
3745 case ISD::SETGT: return X86::COND_A;
3746 case ISD::SETOLE: // flipped
3748 case ISD::SETGE: return X86::COND_AE;
3749 case ISD::SETUGT: // flipped
3751 case ISD::SETLT: return X86::COND_B;
3752 case ISD::SETUGE: // flipped
3754 case ISD::SETLE: return X86::COND_BE;
3756 case ISD::SETNE: return X86::COND_NE;
3757 case ISD::SETUO: return X86::COND_P;
3758 case ISD::SETO: return X86::COND_NP;
3760 case ISD::SETUNE: return X86::COND_INVALID;
3764 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3765 /// code. Current x86 isa includes the following FP cmov instructions:
3766 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3767 static bool hasFPCMov(unsigned X86CC) {
3783 /// isFPImmLegal - Returns true if the target can instruction select the
3784 /// specified FP immediate natively. If false, the legalizer will
3785 /// materialize the FP immediate as a load from a constant pool.
3786 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3787 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3788 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3794 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3795 ISD::LoadExtType ExtTy,
3797 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3798 // relocation target a movq or addq instruction: don't let the load shrink.
3799 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3800 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3801 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3802 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3806 /// \brief Returns true if it is beneficial to convert a load of a constant
3807 /// to just the constant itself.
3808 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3810 assert(Ty->isIntegerTy());
3812 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3813 if (BitSize == 0 || BitSize > 64)
3818 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3819 unsigned Index) const {
3820 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3823 return (Index == 0 || Index == ResVT.getVectorNumElements());
3826 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3827 // Speculate cttz only if we can directly use TZCNT.
3828 return Subtarget->hasBMI();
3831 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3832 // Speculate ctlz only if we can directly use LZCNT.
3833 return Subtarget->hasLZCNT();
3836 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3837 /// the specified range (L, H].
3838 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3839 return (Val < 0) || (Val >= Low && Val < Hi);
3842 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3843 /// specified value.
3844 static bool isUndefOrEqual(int Val, int CmpVal) {
3845 return (Val < 0 || Val == CmpVal);
3848 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3849 /// from position Pos and ending in Pos+Size, falls within the specified
3850 /// sequential range (Low, Low+Size]. or is undef.
3851 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3852 unsigned Pos, unsigned Size, int Low) {
3853 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3854 if (!isUndefOrEqual(Mask[i], Low))
3859 /// isVEXTRACTIndex - Return true if the specified
3860 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3861 /// suitable for instruction that extract 128 or 256 bit vectors
3862 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3863 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3864 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3867 // The index should be aligned on a vecWidth-bit boundary.
3869 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3871 MVT VT = N->getSimpleValueType(0);
3872 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3873 bool Result = (Index * ElSize) % vecWidth == 0;
3878 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3879 /// operand specifies a subvector insert that is suitable for input to
3880 /// insertion of 128 or 256-bit subvectors
3881 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3882 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3883 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3885 // The index should be aligned on a vecWidth-bit boundary.
3887 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3889 MVT VT = N->getSimpleValueType(0);
3890 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3891 bool Result = (Index * ElSize) % vecWidth == 0;
3896 bool X86::isVINSERT128Index(SDNode *N) {
3897 return isVINSERTIndex(N, 128);
3900 bool X86::isVINSERT256Index(SDNode *N) {
3901 return isVINSERTIndex(N, 256);
3904 bool X86::isVEXTRACT128Index(SDNode *N) {
3905 return isVEXTRACTIndex(N, 128);
3908 bool X86::isVEXTRACT256Index(SDNode *N) {
3909 return isVEXTRACTIndex(N, 256);
3912 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3913 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3914 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3915 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3918 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3920 MVT VecVT = N->getOperand(0).getSimpleValueType();
3921 MVT ElVT = VecVT.getVectorElementType();
3923 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3924 return Index / NumElemsPerChunk;
3927 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3928 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3929 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3930 llvm_unreachable("Illegal insert subvector for VINSERT");
3933 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3935 MVT VecVT = N->getSimpleValueType(0);
3936 MVT ElVT = VecVT.getVectorElementType();
3938 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3939 return Index / NumElemsPerChunk;
3942 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3943 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3944 /// and VINSERTI128 instructions.
3945 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3946 return getExtractVEXTRACTImmediate(N, 128);
3949 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3950 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3951 /// and VINSERTI64x4 instructions.
3952 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3953 return getExtractVEXTRACTImmediate(N, 256);
3956 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3957 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3958 /// and VINSERTI128 instructions.
3959 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3960 return getInsertVINSERTImmediate(N, 128);
3963 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3964 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3965 /// and VINSERTI64x4 instructions.
3966 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3967 return getInsertVINSERTImmediate(N, 256);
3970 /// isZero - Returns true if Elt is a constant integer zero
3971 static bool isZero(SDValue V) {
3972 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3973 return C && C->isNullValue();
3976 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3978 bool X86::isZeroNode(SDValue Elt) {
3981 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3982 return CFP->getValueAPF().isPosZero();
3986 /// getZeroVector - Returns a vector of specified type with all zero elements.
3988 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3989 SelectionDAG &DAG, SDLoc dl) {
3990 assert(VT.isVector() && "Expected a vector type");
3992 // Always build SSE zero vectors as <4 x i32> bitcasted
3993 // to their dest type. This ensures they get CSE'd.
3995 if (VT.is128BitVector()) { // SSE
3996 if (Subtarget->hasSSE2()) { // SSE2
3997 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3998 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4000 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4001 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4003 } else if (VT.is256BitVector()) { // AVX
4004 if (Subtarget->hasInt256()) { // AVX2
4005 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4006 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4007 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4009 // 256-bit logic and arithmetic instructions in AVX are all
4010 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4011 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4012 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4013 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4015 } else if (VT.is512BitVector()) { // AVX-512
4016 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4017 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4018 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4019 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4020 } else if (VT.getScalarType() == MVT::i1) {
4022 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4023 && "Unexpected vector type");
4024 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4025 && "Unexpected vector type");
4026 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4027 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4028 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4030 llvm_unreachable("Unexpected vector type");
4032 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4035 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4036 SelectionDAG &DAG, SDLoc dl,
4037 unsigned vectorWidth) {
4038 assert((vectorWidth == 128 || vectorWidth == 256) &&
4039 "Unsupported vector width");
4040 EVT VT = Vec.getValueType();
4041 EVT ElVT = VT.getVectorElementType();
4042 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4043 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4044 VT.getVectorNumElements()/Factor);
4046 // Extract from UNDEF is UNDEF.
4047 if (Vec.getOpcode() == ISD::UNDEF)
4048 return DAG.getUNDEF(ResultVT);
4050 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4051 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4053 // This is the index of the first element of the vectorWidth-bit chunk
4055 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4058 // If the input is a buildvector just emit a smaller one.
4059 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4060 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4061 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4064 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4065 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4068 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4069 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4070 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4071 /// instructions or a simple subregister reference. Idx is an index in the
4072 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4073 /// lowering EXTRACT_VECTOR_ELT operations easier.
4074 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4075 SelectionDAG &DAG, SDLoc dl) {
4076 assert((Vec.getValueType().is256BitVector() ||
4077 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4078 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4081 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4082 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4083 SelectionDAG &DAG, SDLoc dl) {
4084 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4085 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4088 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4089 unsigned IdxVal, SelectionDAG &DAG,
4090 SDLoc dl, unsigned vectorWidth) {
4091 assert((vectorWidth == 128 || vectorWidth == 256) &&
4092 "Unsupported vector width");
4093 // Inserting UNDEF is Result
4094 if (Vec.getOpcode() == ISD::UNDEF)
4096 EVT VT = Vec.getValueType();
4097 EVT ElVT = VT.getVectorElementType();
4098 EVT ResultVT = Result.getValueType();
4100 // Insert the relevant vectorWidth bits.
4101 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4103 // This is the index of the first element of the vectorWidth-bit chunk
4105 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4108 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4109 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4112 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4113 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4114 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4115 /// simple superregister reference. Idx is an index in the 128 bits
4116 /// we want. It need not be aligned to a 128-bit boundary. That makes
4117 /// lowering INSERT_VECTOR_ELT operations easier.
4118 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4119 SelectionDAG &DAG, SDLoc dl) {
4120 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4122 // For insertion into the zero index (low half) of a 256-bit vector, it is
4123 // more efficient to generate a blend with immediate instead of an insert*128.
4124 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4125 // extend the subvector to the size of the result vector. Make sure that
4126 // we are not recursing on that node by checking for undef here.
4127 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4128 Result.getOpcode() != ISD::UNDEF) {
4129 EVT ResultVT = Result.getValueType();
4130 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4131 SDValue Undef = DAG.getUNDEF(ResultVT);
4132 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4135 // The blend instruction, and therefore its mask, depend on the data type.
4136 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4137 if (ScalarType.isFloatingPoint()) {
4138 // Choose either vblendps (float) or vblendpd (double).
4139 unsigned ScalarSize = ScalarType.getSizeInBits();
4140 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4141 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4142 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4143 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4146 const X86Subtarget &Subtarget =
4147 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4149 // AVX2 is needed for 256-bit integer blend support.
4150 // Integers must be cast to 32-bit because there is only vpblendd;
4151 // vpblendw can't be used for this because it has a handicapped mask.
4153 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4154 // is still more efficient than using the wrong domain vinsertf128 that
4155 // will be created by InsertSubVector().
4156 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4158 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4159 Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4160 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4161 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4164 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4167 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4168 SelectionDAG &DAG, SDLoc dl) {
4169 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4170 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4173 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4174 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4175 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4176 /// large BUILD_VECTORS.
4177 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4178 unsigned NumElems, SelectionDAG &DAG,
4180 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4181 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4184 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4185 unsigned NumElems, SelectionDAG &DAG,
4187 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4188 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4191 /// getOnesVector - Returns a vector of specified type with all bits set.
4192 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4193 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4194 /// Then bitcast to their original type, ensuring they get CSE'd.
4195 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4197 assert(VT.isVector() && "Expected a vector type");
4199 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4201 if (VT.is256BitVector()) {
4202 if (HasInt256) { // AVX2
4203 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4204 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4206 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4207 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4209 } else if (VT.is128BitVector()) {
4210 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4212 llvm_unreachable("Unexpected vector type");
4214 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4217 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4218 /// operation of specified width.
4219 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4221 unsigned NumElems = VT.getVectorNumElements();
4222 SmallVector<int, 8> Mask;
4223 Mask.push_back(NumElems);
4224 for (unsigned i = 1; i != NumElems; ++i)
4226 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4229 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4230 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4232 unsigned NumElems = VT.getVectorNumElements();
4233 SmallVector<int, 8> Mask;
4234 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4236 Mask.push_back(i + NumElems);
4238 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4241 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4242 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4244 unsigned NumElems = VT.getVectorNumElements();
4245 SmallVector<int, 8> Mask;
4246 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4247 Mask.push_back(i + Half);
4248 Mask.push_back(i + NumElems + Half);
4250 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4253 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4254 /// vector of zero or undef vector. This produces a shuffle where the low
4255 /// element of V2 is swizzled into the zero/undef vector, landing at element
4256 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4257 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4259 const X86Subtarget *Subtarget,
4260 SelectionDAG &DAG) {
4261 MVT VT = V2.getSimpleValueType();
4263 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4264 unsigned NumElems = VT.getVectorNumElements();
4265 SmallVector<int, 16> MaskVec;
4266 for (unsigned i = 0; i != NumElems; ++i)
4267 // If this is the insertion idx, put the low elt of V2 here.
4268 MaskVec.push_back(i == Idx ? NumElems : i);
4269 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4272 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4273 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4274 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4275 /// shuffles which use a single input multiple times, and in those cases it will
4276 /// adjust the mask to only have indices within that single input.
4277 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4278 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4279 unsigned NumElems = VT.getVectorNumElements();
4283 bool IsFakeUnary = false;
4284 switch(N->getOpcode()) {
4285 case X86ISD::BLENDI:
4286 ImmN = N->getOperand(N->getNumOperands()-1);
4287 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4290 ImmN = N->getOperand(N->getNumOperands()-1);
4291 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4292 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4294 case X86ISD::UNPCKH:
4295 DecodeUNPCKHMask(VT, Mask);
4296 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4298 case X86ISD::UNPCKL:
4299 DecodeUNPCKLMask(VT, Mask);
4300 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4302 case X86ISD::MOVHLPS:
4303 DecodeMOVHLPSMask(NumElems, Mask);
4304 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4306 case X86ISD::MOVLHPS:
4307 DecodeMOVLHPSMask(NumElems, Mask);
4308 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4310 case X86ISD::PALIGNR:
4311 ImmN = N->getOperand(N->getNumOperands()-1);
4312 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4314 case X86ISD::PSHUFD:
4315 case X86ISD::VPERMILPI:
4316 ImmN = N->getOperand(N->getNumOperands()-1);
4317 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4320 case X86ISD::PSHUFHW:
4321 ImmN = N->getOperand(N->getNumOperands()-1);
4322 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4325 case X86ISD::PSHUFLW:
4326 ImmN = N->getOperand(N->getNumOperands()-1);
4327 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4330 case X86ISD::PSHUFB: {
4332 SDValue MaskNode = N->getOperand(1);
4333 while (MaskNode->getOpcode() == ISD::BITCAST)
4334 MaskNode = MaskNode->getOperand(0);
4336 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4337 // If we have a build-vector, then things are easy.
4338 EVT VT = MaskNode.getValueType();
4339 assert(VT.isVector() &&
4340 "Can't produce a non-vector with a build_vector!");
4341 if (!VT.isInteger())
4344 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4346 SmallVector<uint64_t, 32> RawMask;
4347 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4348 SDValue Op = MaskNode->getOperand(i);
4349 if (Op->getOpcode() == ISD::UNDEF) {
4350 RawMask.push_back((uint64_t)SM_SentinelUndef);
4353 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4356 APInt MaskElement = CN->getAPIntValue();
4358 // We now have to decode the element which could be any integer size and
4359 // extract each byte of it.
4360 for (int j = 0; j < NumBytesPerElement; ++j) {
4361 // Note that this is x86 and so always little endian: the low byte is
4362 // the first byte of the mask.
4363 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4364 MaskElement = MaskElement.lshr(8);
4367 DecodePSHUFBMask(RawMask, Mask);
4371 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4375 SDValue Ptr = MaskLoad->getBasePtr();
4376 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4377 Ptr->getOpcode() == X86ISD::WrapperRIP)
4378 Ptr = Ptr->getOperand(0);
4380 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4381 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4384 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4385 DecodePSHUFBMask(C, Mask);
4393 case X86ISD::VPERMI:
4394 ImmN = N->getOperand(N->getNumOperands()-1);
4395 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4400 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4402 case X86ISD::VPERM2X128:
4403 ImmN = N->getOperand(N->getNumOperands()-1);
4404 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4405 if (Mask.empty()) return false;
4407 case X86ISD::MOVSLDUP:
4408 DecodeMOVSLDUPMask(VT, Mask);
4411 case X86ISD::MOVSHDUP:
4412 DecodeMOVSHDUPMask(VT, Mask);
4415 case X86ISD::MOVDDUP:
4416 DecodeMOVDDUPMask(VT, Mask);
4419 case X86ISD::MOVLHPD:
4420 case X86ISD::MOVLPD:
4421 case X86ISD::MOVLPS:
4422 // Not yet implemented
4424 default: llvm_unreachable("unknown target shuffle node");
4427 // If we have a fake unary shuffle, the shuffle mask is spread across two
4428 // inputs that are actually the same node. Re-map the mask to always point
4429 // into the first input.
4432 if (M >= (int)Mask.size())
4438 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4439 /// element of the result of the vector shuffle.
4440 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4443 return SDValue(); // Limit search depth.
4445 SDValue V = SDValue(N, 0);
4446 EVT VT = V.getValueType();
4447 unsigned Opcode = V.getOpcode();
4449 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4450 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4451 int Elt = SV->getMaskElt(Index);
4454 return DAG.getUNDEF(VT.getVectorElementType());
4456 unsigned NumElems = VT.getVectorNumElements();
4457 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4458 : SV->getOperand(1);
4459 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4462 // Recurse into target specific vector shuffles to find scalars.
4463 if (isTargetShuffle(Opcode)) {
4464 MVT ShufVT = V.getSimpleValueType();
4465 unsigned NumElems = ShufVT.getVectorNumElements();
4466 SmallVector<int, 16> ShuffleMask;
4469 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4472 int Elt = ShuffleMask[Index];
4474 return DAG.getUNDEF(ShufVT.getVectorElementType());
4476 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4478 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4482 // Actual nodes that may contain scalar elements
4483 if (Opcode == ISD::BITCAST) {
4484 V = V.getOperand(0);
4485 EVT SrcVT = V.getValueType();
4486 unsigned NumElems = VT.getVectorNumElements();
4488 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4492 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4493 return (Index == 0) ? V.getOperand(0)
4494 : DAG.getUNDEF(VT.getVectorElementType());
4496 if (V.getOpcode() == ISD::BUILD_VECTOR)
4497 return V.getOperand(Index);
4502 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4504 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4505 unsigned NumNonZero, unsigned NumZero,
4507 const X86Subtarget* Subtarget,
4508 const TargetLowering &TLI) {
4516 // SSE4.1 - use PINSRB to insert each byte directly.
4517 if (Subtarget->hasSSE41()) {
4518 for (unsigned i = 0; i < 16; ++i) {
4519 bool isNonZero = (NonZeros & (1 << i)) != 0;
4523 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4525 V = DAG.getUNDEF(MVT::v16i8);
4528 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4529 MVT::v16i8, V, Op.getOperand(i),
4530 DAG.getIntPtrConstant(i, dl));
4537 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4538 for (unsigned i = 0; i < 16; ++i) {
4539 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4540 if (ThisIsNonZero && First) {
4542 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4544 V = DAG.getUNDEF(MVT::v8i16);
4549 SDValue ThisElt, LastElt;
4550 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4551 if (LastIsNonZero) {
4552 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4553 MVT::i16, Op.getOperand(i-1));
4555 if (ThisIsNonZero) {
4556 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4557 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4558 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4560 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4564 if (ThisElt.getNode())
4565 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4566 DAG.getIntPtrConstant(i/2, dl));
4570 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4573 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4575 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4576 unsigned NumNonZero, unsigned NumZero,
4578 const X86Subtarget* Subtarget,
4579 const TargetLowering &TLI) {
4586 for (unsigned i = 0; i < 8; ++i) {
4587 bool isNonZero = (NonZeros & (1 << i)) != 0;
4591 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4593 V = DAG.getUNDEF(MVT::v8i16);
4596 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4597 MVT::v8i16, V, Op.getOperand(i),
4598 DAG.getIntPtrConstant(i, dl));
4605 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4606 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4607 const X86Subtarget *Subtarget,
4608 const TargetLowering &TLI) {
4609 // Find all zeroable elements.
4610 std::bitset<4> Zeroable;
4611 for (int i=0; i < 4; ++i) {
4612 SDValue Elt = Op->getOperand(i);
4613 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4615 assert(Zeroable.size() - Zeroable.count() > 1 &&
4616 "We expect at least two non-zero elements!");
4618 // We only know how to deal with build_vector nodes where elements are either
4619 // zeroable or extract_vector_elt with constant index.
4620 SDValue FirstNonZero;
4621 unsigned FirstNonZeroIdx;
4622 for (unsigned i=0; i < 4; ++i) {
4625 SDValue Elt = Op->getOperand(i);
4626 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4627 !isa<ConstantSDNode>(Elt.getOperand(1)))
4629 // Make sure that this node is extracting from a 128-bit vector.
4630 MVT VT = Elt.getOperand(0).getSimpleValueType();
4631 if (!VT.is128BitVector())
4633 if (!FirstNonZero.getNode()) {
4635 FirstNonZeroIdx = i;
4639 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4640 SDValue V1 = FirstNonZero.getOperand(0);
4641 MVT VT = V1.getSimpleValueType();
4643 // See if this build_vector can be lowered as a blend with zero.
4645 unsigned EltMaskIdx, EltIdx;
4647 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4648 if (Zeroable[EltIdx]) {
4649 // The zero vector will be on the right hand side.
4650 Mask[EltIdx] = EltIdx+4;
4654 Elt = Op->getOperand(EltIdx);
4655 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4656 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4657 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4659 Mask[EltIdx] = EltIdx;
4663 // Let the shuffle legalizer deal with blend operations.
4664 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4665 if (V1.getSimpleValueType() != VT)
4666 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4667 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4670 // See if we can lower this build_vector to a INSERTPS.
4671 if (!Subtarget->hasSSE41())
4674 SDValue V2 = Elt.getOperand(0);
4675 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4678 bool CanFold = true;
4679 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4683 SDValue Current = Op->getOperand(i);
4684 SDValue SrcVector = Current->getOperand(0);
4687 CanFold = SrcVector == V1 &&
4688 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4694 assert(V1.getNode() && "Expected at least two non-zero elements!");
4695 if (V1.getSimpleValueType() != MVT::v4f32)
4696 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4697 if (V2.getSimpleValueType() != MVT::v4f32)
4698 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4700 // Ok, we can emit an INSERTPS instruction.
4701 unsigned ZMask = Zeroable.to_ulong();
4703 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4704 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4706 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4707 DAG.getIntPtrConstant(InsertPSMask, DL));
4708 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4711 /// Return a vector logical shift node.
4712 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4713 unsigned NumBits, SelectionDAG &DAG,
4714 const TargetLowering &TLI, SDLoc dl) {
4715 assert(VT.is128BitVector() && "Unknown type for VShift");
4716 MVT ShVT = MVT::v2i64;
4717 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4718 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4719 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4720 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4721 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4722 return DAG.getNode(ISD::BITCAST, dl, VT,
4723 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4727 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4729 // Check if the scalar load can be widened into a vector load. And if
4730 // the address is "base + cst" see if the cst can be "absorbed" into
4731 // the shuffle mask.
4732 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4733 SDValue Ptr = LD->getBasePtr();
4734 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4736 EVT PVT = LD->getValueType(0);
4737 if (PVT != MVT::i32 && PVT != MVT::f32)
4742 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4743 FI = FINode->getIndex();
4745 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4746 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4747 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4748 Offset = Ptr.getConstantOperandVal(1);
4749 Ptr = Ptr.getOperand(0);
4754 // FIXME: 256-bit vector instructions don't require a strict alignment,
4755 // improve this code to support it better.
4756 unsigned RequiredAlign = VT.getSizeInBits()/8;
4757 SDValue Chain = LD->getChain();
4758 // Make sure the stack object alignment is at least 16 or 32.
4759 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4760 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4761 if (MFI->isFixedObjectIndex(FI)) {
4762 // Can't change the alignment. FIXME: It's possible to compute
4763 // the exact stack offset and reference FI + adjust offset instead.
4764 // If someone *really* cares about this. That's the way to implement it.
4767 MFI->setObjectAlignment(FI, RequiredAlign);
4771 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4772 // Ptr + (Offset & ~15).
4775 if ((Offset % RequiredAlign) & 3)
4777 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4780 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4781 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4784 int EltNo = (Offset - StartOffset) >> 2;
4785 unsigned NumElems = VT.getVectorNumElements();
4787 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4788 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4789 LD->getPointerInfo().getWithOffset(StartOffset),
4790 false, false, false, 0);
4792 SmallVector<int, 8> Mask(NumElems, EltNo);
4794 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4800 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4801 /// elements can be replaced by a single large load which has the same value as
4802 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4804 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4806 /// FIXME: we'd also like to handle the case where the last elements are zero
4807 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4808 /// There's even a handy isZeroNode for that purpose.
4809 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4810 SDLoc &DL, SelectionDAG &DAG,
4811 bool isAfterLegalize) {
4812 unsigned NumElems = Elts.size();
4814 LoadSDNode *LDBase = nullptr;
4815 unsigned LastLoadedElt = -1U;
4817 // For each element in the initializer, see if we've found a load or an undef.
4818 // If we don't find an initial load element, or later load elements are
4819 // non-consecutive, bail out.
4820 for (unsigned i = 0; i < NumElems; ++i) {
4821 SDValue Elt = Elts[i];
4822 // Look through a bitcast.
4823 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4824 Elt = Elt.getOperand(0);
4825 if (!Elt.getNode() ||
4826 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4829 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4831 LDBase = cast<LoadSDNode>(Elt.getNode());
4835 if (Elt.getOpcode() == ISD::UNDEF)
4838 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4839 EVT LdVT = Elt.getValueType();
4840 // Each loaded element must be the correct fractional portion of the
4841 // requested vector load.
4842 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4844 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4849 // If we have found an entire vector of loads and undefs, then return a large
4850 // load of the entire vector width starting at the base pointer. If we found
4851 // consecutive loads for the low half, generate a vzext_load node.
4852 if (LastLoadedElt == NumElems - 1) {
4853 assert(LDBase && "Did not find base load for merging consecutive loads");
4854 EVT EltVT = LDBase->getValueType(0);
4855 // Ensure that the input vector size for the merged loads matches the
4856 // cumulative size of the input elements.
4857 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4860 if (isAfterLegalize &&
4861 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4864 SDValue NewLd = SDValue();
4866 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4867 LDBase->getPointerInfo(), LDBase->isVolatile(),
4868 LDBase->isNonTemporal(), LDBase->isInvariant(),
4869 LDBase->getAlignment());
4871 if (LDBase->hasAnyUseOfValue(1)) {
4872 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4874 SDValue(NewLd.getNode(), 1));
4875 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4876 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4877 SDValue(NewLd.getNode(), 1));
4883 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4884 //of a v4i32 / v4f32. It's probably worth generalizing.
4885 EVT EltVT = VT.getVectorElementType();
4886 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4887 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4888 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4889 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4891 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4892 LDBase->getPointerInfo(),
4893 LDBase->getAlignment(),
4894 false/*isVolatile*/, true/*ReadMem*/,
4897 // Make sure the newly-created LOAD is in the same position as LDBase in
4898 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4899 // update uses of LDBase's output chain to use the TokenFactor.
4900 if (LDBase->hasAnyUseOfValue(1)) {
4901 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4902 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4903 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4904 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4905 SDValue(ResNode.getNode(), 1));
4908 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4913 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4914 /// to generate a splat value for the following cases:
4915 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4916 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4917 /// a scalar load, or a constant.
4918 /// The VBROADCAST node is returned when a pattern is found,
4919 /// or SDValue() otherwise.
4920 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4921 SelectionDAG &DAG) {
4922 // VBROADCAST requires AVX.
4923 // TODO: Splats could be generated for non-AVX CPUs using SSE
4924 // instructions, but there's less potential gain for only 128-bit vectors.
4925 if (!Subtarget->hasAVX())
4928 MVT VT = Op.getSimpleValueType();
4931 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4932 "Unsupported vector type for broadcast.");
4937 switch (Op.getOpcode()) {
4939 // Unknown pattern found.
4942 case ISD::BUILD_VECTOR: {
4943 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4944 BitVector UndefElements;
4945 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4947 // We need a splat of a single value to use broadcast, and it doesn't
4948 // make any sense if the value is only in one element of the vector.
4949 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4953 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4954 Ld.getOpcode() == ISD::ConstantFP);
4956 // Make sure that all of the users of a non-constant load are from the
4957 // BUILD_VECTOR node.
4958 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4963 case ISD::VECTOR_SHUFFLE: {
4964 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4966 // Shuffles must have a splat mask where the first element is
4968 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4971 SDValue Sc = Op.getOperand(0);
4972 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4973 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4975 if (!Subtarget->hasInt256())
4978 // Use the register form of the broadcast instruction available on AVX2.
4979 if (VT.getSizeInBits() >= 256)
4980 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4981 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4984 Ld = Sc.getOperand(0);
4985 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4986 Ld.getOpcode() == ISD::ConstantFP);
4988 // The scalar_to_vector node and the suspected
4989 // load node must have exactly one user.
4990 // Constants may have multiple users.
4992 // AVX-512 has register version of the broadcast
4993 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4994 Ld.getValueType().getSizeInBits() >= 32;
4995 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5002 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5003 bool IsGE256 = (VT.getSizeInBits() >= 256);
5005 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5006 // instruction to save 8 or more bytes of constant pool data.
5007 // TODO: If multiple splats are generated to load the same constant,
5008 // it may be detrimental to overall size. There needs to be a way to detect
5009 // that condition to know if this is truly a size win.
5010 const Function *F = DAG.getMachineFunction().getFunction();
5011 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5013 // Handle broadcasting a single constant scalar from the constant pool
5015 // On Sandybridge (no AVX2), it is still better to load a constant vector
5016 // from the constant pool and not to broadcast it from a scalar.
5017 // But override that restriction when optimizing for size.
5018 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5019 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5020 EVT CVT = Ld.getValueType();
5021 assert(!CVT.isVector() && "Must not broadcast a vector type");
5023 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5024 // For size optimization, also splat v2f64 and v2i64, and for size opt
5025 // with AVX2, also splat i8 and i16.
5026 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5027 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5028 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5029 const Constant *C = nullptr;
5030 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5031 C = CI->getConstantIntValue();
5032 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5033 C = CF->getConstantFPValue();
5035 assert(C && "Invalid constant type");
5037 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5038 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5039 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5040 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5041 MachinePointerInfo::getConstantPool(),
5042 false, false, false, Alignment);
5044 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5048 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5050 // Handle AVX2 in-register broadcasts.
5051 if (!IsLoad && Subtarget->hasInt256() &&
5052 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5053 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5055 // The scalar source must be a normal load.
5059 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5060 (Subtarget->hasVLX() && ScalarSize == 64))
5061 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5063 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5064 // double since there is no vbroadcastsd xmm
5065 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5066 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5067 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5070 // Unsupported broadcast.
5074 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5075 /// underlying vector and index.
5077 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5079 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5081 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5082 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5085 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5087 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5089 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5090 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5093 // In this case the vector is the extract_subvector expression and the index
5094 // is 2, as specified by the shuffle.
5095 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5096 SDValue ShuffleVec = SVOp->getOperand(0);
5097 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5098 assert(ShuffleVecVT.getVectorElementType() ==
5099 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5101 int ShuffleIdx = SVOp->getMaskElt(Idx);
5102 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5103 ExtractedFromVec = ShuffleVec;
5109 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5110 MVT VT = Op.getSimpleValueType();
5112 // Skip if insert_vec_elt is not supported.
5113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5114 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5118 unsigned NumElems = Op.getNumOperands();
5122 SmallVector<unsigned, 4> InsertIndices;
5123 SmallVector<int, 8> Mask(NumElems, -1);
5125 for (unsigned i = 0; i != NumElems; ++i) {
5126 unsigned Opc = Op.getOperand(i).getOpcode();
5128 if (Opc == ISD::UNDEF)
5131 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5132 // Quit if more than 1 elements need inserting.
5133 if (InsertIndices.size() > 1)
5136 InsertIndices.push_back(i);
5140 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5141 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5142 // Quit if non-constant index.
5143 if (!isa<ConstantSDNode>(ExtIdx))
5145 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5147 // Quit if extracted from vector of different type.
5148 if (ExtractedFromVec.getValueType() != VT)
5151 if (!VecIn1.getNode())
5152 VecIn1 = ExtractedFromVec;
5153 else if (VecIn1 != ExtractedFromVec) {
5154 if (!VecIn2.getNode())
5155 VecIn2 = ExtractedFromVec;
5156 else if (VecIn2 != ExtractedFromVec)
5157 // Quit if more than 2 vectors to shuffle
5161 if (ExtractedFromVec == VecIn1)
5163 else if (ExtractedFromVec == VecIn2)
5164 Mask[i] = Idx + NumElems;
5167 if (!VecIn1.getNode())
5170 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5171 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5172 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5173 unsigned Idx = InsertIndices[i];
5174 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5175 DAG.getIntPtrConstant(Idx, DL));
5181 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5183 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5185 MVT VT = Op.getSimpleValueType();
5186 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5187 "Unexpected type in LowerBUILD_VECTORvXi1!");
5190 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5191 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5192 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5193 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5196 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5197 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5198 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5199 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5202 bool AllContants = true;
5203 uint64_t Immediate = 0;
5204 int NonConstIdx = -1;
5205 bool IsSplat = true;
5206 unsigned NumNonConsts = 0;
5207 unsigned NumConsts = 0;
5208 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5209 SDValue In = Op.getOperand(idx);
5210 if (In.getOpcode() == ISD::UNDEF)
5212 if (!isa<ConstantSDNode>(In)) {
5213 AllContants = false;
5218 if (cast<ConstantSDNode>(In)->getZExtValue())
5219 Immediate |= (1ULL << idx);
5221 if (In != Op.getOperand(0))
5226 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5227 DAG.getConstant(Immediate, dl, MVT::i16));
5228 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5229 DAG.getIntPtrConstant(0, dl));
5232 if (NumNonConsts == 1 && NonConstIdx != 0) {
5235 SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5236 MVT::getIntegerVT(VT.getSizeInBits()));
5237 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5240 DstVec = DAG.getUNDEF(VT);
5241 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5242 Op.getOperand(NonConstIdx),
5243 DAG.getIntPtrConstant(NonConstIdx, dl));
5245 if (!IsSplat && (NonConstIdx != 0))
5246 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5247 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5250 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5251 DAG.getConstant(-1, dl, SelectVT),
5252 DAG.getConstant(0, dl, SelectVT));
5254 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5255 DAG.getConstant((Immediate | 1), dl, SelectVT),
5256 DAG.getConstant(Immediate, dl, SelectVT));
5257 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5260 /// \brief Return true if \p N implements a horizontal binop and return the
5261 /// operands for the horizontal binop into V0 and V1.
5263 /// This is a helper function of LowerToHorizontalOp().
5264 /// This function checks that the build_vector \p N in input implements a
5265 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5266 /// operation to match.
5267 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5268 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5269 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5272 /// This function only analyzes elements of \p N whose indices are
5273 /// in range [BaseIdx, LastIdx).
5274 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5276 unsigned BaseIdx, unsigned LastIdx,
5277 SDValue &V0, SDValue &V1) {
5278 EVT VT = N->getValueType(0);
5280 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5281 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5282 "Invalid Vector in input!");
5284 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5285 bool CanFold = true;
5286 unsigned ExpectedVExtractIdx = BaseIdx;
5287 unsigned NumElts = LastIdx - BaseIdx;
5288 V0 = DAG.getUNDEF(VT);
5289 V1 = DAG.getUNDEF(VT);
5291 // Check if N implements a horizontal binop.
5292 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5293 SDValue Op = N->getOperand(i + BaseIdx);
5296 if (Op->getOpcode() == ISD::UNDEF) {
5297 // Update the expected vector extract index.
5298 if (i * 2 == NumElts)
5299 ExpectedVExtractIdx = BaseIdx;
5300 ExpectedVExtractIdx += 2;
5304 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5309 SDValue Op0 = Op.getOperand(0);
5310 SDValue Op1 = Op.getOperand(1);
5312 // Try to match the following pattern:
5313 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5314 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5315 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5316 Op0.getOperand(0) == Op1.getOperand(0) &&
5317 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5318 isa<ConstantSDNode>(Op1.getOperand(1)));
5322 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5323 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5325 if (i * 2 < NumElts) {
5326 if (V0.getOpcode() == ISD::UNDEF) {
5327 V0 = Op0.getOperand(0);
5328 if (V0.getValueType() != VT)
5332 if (V1.getOpcode() == ISD::UNDEF) {
5333 V1 = Op0.getOperand(0);
5334 if (V1.getValueType() != VT)
5337 if (i * 2 == NumElts)
5338 ExpectedVExtractIdx = BaseIdx;
5341 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5342 if (I0 == ExpectedVExtractIdx)
5343 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5344 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5345 // Try to match the following dag sequence:
5346 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5347 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5351 ExpectedVExtractIdx += 2;
5357 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5358 /// a concat_vector.
5360 /// This is a helper function of LowerToHorizontalOp().
5361 /// This function expects two 256-bit vectors called V0 and V1.
5362 /// At first, each vector is split into two separate 128-bit vectors.
5363 /// Then, the resulting 128-bit vectors are used to implement two
5364 /// horizontal binary operations.
5366 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5368 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5369 /// the two new horizontal binop.
5370 /// When Mode is set, the first horizontal binop dag node would take as input
5371 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5372 /// horizontal binop dag node would take as input the lower 128-bit of V1
5373 /// and the upper 128-bit of V1.
5375 /// HADD V0_LO, V0_HI
5376 /// HADD V1_LO, V1_HI
5378 /// Otherwise, the first horizontal binop dag node takes as input the lower
5379 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5380 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5382 /// HADD V0_LO, V1_LO
5383 /// HADD V0_HI, V1_HI
5385 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5386 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5387 /// the upper 128-bits of the result.
5388 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5389 SDLoc DL, SelectionDAG &DAG,
5390 unsigned X86Opcode, bool Mode,
5391 bool isUndefLO, bool isUndefHI) {
5392 EVT VT = V0.getValueType();
5393 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5394 "Invalid nodes in input!");
5396 unsigned NumElts = VT.getVectorNumElements();
5397 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5398 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5399 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5400 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5401 EVT NewVT = V0_LO.getValueType();
5403 SDValue LO = DAG.getUNDEF(NewVT);
5404 SDValue HI = DAG.getUNDEF(NewVT);
5407 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5408 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5409 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5410 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5411 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5413 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5414 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5415 V1_LO->getOpcode() != ISD::UNDEF))
5416 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5418 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5419 V1_HI->getOpcode() != ISD::UNDEF))
5420 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5423 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5426 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5428 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5429 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5430 EVT VT = BV->getValueType(0);
5431 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5432 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5436 unsigned NumElts = VT.getVectorNumElements();
5437 SDValue InVec0 = DAG.getUNDEF(VT);
5438 SDValue InVec1 = DAG.getUNDEF(VT);
5440 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5441 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5443 // Odd-numbered elements in the input build vector are obtained from
5444 // adding two integer/float elements.
5445 // Even-numbered elements in the input build vector are obtained from
5446 // subtracting two integer/float elements.
5447 unsigned ExpectedOpcode = ISD::FSUB;
5448 unsigned NextExpectedOpcode = ISD::FADD;
5449 bool AddFound = false;
5450 bool SubFound = false;
5452 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5453 SDValue Op = BV->getOperand(i);
5455 // Skip 'undef' values.
5456 unsigned Opcode = Op.getOpcode();
5457 if (Opcode == ISD::UNDEF) {
5458 std::swap(ExpectedOpcode, NextExpectedOpcode);
5462 // Early exit if we found an unexpected opcode.
5463 if (Opcode != ExpectedOpcode)
5466 SDValue Op0 = Op.getOperand(0);
5467 SDValue Op1 = Op.getOperand(1);
5469 // Try to match the following pattern:
5470 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5471 // Early exit if we cannot match that sequence.
5472 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5473 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5474 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5475 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5476 Op0.getOperand(1) != Op1.getOperand(1))
5479 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5483 // We found a valid add/sub node. Update the information accordingly.
5489 // Update InVec0 and InVec1.
5490 if (InVec0.getOpcode() == ISD::UNDEF) {
5491 InVec0 = Op0.getOperand(0);
5492 if (InVec0.getValueType() != VT)
5495 if (InVec1.getOpcode() == ISD::UNDEF) {
5496 InVec1 = Op1.getOperand(0);
5497 if (InVec1.getValueType() != VT)
5501 // Make sure that operands in input to each add/sub node always
5502 // come from a same pair of vectors.
5503 if (InVec0 != Op0.getOperand(0)) {
5504 if (ExpectedOpcode == ISD::FSUB)
5507 // FADD is commutable. Try to commute the operands
5508 // and then test again.
5509 std::swap(Op0, Op1);
5510 if (InVec0 != Op0.getOperand(0))
5514 if (InVec1 != Op1.getOperand(0))
5517 // Update the pair of expected opcodes.
5518 std::swap(ExpectedOpcode, NextExpectedOpcode);
5521 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5522 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5523 InVec1.getOpcode() != ISD::UNDEF)
5524 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5529 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5530 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5531 const X86Subtarget *Subtarget,
5532 SelectionDAG &DAG) {
5533 EVT VT = BV->getValueType(0);
5534 unsigned NumElts = VT.getVectorNumElements();
5535 unsigned NumUndefsLO = 0;
5536 unsigned NumUndefsHI = 0;
5537 unsigned Half = NumElts/2;
5539 // Count the number of UNDEF operands in the build_vector in input.
5540 for (unsigned i = 0, e = Half; i != e; ++i)
5541 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5544 for (unsigned i = Half, e = NumElts; i != e; ++i)
5545 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5548 // Early exit if this is either a build_vector of all UNDEFs or all the
5549 // operands but one are UNDEF.
5550 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5554 SDValue InVec0, InVec1;
5555 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5556 // Try to match an SSE3 float HADD/HSUB.
5557 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5558 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5560 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5561 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5562 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5563 // Try to match an SSSE3 integer HADD/HSUB.
5564 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5565 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5567 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5568 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5571 if (!Subtarget->hasAVX())
5574 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5575 // Try to match an AVX horizontal add/sub of packed single/double
5576 // precision floating point values from 256-bit vectors.
5577 SDValue InVec2, InVec3;
5578 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5579 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5580 ((InVec0.getOpcode() == ISD::UNDEF ||
5581 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5582 ((InVec1.getOpcode() == ISD::UNDEF ||
5583 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5584 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5586 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5587 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5588 ((InVec0.getOpcode() == ISD::UNDEF ||
5589 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5590 ((InVec1.getOpcode() == ISD::UNDEF ||
5591 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5592 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5593 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5594 // Try to match an AVX2 horizontal add/sub of signed integers.
5595 SDValue InVec2, InVec3;
5597 bool CanFold = true;
5599 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5600 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5601 ((InVec0.getOpcode() == ISD::UNDEF ||
5602 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5603 ((InVec1.getOpcode() == ISD::UNDEF ||
5604 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5605 X86Opcode = X86ISD::HADD;
5606 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5607 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5608 ((InVec0.getOpcode() == ISD::UNDEF ||
5609 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5610 ((InVec1.getOpcode() == ISD::UNDEF ||
5611 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5612 X86Opcode = X86ISD::HSUB;
5617 // Fold this build_vector into a single horizontal add/sub.
5618 // Do this only if the target has AVX2.
5619 if (Subtarget->hasAVX2())
5620 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5622 // Do not try to expand this build_vector into a pair of horizontal
5623 // add/sub if we can emit a pair of scalar add/sub.
5624 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5627 // Convert this build_vector into a pair of horizontal binop followed by
5629 bool isUndefLO = NumUndefsLO == Half;
5630 bool isUndefHI = NumUndefsHI == Half;
5631 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5632 isUndefLO, isUndefHI);
5636 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5637 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5639 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5640 X86Opcode = X86ISD::HADD;
5641 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5642 X86Opcode = X86ISD::HSUB;
5643 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5644 X86Opcode = X86ISD::FHADD;
5645 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5646 X86Opcode = X86ISD::FHSUB;
5650 // Don't try to expand this build_vector into a pair of horizontal add/sub
5651 // if we can simply emit a pair of scalar add/sub.
5652 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5655 // Convert this build_vector into two horizontal add/sub followed by
5657 bool isUndefLO = NumUndefsLO == Half;
5658 bool isUndefHI = NumUndefsHI == Half;
5659 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5660 isUndefLO, isUndefHI);
5667 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5670 MVT VT = Op.getSimpleValueType();
5671 MVT ExtVT = VT.getVectorElementType();
5672 unsigned NumElems = Op.getNumOperands();
5674 // Generate vectors for predicate vectors.
5675 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5676 return LowerBUILD_VECTORvXi1(Op, DAG);
5678 // Vectors containing all zeros can be matched by pxor and xorps later
5679 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5680 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5681 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5682 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5685 return getZeroVector(VT, Subtarget, DAG, dl);
5688 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5689 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5690 // vpcmpeqd on 256-bit vectors.
5691 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5692 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5695 if (!VT.is512BitVector())
5696 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5699 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5700 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5702 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5703 return HorizontalOp;
5704 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5707 unsigned EVTBits = ExtVT.getSizeInBits();
5709 unsigned NumZero = 0;
5710 unsigned NumNonZero = 0;
5711 unsigned NonZeros = 0;
5712 bool IsAllConstants = true;
5713 SmallSet<SDValue, 8> Values;
5714 for (unsigned i = 0; i < NumElems; ++i) {
5715 SDValue Elt = Op.getOperand(i);
5716 if (Elt.getOpcode() == ISD::UNDEF)
5719 if (Elt.getOpcode() != ISD::Constant &&
5720 Elt.getOpcode() != ISD::ConstantFP)
5721 IsAllConstants = false;
5722 if (X86::isZeroNode(Elt))
5725 NonZeros |= (1 << i);
5730 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5731 if (NumNonZero == 0)
5732 return DAG.getUNDEF(VT);
5734 // Special case for single non-zero, non-undef, element.
5735 if (NumNonZero == 1) {
5736 unsigned Idx = countTrailingZeros(NonZeros);
5737 SDValue Item = Op.getOperand(Idx);
5739 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5740 // the value are obviously zero, truncate the value to i32 and do the
5741 // insertion that way. Only do this if the value is non-constant or if the
5742 // value is a constant being inserted into element 0. It is cheaper to do
5743 // a constant pool load than it is to do a movd + shuffle.
5744 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5745 (!IsAllConstants || Idx == 0)) {
5746 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5748 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5749 EVT VecVT = MVT::v4i32;
5751 // Truncate the value (which may itself be a constant) to i32, and
5752 // convert it to a vector with movd (S2V+shuffle to zero extend).
5753 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5754 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5756 ISD::BITCAST, dl, VT,
5757 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5761 // If we have a constant or non-constant insertion into the low element of
5762 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5763 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5764 // depending on what the source datatype is.
5767 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5769 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5770 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5771 if (VT.is512BitVector()) {
5772 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5773 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5774 Item, DAG.getIntPtrConstant(0, dl));
5776 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5777 "Expected an SSE value type!");
5778 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5779 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5780 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5783 // We can't directly insert an i8 or i16 into a vector, so zero extend
5785 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5786 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5787 if (VT.is256BitVector()) {
5788 if (Subtarget->hasAVX()) {
5789 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5790 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5792 // Without AVX, we need to extend to a 128-bit vector and then
5793 // insert into the 256-bit vector.
5794 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5795 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5796 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5799 assert(VT.is128BitVector() && "Expected an SSE value type!");
5800 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5801 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5803 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5807 // Is it a vector logical left shift?
5808 if (NumElems == 2 && Idx == 1 &&
5809 X86::isZeroNode(Op.getOperand(0)) &&
5810 !X86::isZeroNode(Op.getOperand(1))) {
5811 unsigned NumBits = VT.getSizeInBits();
5812 return getVShift(true, VT,
5813 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5814 VT, Op.getOperand(1)),
5815 NumBits/2, DAG, *this, dl);
5818 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5821 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5822 // is a non-constant being inserted into an element other than the low one,
5823 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5824 // movd/movss) to move this into the low element, then shuffle it into
5826 if (EVTBits == 32) {
5827 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5828 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5832 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5833 if (Values.size() == 1) {
5834 if (EVTBits == 32) {
5835 // Instead of a shuffle like this:
5836 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5837 // Check if it's possible to issue this instead.
5838 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5839 unsigned Idx = countTrailingZeros(NonZeros);
5840 SDValue Item = Op.getOperand(Idx);
5841 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5842 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5847 // A vector full of immediates; various special cases are already
5848 // handled, so this is best done with a single constant-pool load.
5852 // For AVX-length vectors, see if we can use a vector load to get all of the
5853 // elements, otherwise build the individual 128-bit pieces and use
5854 // shuffles to put them in place.
5855 if (VT.is256BitVector() || VT.is512BitVector()) {
5856 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5858 // Check for a build vector of consecutive loads.
5859 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5862 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5864 // Build both the lower and upper subvector.
5865 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5866 makeArrayRef(&V[0], NumElems/2));
5867 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5868 makeArrayRef(&V[NumElems / 2], NumElems/2));
5870 // Recreate the wider vector with the lower and upper part.
5871 if (VT.is256BitVector())
5872 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5873 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5876 // Let legalizer expand 2-wide build_vectors.
5877 if (EVTBits == 64) {
5878 if (NumNonZero == 1) {
5879 // One half is zero or undef.
5880 unsigned Idx = countTrailingZeros(NonZeros);
5881 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5882 Op.getOperand(Idx));
5883 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5888 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5889 if (EVTBits == 8 && NumElems == 16)
5890 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5894 if (EVTBits == 16 && NumElems == 8)
5895 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5899 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5900 if (EVTBits == 32 && NumElems == 4)
5901 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5904 // If element VT is == 32 bits, turn it into a number of shuffles.
5905 SmallVector<SDValue, 8> V(NumElems);
5906 if (NumElems == 4 && NumZero > 0) {
5907 for (unsigned i = 0; i < 4; ++i) {
5908 bool isZero = !(NonZeros & (1 << i));
5910 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5912 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5915 for (unsigned i = 0; i < 2; ++i) {
5916 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5919 V[i] = V[i*2]; // Must be a zero vector.
5922 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5925 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5928 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5933 bool Reverse1 = (NonZeros & 0x3) == 2;
5934 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5938 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5939 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5941 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5944 if (Values.size() > 1 && VT.is128BitVector()) {
5945 // Check for a build vector of consecutive loads.
5946 for (unsigned i = 0; i < NumElems; ++i)
5947 V[i] = Op.getOperand(i);
5949 // Check for elements which are consecutive loads.
5950 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5953 // Check for a build vector from mostly shuffle plus few inserting.
5954 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5957 // For SSE 4.1, use insertps to put the high elements into the low element.
5958 if (Subtarget->hasSSE41()) {
5960 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5961 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5963 Result = DAG.getUNDEF(VT);
5965 for (unsigned i = 1; i < NumElems; ++i) {
5966 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5967 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5968 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5973 // Otherwise, expand into a number of unpckl*, start by extending each of
5974 // our (non-undef) elements to the full vector width with the element in the
5975 // bottom slot of the vector (which generates no code for SSE).
5976 for (unsigned i = 0; i < NumElems; ++i) {
5977 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5978 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5980 V[i] = DAG.getUNDEF(VT);
5983 // Next, we iteratively mix elements, e.g. for v4f32:
5984 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5985 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5986 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5987 unsigned EltStride = NumElems >> 1;
5988 while (EltStride != 0) {
5989 for (unsigned i = 0; i < EltStride; ++i) {
5990 // If V[i+EltStride] is undef and this is the first round of mixing,
5991 // then it is safe to just drop this shuffle: V[i] is already in the
5992 // right place, the one element (since it's the first round) being
5993 // inserted as undef can be dropped. This isn't safe for successive
5994 // rounds because they will permute elements within both vectors.
5995 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5996 EltStride == NumElems/2)
5999 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6008 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6009 // to create 256-bit vectors from two other 128-bit ones.
6010 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6012 MVT ResVT = Op.getSimpleValueType();
6014 assert((ResVT.is256BitVector() ||
6015 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6017 SDValue V1 = Op.getOperand(0);
6018 SDValue V2 = Op.getOperand(1);
6019 unsigned NumElems = ResVT.getVectorNumElements();
6020 if (ResVT.is256BitVector())
6021 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6023 if (Op.getNumOperands() == 4) {
6024 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6025 ResVT.getVectorNumElements()/2);
6026 SDValue V3 = Op.getOperand(2);
6027 SDValue V4 = Op.getOperand(3);
6028 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6029 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6031 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6034 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6035 const X86Subtarget *Subtarget,
6036 SelectionDAG & DAG) {
6038 MVT ResVT = Op.getSimpleValueType();
6039 unsigned NumOfOperands = Op.getNumOperands();
6041 assert(isPowerOf2_32(NumOfOperands) &&
6042 "Unexpected number of operands in CONCAT_VECTORS");
6044 if (NumOfOperands > 2) {
6045 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6046 ResVT.getVectorNumElements()/2);
6047 SmallVector<SDValue, 2> Ops;
6048 for (unsigned i = 0; i < NumOfOperands/2; i++)
6049 Ops.push_back(Op.getOperand(i));
6050 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6052 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6053 Ops.push_back(Op.getOperand(i));
6054 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6055 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6058 SDValue V1 = Op.getOperand(0);
6059 SDValue V2 = Op.getOperand(1);
6060 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6061 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6063 if (IsZeroV1 && IsZeroV2)
6064 return getZeroVector(ResVT, Subtarget, DAG, dl);
6066 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6067 SDValue Undef = DAG.getUNDEF(ResVT);
6068 unsigned NumElems = ResVT.getVectorNumElements();
6069 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6071 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6072 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6076 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6077 // Zero the upper bits of V1
6078 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6079 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6082 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6085 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6086 const X86Subtarget *Subtarget,
6087 SelectionDAG &DAG) {
6088 MVT VT = Op.getSimpleValueType();
6089 if (VT.getVectorElementType() == MVT::i1)
6090 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6092 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6093 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6094 Op.getNumOperands() == 4)));
6096 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6097 // from two other 128-bit ones.
6099 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6100 return LowerAVXCONCAT_VECTORS(Op, DAG);
6104 //===----------------------------------------------------------------------===//
6105 // Vector shuffle lowering
6107 // This is an experimental code path for lowering vector shuffles on x86. It is
6108 // designed to handle arbitrary vector shuffles and blends, gracefully
6109 // degrading performance as necessary. It works hard to recognize idiomatic
6110 // shuffles and lower them to optimal instruction patterns without leaving
6111 // a framework that allows reasonably efficient handling of all vector shuffle
6113 //===----------------------------------------------------------------------===//
6115 /// \brief Tiny helper function to identify a no-op mask.
6117 /// This is a somewhat boring predicate function. It checks whether the mask
6118 /// array input, which is assumed to be a single-input shuffle mask of the kind
6119 /// used by the X86 shuffle instructions (not a fully general
6120 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6121 /// in-place shuffle are 'no-op's.
6122 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6123 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6124 if (Mask[i] != -1 && Mask[i] != i)
6129 /// \brief Helper function to classify a mask as a single-input mask.
6131 /// This isn't a generic single-input test because in the vector shuffle
6132 /// lowering we canonicalize single inputs to be the first input operand. This
6133 /// means we can more quickly test for a single input by only checking whether
6134 /// an input from the second operand exists. We also assume that the size of
6135 /// mask corresponds to the size of the input vectors which isn't true in the
6136 /// fully general case.
6137 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6139 if (M >= (int)Mask.size())
6144 /// \brief Test whether there are elements crossing 128-bit lanes in this
6147 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6148 /// and we routinely test for these.
6149 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6150 int LaneSize = 128 / VT.getScalarSizeInBits();
6151 int Size = Mask.size();
6152 for (int i = 0; i < Size; ++i)
6153 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6158 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6160 /// This checks a shuffle mask to see if it is performing the same
6161 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6162 /// that it is also not lane-crossing. It may however involve a blend from the
6163 /// same lane of a second vector.
6165 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6166 /// non-trivial to compute in the face of undef lanes. The representation is
6167 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6168 /// entries from both V1 and V2 inputs to the wider mask.
6170 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6171 SmallVectorImpl<int> &RepeatedMask) {
6172 int LaneSize = 128 / VT.getScalarSizeInBits();
6173 RepeatedMask.resize(LaneSize, -1);
6174 int Size = Mask.size();
6175 for (int i = 0; i < Size; ++i) {
6178 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6179 // This entry crosses lanes, so there is no way to model this shuffle.
6182 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6183 if (RepeatedMask[i % LaneSize] == -1)
6184 // This is the first non-undef entry in this slot of a 128-bit lane.
6185 RepeatedMask[i % LaneSize] =
6186 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6187 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6188 // Found a mismatch with the repeated mask.
6194 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6197 /// This is a fast way to test a shuffle mask against a fixed pattern:
6199 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6201 /// It returns true if the mask is exactly as wide as the argument list, and
6202 /// each element of the mask is either -1 (signifying undef) or the value given
6203 /// in the argument.
6204 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6205 ArrayRef<int> ExpectedMask) {
6206 if (Mask.size() != ExpectedMask.size())
6209 int Size = Mask.size();
6211 // If the values are build vectors, we can look through them to find
6212 // equivalent inputs that make the shuffles equivalent.
6213 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6214 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6216 for (int i = 0; i < Size; ++i)
6217 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6218 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6219 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6220 if (!MaskBV || !ExpectedBV ||
6221 MaskBV->getOperand(Mask[i] % Size) !=
6222 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6229 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6231 /// This helper function produces an 8-bit shuffle immediate corresponding to
6232 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6233 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6236 /// NB: We rely heavily on "undef" masks preserving the input lane.
6237 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6238 SelectionDAG &DAG) {
6239 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6240 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6241 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6242 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6243 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6246 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6247 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6248 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6249 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6250 return DAG.getConstant(Imm, DL, MVT::i8);
6253 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6255 /// This is used as a fallback approach when first class blend instructions are
6256 /// unavailable. Currently it is only suitable for integer vectors, but could
6257 /// be generalized for floating point vectors if desirable.
6258 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6259 SDValue V2, ArrayRef<int> Mask,
6260 SelectionDAG &DAG) {
6261 assert(VT.isInteger() && "Only supports integer vector types!");
6262 MVT EltVT = VT.getScalarType();
6263 int NumEltBits = EltVT.getSizeInBits();
6264 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6265 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6267 SmallVector<SDValue, 16> MaskOps;
6268 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6269 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6270 return SDValue(); // Shuffled input!
6271 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6274 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6275 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6276 // We have to cast V2 around.
6277 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6278 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6279 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6280 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6281 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6282 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6285 /// \brief Try to emit a blend instruction for a shuffle.
6287 /// This doesn't do any checks for the availability of instructions for blending
6288 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6289 /// be matched in the backend with the type given. What it does check for is
6290 /// that the shuffle mask is in fact a blend.
6291 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6292 SDValue V2, ArrayRef<int> Mask,
6293 const X86Subtarget *Subtarget,
6294 SelectionDAG &DAG) {
6295 unsigned BlendMask = 0;
6296 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6297 if (Mask[i] >= Size) {
6298 if (Mask[i] != i + Size)
6299 return SDValue(); // Shuffled V2 input!
6300 BlendMask |= 1u << i;
6303 if (Mask[i] >= 0 && Mask[i] != i)
6304 return SDValue(); // Shuffled V1 input!
6306 switch (VT.SimpleTy) {
6311 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6312 DAG.getConstant(BlendMask, DL, MVT::i8));
6316 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6320 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6321 // that instruction.
6322 if (Subtarget->hasAVX2()) {
6323 // Scale the blend by the number of 32-bit dwords per element.
6324 int Scale = VT.getScalarSizeInBits() / 32;
6326 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6327 if (Mask[i] >= Size)
6328 for (int j = 0; j < Scale; ++j)
6329 BlendMask |= 1u << (i * Scale + j);
6331 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6332 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6333 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6334 return DAG.getNode(ISD::BITCAST, DL, VT,
6335 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6336 DAG.getConstant(BlendMask, DL, MVT::i8)));
6340 // For integer shuffles we need to expand the mask and cast the inputs to
6341 // v8i16s prior to blending.
6342 int Scale = 8 / VT.getVectorNumElements();
6344 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6345 if (Mask[i] >= Size)
6346 for (int j = 0; j < Scale; ++j)
6347 BlendMask |= 1u << (i * Scale + j);
6349 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6350 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6351 return DAG.getNode(ISD::BITCAST, DL, VT,
6352 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6353 DAG.getConstant(BlendMask, DL, MVT::i8)));
6357 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6358 SmallVector<int, 8> RepeatedMask;
6359 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6360 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6361 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6363 for (int i = 0; i < 8; ++i)
6364 if (RepeatedMask[i] >= 16)
6365 BlendMask |= 1u << i;
6366 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6367 DAG.getConstant(BlendMask, DL, MVT::i8));
6373 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6374 "256-bit byte-blends require AVX2 support!");
6376 // Scale the blend by the number of bytes per element.
6377 int Scale = VT.getScalarSizeInBits() / 8;
6379 // This form of blend is always done on bytes. Compute the byte vector
6381 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6383 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6384 // mix of LLVM's code generator and the x86 backend. We tell the code
6385 // generator that boolean values in the elements of an x86 vector register
6386 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6387 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6388 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6389 // of the element (the remaining are ignored) and 0 in that high bit would
6390 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6391 // the LLVM model for boolean values in vector elements gets the relevant
6392 // bit set, it is set backwards and over constrained relative to x86's
6394 SmallVector<SDValue, 32> VSELECTMask;
6395 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6396 for (int j = 0; j < Scale; ++j)
6397 VSELECTMask.push_back(
6398 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6399 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6402 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6403 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6405 ISD::BITCAST, DL, VT,
6406 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6407 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6412 llvm_unreachable("Not a supported integer vector type!");
6416 /// \brief Try to lower as a blend of elements from two inputs followed by
6417 /// a single-input permutation.
6419 /// This matches the pattern where we can blend elements from two inputs and
6420 /// then reduce the shuffle to a single-input permutation.
6421 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6424 SelectionDAG &DAG) {
6425 // We build up the blend mask while checking whether a blend is a viable way
6426 // to reduce the shuffle.
6427 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6428 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6430 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6434 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6436 if (BlendMask[Mask[i] % Size] == -1)
6437 BlendMask[Mask[i] % Size] = Mask[i];
6438 else if (BlendMask[Mask[i] % Size] != Mask[i])
6439 return SDValue(); // Can't blend in the needed input!
6441 PermuteMask[i] = Mask[i] % Size;
6444 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6445 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6448 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6449 /// blends and permutes.
6451 /// This matches the extremely common pattern for handling combined
6452 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6453 /// operations. It will try to pick the best arrangement of shuffles and
6455 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6459 SelectionDAG &DAG) {
6460 // Shuffle the input elements into the desired positions in V1 and V2 and
6461 // blend them together.
6462 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6463 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6464 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6465 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6466 if (Mask[i] >= 0 && Mask[i] < Size) {
6467 V1Mask[i] = Mask[i];
6469 } else if (Mask[i] >= Size) {
6470 V2Mask[i] = Mask[i] - Size;
6471 BlendMask[i] = i + Size;
6474 // Try to lower with the simpler initial blend strategy unless one of the
6475 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6476 // shuffle may be able to fold with a load or other benefit. However, when
6477 // we'll have to do 2x as many shuffles in order to achieve this, blending
6478 // first is a better strategy.
6479 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6480 if (SDValue BlendPerm =
6481 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6484 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6485 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6486 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6489 /// \brief Try to lower a vector shuffle as a byte rotation.
6491 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6492 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6493 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6494 /// try to generically lower a vector shuffle through such an pattern. It
6495 /// does not check for the profitability of lowering either as PALIGNR or
6496 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6497 /// This matches shuffle vectors that look like:
6499 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6501 /// Essentially it concatenates V1 and V2, shifts right by some number of
6502 /// elements, and takes the low elements as the result. Note that while this is
6503 /// specified as a *right shift* because x86 is little-endian, it is a *left
6504 /// rotate* of the vector lanes.
6505 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6508 const X86Subtarget *Subtarget,
6509 SelectionDAG &DAG) {
6510 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6512 int NumElts = Mask.size();
6513 int NumLanes = VT.getSizeInBits() / 128;
6514 int NumLaneElts = NumElts / NumLanes;
6516 // We need to detect various ways of spelling a rotation:
6517 // [11, 12, 13, 14, 15, 0, 1, 2]
6518 // [-1, 12, 13, 14, -1, -1, 1, -1]
6519 // [-1, -1, -1, -1, -1, -1, 1, 2]
6520 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6521 // [-1, 4, 5, 6, -1, -1, 9, -1]
6522 // [-1, 4, 5, 6, -1, -1, -1, -1]
6525 for (int l = 0; l < NumElts; l += NumLaneElts) {
6526 for (int i = 0; i < NumLaneElts; ++i) {
6527 if (Mask[l + i] == -1)
6529 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6531 // Get the mod-Size index and lane correct it.
6532 int LaneIdx = (Mask[l + i] % NumElts) - l;
6533 // Make sure it was in this lane.
6534 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6537 // Determine where a rotated vector would have started.
6538 int StartIdx = i - LaneIdx;
6540 // The identity rotation isn't interesting, stop.
6543 // If we found the tail of a vector the rotation must be the missing
6544 // front. If we found the head of a vector, it must be how much of the
6546 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6549 Rotation = CandidateRotation;
6550 else if (Rotation != CandidateRotation)
6551 // The rotations don't match, so we can't match this mask.
6554 // Compute which value this mask is pointing at.
6555 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6557 // Compute which of the two target values this index should be assigned
6558 // to. This reflects whether the high elements are remaining or the low
6559 // elements are remaining.
6560 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6562 // Either set up this value if we've not encountered it before, or check
6563 // that it remains consistent.
6566 else if (TargetV != MaskV)
6567 // This may be a rotation, but it pulls from the inputs in some
6568 // unsupported interleaving.
6573 // Check that we successfully analyzed the mask, and normalize the results.
6574 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6575 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6581 // The actual rotate instruction rotates bytes, so we need to scale the
6582 // rotation based on how many bytes are in the vector lane.
6583 int Scale = 16 / NumLaneElts;
6585 // SSSE3 targets can use the palignr instruction.
6586 if (Subtarget->hasSSSE3()) {
6587 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6588 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6589 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6590 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6592 return DAG.getNode(ISD::BITCAST, DL, VT,
6593 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6594 DAG.getConstant(Rotation * Scale, DL,
6598 assert(VT.getSizeInBits() == 128 &&
6599 "Rotate-based lowering only supports 128-bit lowering!");
6600 assert(Mask.size() <= 16 &&
6601 "Can shuffle at most 16 bytes in a 128-bit vector!");
6603 // Default SSE2 implementation
6604 int LoByteShift = 16 - Rotation * Scale;
6605 int HiByteShift = Rotation * Scale;
6607 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6608 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6609 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6611 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6612 DAG.getConstant(LoByteShift, DL, MVT::i8));
6613 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6614 DAG.getConstant(HiByteShift, DL, MVT::i8));
6615 return DAG.getNode(ISD::BITCAST, DL, VT,
6616 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6619 /// \brief Compute whether each element of a shuffle is zeroable.
6621 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6622 /// Either it is an undef element in the shuffle mask, the element of the input
6623 /// referenced is undef, or the element of the input referenced is known to be
6624 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6625 /// as many lanes with this technique as possible to simplify the remaining
6627 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6628 SDValue V1, SDValue V2) {
6629 SmallBitVector Zeroable(Mask.size(), false);
6631 while (V1.getOpcode() == ISD::BITCAST)
6632 V1 = V1->getOperand(0);
6633 while (V2.getOpcode() == ISD::BITCAST)
6634 V2 = V2->getOperand(0);
6636 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6637 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6639 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6641 // Handle the easy cases.
6642 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6647 // If this is an index into a build_vector node (which has the same number
6648 // of elements), dig out the input value and use it.
6649 SDValue V = M < Size ? V1 : V2;
6650 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6653 SDValue Input = V.getOperand(M % Size);
6654 // The UNDEF opcode check really should be dead code here, but not quite
6655 // worth asserting on (it isn't invalid, just unexpected).
6656 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6663 /// \brief Try to emit a bitmask instruction for a shuffle.
6665 /// This handles cases where we can model a blend exactly as a bitmask due to
6666 /// one of the inputs being zeroable.
6667 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6668 SDValue V2, ArrayRef<int> Mask,
6669 SelectionDAG &DAG) {
6670 MVT EltVT = VT.getScalarType();
6671 int NumEltBits = EltVT.getSizeInBits();
6672 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6673 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6674 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6676 if (EltVT.isFloatingPoint()) {
6677 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6678 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6680 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6681 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6683 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6686 if (Mask[i] % Size != i)
6687 return SDValue(); // Not a blend.
6689 V = Mask[i] < Size ? V1 : V2;
6690 else if (V != (Mask[i] < Size ? V1 : V2))
6691 return SDValue(); // Can only let one input through the mask.
6693 VMaskOps[i] = AllOnes;
6696 return SDValue(); // No non-zeroable elements!
6698 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6699 V = DAG.getNode(VT.isFloatingPoint()
6700 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6705 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6707 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6708 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6709 /// matches elements from one of the input vectors shuffled to the left or
6710 /// right with zeroable elements 'shifted in'. It handles both the strictly
6711 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6714 /// PSHL : (little-endian) left bit shift.
6715 /// [ zz, 0, zz, 2 ]
6716 /// [ -1, 4, zz, -1 ]
6717 /// PSRL : (little-endian) right bit shift.
6719 /// [ -1, -1, 7, zz]
6720 /// PSLLDQ : (little-endian) left byte shift
6721 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6722 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6723 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6724 /// PSRLDQ : (little-endian) right byte shift
6725 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6726 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6727 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6728 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6729 SDValue V2, ArrayRef<int> Mask,
6730 SelectionDAG &DAG) {
6731 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6733 int Size = Mask.size();
6734 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6736 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6737 for (int i = 0; i < Size; i += Scale)
6738 for (int j = 0; j < Shift; ++j)
6739 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6745 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6746 for (int i = 0; i != Size; i += Scale) {
6747 unsigned Pos = Left ? i + Shift : i;
6748 unsigned Low = Left ? i : i + Shift;
6749 unsigned Len = Scale - Shift;
6750 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6751 Low + (V == V1 ? 0 : Size)))
6755 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6756 bool ByteShift = ShiftEltBits > 64;
6757 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6758 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6759 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6761 // Normalize the scale for byte shifts to still produce an i64 element
6763 Scale = ByteShift ? Scale / 2 : Scale;
6765 // We need to round trip through the appropriate type for the shift.
6766 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6767 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6768 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6769 "Illegal integer vector type");
6770 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6772 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6773 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6774 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6777 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6778 // keep doubling the size of the integer elements up to that. We can
6779 // then shift the elements of the integer vector by whole multiples of
6780 // their width within the elements of the larger integer vector. Test each
6781 // multiple to see if we can find a match with the moved element indices
6782 // and that the shifted in elements are all zeroable.
6783 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6784 for (int Shift = 1; Shift != Scale; ++Shift)
6785 for (bool Left : {true, false})
6786 if (CheckZeros(Shift, Scale, Left))
6787 for (SDValue V : {V1, V2})
6788 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6795 /// \brief Lower a vector shuffle as a zero or any extension.
6797 /// Given a specific number of elements, element bit width, and extension
6798 /// stride, produce either a zero or any extension based on the available
6799 /// features of the subtarget.
6800 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6801 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6802 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6803 assert(Scale > 1 && "Need a scale to extend.");
6804 int NumElements = VT.getVectorNumElements();
6805 int EltBits = VT.getScalarSizeInBits();
6806 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6807 "Only 8, 16, and 32 bit elements can be extended.");
6808 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6810 // Found a valid zext mask! Try various lowering strategies based on the
6811 // input type and available ISA extensions.
6812 if (Subtarget->hasSSE41()) {
6813 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6814 NumElements / Scale);
6815 return DAG.getNode(ISD::BITCAST, DL, VT,
6816 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6819 // For any extends we can cheat for larger element sizes and use shuffle
6820 // instructions that can fold with a load and/or copy.
6821 if (AnyExt && EltBits == 32) {
6822 int PSHUFDMask[4] = {0, -1, 1, -1};
6824 ISD::BITCAST, DL, VT,
6825 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6826 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6827 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6829 if (AnyExt && EltBits == 16 && Scale > 2) {
6830 int PSHUFDMask[4] = {0, -1, 0, -1};
6831 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6832 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6833 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6834 int PSHUFHWMask[4] = {1, -1, -1, -1};
6836 ISD::BITCAST, DL, VT,
6837 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6838 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6839 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6842 // If this would require more than 2 unpack instructions to expand, use
6843 // pshufb when available. We can only use more than 2 unpack instructions
6844 // when zero extending i8 elements which also makes it easier to use pshufb.
6845 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6846 assert(NumElements == 16 && "Unexpected byte vector width!");
6847 SDValue PSHUFBMask[16];
6848 for (int i = 0; i < 16; ++i)
6850 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6851 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6852 return DAG.getNode(ISD::BITCAST, DL, VT,
6853 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6854 DAG.getNode(ISD::BUILD_VECTOR, DL,
6855 MVT::v16i8, PSHUFBMask)));
6858 // Otherwise emit a sequence of unpacks.
6860 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6861 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6862 : getZeroVector(InputVT, Subtarget, DAG, DL);
6863 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6864 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6868 } while (Scale > 1);
6869 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6872 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6874 /// This routine will try to do everything in its power to cleverly lower
6875 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6876 /// check for the profitability of this lowering, it tries to aggressively
6877 /// match this pattern. It will use all of the micro-architectural details it
6878 /// can to emit an efficient lowering. It handles both blends with all-zero
6879 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6880 /// masking out later).
6882 /// The reason we have dedicated lowering for zext-style shuffles is that they
6883 /// are both incredibly common and often quite performance sensitive.
6884 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6885 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6886 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6887 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6889 int Bits = VT.getSizeInBits();
6890 int NumElements = VT.getVectorNumElements();
6891 assert(VT.getScalarSizeInBits() <= 32 &&
6892 "Exceeds 32-bit integer zero extension limit");
6893 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6895 // Define a helper function to check a particular ext-scale and lower to it if
6897 auto Lower = [&](int Scale) -> SDValue {
6900 for (int i = 0; i < NumElements; ++i) {
6902 continue; // Valid anywhere but doesn't tell us anything.
6903 if (i % Scale != 0) {
6904 // Each of the extended elements need to be zeroable.
6908 // We no longer are in the anyext case.
6913 // Each of the base elements needs to be consecutive indices into the
6914 // same input vector.
6915 SDValue V = Mask[i] < NumElements ? V1 : V2;
6918 else if (InputV != V)
6919 return SDValue(); // Flip-flopping inputs.
6921 if (Mask[i] % NumElements != i / Scale)
6922 return SDValue(); // Non-consecutive strided elements.
6925 // If we fail to find an input, we have a zero-shuffle which should always
6926 // have already been handled.
6927 // FIXME: Maybe handle this here in case during blending we end up with one?
6931 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6932 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6935 // The widest scale possible for extending is to a 64-bit integer.
6936 assert(Bits % 64 == 0 &&
6937 "The number of bits in a vector must be divisible by 64 on x86!");
6938 int NumExtElements = Bits / 64;
6940 // Each iteration, try extending the elements half as much, but into twice as
6942 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6943 assert(NumElements % NumExtElements == 0 &&
6944 "The input vector size must be divisible by the extended size.");
6945 if (SDValue V = Lower(NumElements / NumExtElements))
6949 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6953 // Returns one of the source operands if the shuffle can be reduced to a
6954 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6955 auto CanZExtLowHalf = [&]() {
6956 for (int i = NumElements / 2; i != NumElements; ++i)
6959 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6961 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6966 if (SDValue V = CanZExtLowHalf()) {
6967 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6968 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6969 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6972 // No viable ext lowering found.
6976 /// \brief Try to get a scalar value for a specific element of a vector.
6978 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6979 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6980 SelectionDAG &DAG) {
6981 MVT VT = V.getSimpleValueType();
6982 MVT EltVT = VT.getVectorElementType();
6983 while (V.getOpcode() == ISD::BITCAST)
6984 V = V.getOperand(0);
6985 // If the bitcasts shift the element size, we can't extract an equivalent
6987 MVT NewVT = V.getSimpleValueType();
6988 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6991 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6992 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6993 // Ensure the scalar operand is the same size as the destination.
6994 // FIXME: Add support for scalar truncation where possible.
6995 SDValue S = V.getOperand(Idx);
6996 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
6997 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7003 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7005 /// This is particularly important because the set of instructions varies
7006 /// significantly based on whether the operand is a load or not.
7007 static bool isShuffleFoldableLoad(SDValue V) {
7008 while (V.getOpcode() == ISD::BITCAST)
7009 V = V.getOperand(0);
7011 return ISD::isNON_EXTLoad(V.getNode());
7014 /// \brief Try to lower insertion of a single element into a zero vector.
7016 /// This is a common pattern that we have especially efficient patterns to lower
7017 /// across all subtarget feature sets.
7018 static SDValue lowerVectorShuffleAsElementInsertion(
7019 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7020 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7021 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7023 MVT EltVT = VT.getVectorElementType();
7025 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7026 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7028 bool IsV1Zeroable = true;
7029 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7030 if (i != V2Index && !Zeroable[i]) {
7031 IsV1Zeroable = false;
7035 // Check for a single input from a SCALAR_TO_VECTOR node.
7036 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7037 // all the smarts here sunk into that routine. However, the current
7038 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7039 // vector shuffle lowering is dead.
7040 if (SDValue V2S = getScalarValueForVectorElement(
7041 V2, Mask[V2Index] - Mask.size(), DAG)) {
7042 // We need to zext the scalar if it is smaller than an i32.
7043 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7044 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7045 // Using zext to expand a narrow element won't work for non-zero
7050 // Zero-extend directly to i32.
7052 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7054 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7055 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7056 EltVT == MVT::i16) {
7057 // Either not inserting from the low element of the input or the input
7058 // element size is too small to use VZEXT_MOVL to clear the high bits.
7062 if (!IsV1Zeroable) {
7063 // If V1 can't be treated as a zero vector we have fewer options to lower
7064 // this. We can't support integer vectors or non-zero targets cheaply, and
7065 // the V1 elements can't be permuted in any way.
7066 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7067 if (!VT.isFloatingPoint() || V2Index != 0)
7069 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7070 V1Mask[V2Index] = -1;
7071 if (!isNoopShuffleMask(V1Mask))
7073 // This is essentially a special case blend operation, but if we have
7074 // general purpose blend operations, they are always faster. Bail and let
7075 // the rest of the lowering handle these as blends.
7076 if (Subtarget->hasSSE41())
7079 // Otherwise, use MOVSD or MOVSS.
7080 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7081 "Only two types of floating point element types to handle!");
7082 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7086 // This lowering only works for the low element with floating point vectors.
7087 if (VT.isFloatingPoint() && V2Index != 0)
7090 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7092 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7095 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7096 // the desired position. Otherwise it is more efficient to do a vector
7097 // shift left. We know that we can do a vector shift left because all
7098 // the inputs are zero.
7099 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7100 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7101 V2Shuffle[V2Index] = 0;
7102 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7104 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7106 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7108 V2Index * EltVT.getSizeInBits()/8, DL,
7109 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7110 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7116 /// \brief Try to lower broadcast of a single element.
7118 /// For convenience, this code also bundles all of the subtarget feature set
7119 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7120 /// a convenient way to factor it out.
7121 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7123 const X86Subtarget *Subtarget,
7124 SelectionDAG &DAG) {
7125 if (!Subtarget->hasAVX())
7127 if (VT.isInteger() && !Subtarget->hasAVX2())
7130 // Check that the mask is a broadcast.
7131 int BroadcastIdx = -1;
7133 if (M >= 0 && BroadcastIdx == -1)
7135 else if (M >= 0 && M != BroadcastIdx)
7138 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7139 "a sorted mask where the broadcast "
7142 // Go up the chain of (vector) values to find a scalar load that we can
7143 // combine with the broadcast.
7145 switch (V.getOpcode()) {
7146 case ISD::CONCAT_VECTORS: {
7147 int OperandSize = Mask.size() / V.getNumOperands();
7148 V = V.getOperand(BroadcastIdx / OperandSize);
7149 BroadcastIdx %= OperandSize;
7153 case ISD::INSERT_SUBVECTOR: {
7154 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7155 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7159 int BeginIdx = (int)ConstantIdx->getZExtValue();
7161 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7162 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7163 BroadcastIdx -= BeginIdx;
7174 // Check if this is a broadcast of a scalar. We special case lowering
7175 // for scalars so that we can more effectively fold with loads.
7176 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7177 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7178 V = V.getOperand(BroadcastIdx);
7180 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7181 // Only AVX2 has register broadcasts.
7182 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7184 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7185 // We can't broadcast from a vector register without AVX2, and we can only
7186 // broadcast from the zero-element of a vector register.
7190 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7193 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7194 // INSERTPS when the V1 elements are already in the correct locations
7195 // because otherwise we can just always use two SHUFPS instructions which
7196 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7197 // perform INSERTPS if a single V1 element is out of place and all V2
7198 // elements are zeroable.
7199 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7201 SelectionDAG &DAG) {
7202 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7203 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7204 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7205 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7207 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7210 int V1DstIndex = -1;
7211 int V2DstIndex = -1;
7212 bool V1UsedInPlace = false;
7214 for (int i = 0; i < 4; ++i) {
7215 // Synthesize a zero mask from the zeroable elements (includes undefs).
7221 // Flag if we use any V1 inputs in place.
7223 V1UsedInPlace = true;
7227 // We can only insert a single non-zeroable element.
7228 if (V1DstIndex != -1 || V2DstIndex != -1)
7232 // V1 input out of place for insertion.
7235 // V2 input for insertion.
7240 // Don't bother if we have no (non-zeroable) element for insertion.
7241 if (V1DstIndex == -1 && V2DstIndex == -1)
7244 // Determine element insertion src/dst indices. The src index is from the
7245 // start of the inserted vector, not the start of the concatenated vector.
7246 unsigned V2SrcIndex = 0;
7247 if (V1DstIndex != -1) {
7248 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7249 // and don't use the original V2 at all.
7250 V2SrcIndex = Mask[V1DstIndex];
7251 V2DstIndex = V1DstIndex;
7254 V2SrcIndex = Mask[V2DstIndex] - 4;
7257 // If no V1 inputs are used in place, then the result is created only from
7258 // the zero mask and the V2 insertion - so remove V1 dependency.
7260 V1 = DAG.getUNDEF(MVT::v4f32);
7262 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7263 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7265 // Insert the V2 element into the desired position.
7267 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7268 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7271 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7272 /// UNPCK instruction.
7274 /// This specifically targets cases where we end up with alternating between
7275 /// the two inputs, and so can permute them into something that feeds a single
7276 /// UNPCK instruction. Note that this routine only targets integer vectors
7277 /// because for floating point vectors we have a generalized SHUFPS lowering
7278 /// strategy that handles everything that doesn't *exactly* match an unpack,
7279 /// making this clever lowering unnecessary.
7280 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7281 SDValue V2, ArrayRef<int> Mask,
7282 SelectionDAG &DAG) {
7283 assert(!VT.isFloatingPoint() &&
7284 "This routine only supports integer vectors.");
7285 assert(!isSingleInputShuffleMask(Mask) &&
7286 "This routine should only be used when blending two inputs.");
7287 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7289 int Size = Mask.size();
7291 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7292 return M >= 0 && M % Size < Size / 2;
7294 int NumHiInputs = std::count_if(
7295 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7297 bool UnpackLo = NumLoInputs >= NumHiInputs;
7299 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7300 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7301 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7303 for (int i = 0; i < Size; ++i) {
7307 // Each element of the unpack contains Scale elements from this mask.
7308 int UnpackIdx = i / Scale;
7310 // We only handle the case where V1 feeds the first slots of the unpack.
7311 // We rely on canonicalization to ensure this is the case.
7312 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7315 // Setup the mask for this input. The indexing is tricky as we have to
7316 // handle the unpack stride.
7317 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7318 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7322 // If we will have to shuffle both inputs to use the unpack, check whether
7323 // we can just unpack first and shuffle the result. If so, skip this unpack.
7324 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7325 !isNoopShuffleMask(V2Mask))
7328 // Shuffle the inputs into place.
7329 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7330 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7332 // Cast the inputs to the type we will use to unpack them.
7333 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7334 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7336 // Unpack the inputs and cast the result back to the desired type.
7337 return DAG.getNode(ISD::BITCAST, DL, VT,
7338 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7339 DL, UnpackVT, V1, V2));
7342 // We try each unpack from the largest to the smallest to try and find one
7343 // that fits this mask.
7344 int OrigNumElements = VT.getVectorNumElements();
7345 int OrigScalarSize = VT.getScalarSizeInBits();
7346 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7347 int Scale = ScalarSize / OrigScalarSize;
7348 int NumElements = OrigNumElements / Scale;
7349 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7350 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7354 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7356 if (NumLoInputs == 0 || NumHiInputs == 0) {
7357 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7358 "We have to have *some* inputs!");
7359 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7361 // FIXME: We could consider the total complexity of the permute of each
7362 // possible unpacking. Or at the least we should consider how many
7363 // half-crossings are created.
7364 // FIXME: We could consider commuting the unpacks.
7366 SmallVector<int, 32> PermMask;
7367 PermMask.assign(Size, -1);
7368 for (int i = 0; i < Size; ++i) {
7372 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7375 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7377 return DAG.getVectorShuffle(
7378 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7380 DAG.getUNDEF(VT), PermMask);
7386 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7388 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7389 /// support for floating point shuffles but not integer shuffles. These
7390 /// instructions will incur a domain crossing penalty on some chips though so
7391 /// it is better to avoid lowering through this for integer vectors where
7393 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7394 const X86Subtarget *Subtarget,
7395 SelectionDAG &DAG) {
7397 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7398 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7399 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7400 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7401 ArrayRef<int> Mask = SVOp->getMask();
7402 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7404 if (isSingleInputShuffleMask(Mask)) {
7405 // Use low duplicate instructions for masks that match their pattern.
7406 if (Subtarget->hasSSE3())
7407 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7408 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7410 // Straight shuffle of a single input vector. Simulate this by using the
7411 // single input as both of the "inputs" to this instruction..
7412 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7414 if (Subtarget->hasAVX()) {
7415 // If we have AVX, we can use VPERMILPS which will allow folding a load
7416 // into the shuffle.
7417 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7418 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7421 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7422 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7424 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7425 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7427 // If we have a single input, insert that into V1 if we can do so cheaply.
7428 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7429 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7430 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7432 // Try inverting the insertion since for v2 masks it is easy to do and we
7433 // can't reliably sort the mask one way or the other.
7434 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7435 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7436 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7437 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7441 // Try to use one of the special instruction patterns to handle two common
7442 // blend patterns if a zero-blend above didn't work.
7443 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7444 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7445 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7446 // We can either use a special instruction to load over the low double or
7447 // to move just the low double.
7449 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7451 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7453 if (Subtarget->hasSSE41())
7454 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7458 // Use dedicated unpack instructions for masks that match their pattern.
7459 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7460 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7461 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7462 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7464 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7465 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7466 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7469 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7471 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7472 /// the integer unit to minimize domain crossing penalties. However, for blends
7473 /// it falls back to the floating point shuffle operation with appropriate bit
7475 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7476 const X86Subtarget *Subtarget,
7477 SelectionDAG &DAG) {
7479 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7480 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7481 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7482 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7483 ArrayRef<int> Mask = SVOp->getMask();
7484 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7486 if (isSingleInputShuffleMask(Mask)) {
7487 // Check for being able to broadcast a single element.
7488 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7489 Mask, Subtarget, DAG))
7492 // Straight shuffle of a single input vector. For everything from SSE2
7493 // onward this has a single fast instruction with no scary immediates.
7494 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7495 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7496 int WidenedMask[4] = {
7497 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7498 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7500 ISD::BITCAST, DL, MVT::v2i64,
7501 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7502 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7504 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7505 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7506 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7507 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7509 // If we have a blend of two PACKUS operations an the blend aligns with the
7510 // low and half halves, we can just merge the PACKUS operations. This is
7511 // particularly important as it lets us merge shuffles that this routine itself
7513 auto GetPackNode = [](SDValue V) {
7514 while (V.getOpcode() == ISD::BITCAST)
7515 V = V.getOperand(0);
7517 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7519 if (SDValue V1Pack = GetPackNode(V1))
7520 if (SDValue V2Pack = GetPackNode(V2))
7521 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7522 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7523 Mask[0] == 0 ? V1Pack.getOperand(0)
7524 : V1Pack.getOperand(1),
7525 Mask[1] == 2 ? V2Pack.getOperand(0)
7526 : V2Pack.getOperand(1)));
7528 // Try to use shift instructions.
7530 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7533 // When loading a scalar and then shuffling it into a vector we can often do
7534 // the insertion cheaply.
7535 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7536 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7538 // Try inverting the insertion since for v2 masks it is easy to do and we
7539 // can't reliably sort the mask one way or the other.
7540 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7541 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7542 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7545 // We have different paths for blend lowering, but they all must use the
7546 // *exact* same predicate.
7547 bool IsBlendSupported = Subtarget->hasSSE41();
7548 if (IsBlendSupported)
7549 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7553 // Use dedicated unpack instructions for masks that match their pattern.
7554 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7555 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7556 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7557 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7559 // Try to use byte rotation instructions.
7560 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7561 if (Subtarget->hasSSSE3())
7562 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7563 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7566 // If we have direct support for blends, we should lower by decomposing into
7567 // a permute. That will be faster than the domain cross.
7568 if (IsBlendSupported)
7569 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7572 // We implement this with SHUFPD which is pretty lame because it will likely
7573 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7574 // However, all the alternatives are still more cycles and newer chips don't
7575 // have this problem. It would be really nice if x86 had better shuffles here.
7576 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7577 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7578 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7579 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7582 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7584 /// This is used to disable more specialized lowerings when the shufps lowering
7585 /// will happen to be efficient.
7586 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7587 // This routine only handles 128-bit shufps.
7588 assert(Mask.size() == 4 && "Unsupported mask size!");
7590 // To lower with a single SHUFPS we need to have the low half and high half
7591 // each requiring a single input.
7592 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7594 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7600 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7602 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7603 /// It makes no assumptions about whether this is the *best* lowering, it simply
7605 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7606 ArrayRef<int> Mask, SDValue V1,
7607 SDValue V2, SelectionDAG &DAG) {
7608 SDValue LowV = V1, HighV = V2;
7609 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7612 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7614 if (NumV2Elements == 1) {
7616 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7619 // Compute the index adjacent to V2Index and in the same half by toggling
7621 int V2AdjIndex = V2Index ^ 1;
7623 if (Mask[V2AdjIndex] == -1) {
7624 // Handles all the cases where we have a single V2 element and an undef.
7625 // This will only ever happen in the high lanes because we commute the
7626 // vector otherwise.
7628 std::swap(LowV, HighV);
7629 NewMask[V2Index] -= 4;
7631 // Handle the case where the V2 element ends up adjacent to a V1 element.
7632 // To make this work, blend them together as the first step.
7633 int V1Index = V2AdjIndex;
7634 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7635 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7636 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7638 // Now proceed to reconstruct the final blend as we have the necessary
7639 // high or low half formed.
7646 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7647 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7649 } else if (NumV2Elements == 2) {
7650 if (Mask[0] < 4 && Mask[1] < 4) {
7651 // Handle the easy case where we have V1 in the low lanes and V2 in the
7655 } else if (Mask[2] < 4 && Mask[3] < 4) {
7656 // We also handle the reversed case because this utility may get called
7657 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7658 // arrange things in the right direction.
7664 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7665 // trying to place elements directly, just blend them and set up the final
7666 // shuffle to place them.
7668 // The first two blend mask elements are for V1, the second two are for
7670 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7671 Mask[2] < 4 ? Mask[2] : Mask[3],
7672 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7673 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7674 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7675 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7677 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7680 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7681 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7682 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7683 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7686 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7687 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7690 /// \brief Lower 4-lane 32-bit floating point shuffles.
7692 /// Uses instructions exclusively from the floating point unit to minimize
7693 /// domain crossing penalties, as these are sufficient to implement all v4f32
7695 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7696 const X86Subtarget *Subtarget,
7697 SelectionDAG &DAG) {
7699 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7700 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7701 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7702 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7703 ArrayRef<int> Mask = SVOp->getMask();
7704 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7707 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7709 if (NumV2Elements == 0) {
7710 // Check for being able to broadcast a single element.
7711 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7712 Mask, Subtarget, DAG))
7715 // Use even/odd duplicate instructions for masks that match their pattern.
7716 if (Subtarget->hasSSE3()) {
7717 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7718 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7719 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7720 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7723 if (Subtarget->hasAVX()) {
7724 // If we have AVX, we can use VPERMILPS which will allow folding a load
7725 // into the shuffle.
7726 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7727 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7730 // Otherwise, use a straight shuffle of a single input vector. We pass the
7731 // input vector to both operands to simulate this with a SHUFPS.
7732 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7733 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7736 // There are special ways we can lower some single-element blends. However, we
7737 // have custom ways we can lower more complex single-element blends below that
7738 // we defer to if both this and BLENDPS fail to match, so restrict this to
7739 // when the V2 input is targeting element 0 of the mask -- that is the fast
7741 if (NumV2Elements == 1 && Mask[0] >= 4)
7742 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7743 Mask, Subtarget, DAG))
7746 if (Subtarget->hasSSE41()) {
7747 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7751 // Use INSERTPS if we can complete the shuffle efficiently.
7752 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7755 if (!isSingleSHUFPSMask(Mask))
7756 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7757 DL, MVT::v4f32, V1, V2, Mask, DAG))
7761 // Use dedicated unpack instructions for masks that match their pattern.
7762 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7763 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7764 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7765 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7766 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7767 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7768 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7769 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7771 // Otherwise fall back to a SHUFPS lowering strategy.
7772 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7775 /// \brief Lower 4-lane i32 vector shuffles.
7777 /// We try to handle these with integer-domain shuffles where we can, but for
7778 /// blends we use the floating point domain blend instructions.
7779 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7780 const X86Subtarget *Subtarget,
7781 SelectionDAG &DAG) {
7783 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7784 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7785 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7786 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7787 ArrayRef<int> Mask = SVOp->getMask();
7788 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7790 // Whenever we can lower this as a zext, that instruction is strictly faster
7791 // than any alternative. It also allows us to fold memory operands into the
7792 // shuffle in many cases.
7793 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7794 Mask, Subtarget, DAG))
7798 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7800 if (NumV2Elements == 0) {
7801 // Check for being able to broadcast a single element.
7802 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7803 Mask, Subtarget, DAG))
7806 // Straight shuffle of a single input vector. For everything from SSE2
7807 // onward this has a single fast instruction with no scary immediates.
7808 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7809 // but we aren't actually going to use the UNPCK instruction because doing
7810 // so prevents folding a load into this instruction or making a copy.
7811 const int UnpackLoMask[] = {0, 0, 1, 1};
7812 const int UnpackHiMask[] = {2, 2, 3, 3};
7813 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7814 Mask = UnpackLoMask;
7815 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7816 Mask = UnpackHiMask;
7818 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7819 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7822 // Try to use shift instructions.
7824 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7827 // There are special ways we can lower some single-element blends.
7828 if (NumV2Elements == 1)
7829 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7830 Mask, Subtarget, DAG))
7833 // We have different paths for blend lowering, but they all must use the
7834 // *exact* same predicate.
7835 bool IsBlendSupported = Subtarget->hasSSE41();
7836 if (IsBlendSupported)
7837 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7841 if (SDValue Masked =
7842 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7845 // Use dedicated unpack instructions for masks that match their pattern.
7846 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7847 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7848 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7849 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7850 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7851 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7852 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7853 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7855 // Try to use byte rotation instructions.
7856 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7857 if (Subtarget->hasSSSE3())
7858 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7859 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7862 // If we have direct support for blends, we should lower by decomposing into
7863 // a permute. That will be faster than the domain cross.
7864 if (IsBlendSupported)
7865 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7868 // Try to lower by permuting the inputs into an unpack instruction.
7869 if (SDValue Unpack =
7870 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7873 // We implement this with SHUFPS because it can blend from two vectors.
7874 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7875 // up the inputs, bypassing domain shift penalties that we would encur if we
7876 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7878 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7879 DAG.getVectorShuffle(
7881 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7882 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7885 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7886 /// shuffle lowering, and the most complex part.
7888 /// The lowering strategy is to try to form pairs of input lanes which are
7889 /// targeted at the same half of the final vector, and then use a dword shuffle
7890 /// to place them onto the right half, and finally unpack the paired lanes into
7891 /// their final position.
7893 /// The exact breakdown of how to form these dword pairs and align them on the
7894 /// correct sides is really tricky. See the comments within the function for
7895 /// more of the details.
7897 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7898 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7899 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7900 /// vector, form the analogous 128-bit 8-element Mask.
7901 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7902 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7903 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7904 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7905 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7907 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7908 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7909 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7911 SmallVector<int, 4> LoInputs;
7912 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7913 [](int M) { return M >= 0; });
7914 std::sort(LoInputs.begin(), LoInputs.end());
7915 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7916 SmallVector<int, 4> HiInputs;
7917 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7918 [](int M) { return M >= 0; });
7919 std::sort(HiInputs.begin(), HiInputs.end());
7920 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7922 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7923 int NumHToL = LoInputs.size() - NumLToL;
7925 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7926 int NumHToH = HiInputs.size() - NumLToH;
7927 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7928 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7929 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7930 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7932 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7933 // such inputs we can swap two of the dwords across the half mark and end up
7934 // with <=2 inputs to each half in each half. Once there, we can fall through
7935 // to the generic code below. For example:
7937 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7938 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7940 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7941 // and an existing 2-into-2 on the other half. In this case we may have to
7942 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7943 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7944 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7945 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7946 // half than the one we target for fixing) will be fixed when we re-enter this
7947 // path. We will also combine away any sequence of PSHUFD instructions that
7948 // result into a single instruction. Here is an example of the tricky case:
7950 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7951 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7953 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7955 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7956 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7958 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7959 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7961 // The result is fine to be handled by the generic logic.
7962 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7963 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7964 int AOffset, int BOffset) {
7965 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7966 "Must call this with A having 3 or 1 inputs from the A half.");
7967 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7968 "Must call this with B having 1 or 3 inputs from the B half.");
7969 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7970 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7972 // Compute the index of dword with only one word among the three inputs in
7973 // a half by taking the sum of the half with three inputs and subtracting
7974 // the sum of the actual three inputs. The difference is the remaining
7977 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7978 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7979 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7980 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7981 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7982 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7983 int TripleNonInputIdx =
7984 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7985 TripleDWord = TripleNonInputIdx / 2;
7987 // We use xor with one to compute the adjacent DWord to whichever one the
7989 OneInputDWord = (OneInput / 2) ^ 1;
7991 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7992 // and BToA inputs. If there is also such a problem with the BToB and AToB
7993 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7994 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7995 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7996 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7997 // Compute how many inputs will be flipped by swapping these DWords. We
7999 // to balance this to ensure we don't form a 3-1 shuffle in the other
8001 int NumFlippedAToBInputs =
8002 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8003 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8004 int NumFlippedBToBInputs =
8005 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8006 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8007 if ((NumFlippedAToBInputs == 1 &&
8008 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8009 (NumFlippedBToBInputs == 1 &&
8010 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8011 // We choose whether to fix the A half or B half based on whether that
8012 // half has zero flipped inputs. At zero, we may not be able to fix it
8013 // with that half. We also bias towards fixing the B half because that
8014 // will more commonly be the high half, and we have to bias one way.
8015 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8016 ArrayRef<int> Inputs) {
8017 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8018 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8019 PinnedIdx ^ 1) != Inputs.end();
8020 // Determine whether the free index is in the flipped dword or the
8021 // unflipped dword based on where the pinned index is. We use this bit
8022 // in an xor to conditionally select the adjacent dword.
8023 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8024 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8025 FixFreeIdx) != Inputs.end();
8026 if (IsFixIdxInput == IsFixFreeIdxInput)
8028 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8029 FixFreeIdx) != Inputs.end();
8030 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8031 "We need to be changing the number of flipped inputs!");
8032 int PSHUFHalfMask[] = {0, 1, 2, 3};
8033 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8034 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8036 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8039 if (M != -1 && M == FixIdx)
8041 else if (M != -1 && M == FixFreeIdx)
8044 if (NumFlippedBToBInputs != 0) {
8046 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8047 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8049 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8051 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8052 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8057 int PSHUFDMask[] = {0, 1, 2, 3};
8058 PSHUFDMask[ADWord] = BDWord;
8059 PSHUFDMask[BDWord] = ADWord;
8060 V = DAG.getNode(ISD::BITCAST, DL, VT,
8061 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8062 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8063 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8066 // Adjust the mask to match the new locations of A and B.
8068 if (M != -1 && M/2 == ADWord)
8069 M = 2 * BDWord + M % 2;
8070 else if (M != -1 && M/2 == BDWord)
8071 M = 2 * ADWord + M % 2;
8073 // Recurse back into this routine to re-compute state now that this isn't
8074 // a 3 and 1 problem.
8075 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8078 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8079 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8080 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8081 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8083 // At this point there are at most two inputs to the low and high halves from
8084 // each half. That means the inputs can always be grouped into dwords and
8085 // those dwords can then be moved to the correct half with a dword shuffle.
8086 // We use at most one low and one high word shuffle to collect these paired
8087 // inputs into dwords, and finally a dword shuffle to place them.
8088 int PSHUFLMask[4] = {-1, -1, -1, -1};
8089 int PSHUFHMask[4] = {-1, -1, -1, -1};
8090 int PSHUFDMask[4] = {-1, -1, -1, -1};
8092 // First fix the masks for all the inputs that are staying in their
8093 // original halves. This will then dictate the targets of the cross-half
8095 auto fixInPlaceInputs =
8096 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8097 MutableArrayRef<int> SourceHalfMask,
8098 MutableArrayRef<int> HalfMask, int HalfOffset) {
8099 if (InPlaceInputs.empty())
8101 if (InPlaceInputs.size() == 1) {
8102 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8103 InPlaceInputs[0] - HalfOffset;
8104 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8107 if (IncomingInputs.empty()) {
8108 // Just fix all of the in place inputs.
8109 for (int Input : InPlaceInputs) {
8110 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8111 PSHUFDMask[Input / 2] = Input / 2;
8116 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8117 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8118 InPlaceInputs[0] - HalfOffset;
8119 // Put the second input next to the first so that they are packed into
8120 // a dword. We find the adjacent index by toggling the low bit.
8121 int AdjIndex = InPlaceInputs[0] ^ 1;
8122 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8123 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8124 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8126 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8127 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8129 // Now gather the cross-half inputs and place them into a free dword of
8130 // their target half.
8131 // FIXME: This operation could almost certainly be simplified dramatically to
8132 // look more like the 3-1 fixing operation.
8133 auto moveInputsToRightHalf = [&PSHUFDMask](
8134 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8135 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8136 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8138 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8139 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8141 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8143 int LowWord = Word & ~1;
8144 int HighWord = Word | 1;
8145 return isWordClobbered(SourceHalfMask, LowWord) ||
8146 isWordClobbered(SourceHalfMask, HighWord);
8149 if (IncomingInputs.empty())
8152 if (ExistingInputs.empty()) {
8153 // Map any dwords with inputs from them into the right half.
8154 for (int Input : IncomingInputs) {
8155 // If the source half mask maps over the inputs, turn those into
8156 // swaps and use the swapped lane.
8157 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8158 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8159 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8160 Input - SourceOffset;
8161 // We have to swap the uses in our half mask in one sweep.
8162 for (int &M : HalfMask)
8163 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8165 else if (M == Input)
8166 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8168 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8169 Input - SourceOffset &&
8170 "Previous placement doesn't match!");
8172 // Note that this correctly re-maps both when we do a swap and when
8173 // we observe the other side of the swap above. We rely on that to
8174 // avoid swapping the members of the input list directly.
8175 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8178 // Map the input's dword into the correct half.
8179 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8180 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8182 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8184 "Previous placement doesn't match!");
8187 // And just directly shift any other-half mask elements to be same-half
8188 // as we will have mirrored the dword containing the element into the
8189 // same position within that half.
8190 for (int &M : HalfMask)
8191 if (M >= SourceOffset && M < SourceOffset + 4) {
8192 M = M - SourceOffset + DestOffset;
8193 assert(M >= 0 && "This should never wrap below zero!");
8198 // Ensure we have the input in a viable dword of its current half. This
8199 // is particularly tricky because the original position may be clobbered
8200 // by inputs being moved and *staying* in that half.
8201 if (IncomingInputs.size() == 1) {
8202 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8203 int InputFixed = std::find(std::begin(SourceHalfMask),
8204 std::end(SourceHalfMask), -1) -
8205 std::begin(SourceHalfMask) + SourceOffset;
8206 SourceHalfMask[InputFixed - SourceOffset] =
8207 IncomingInputs[0] - SourceOffset;
8208 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8210 IncomingInputs[0] = InputFixed;
8212 } else if (IncomingInputs.size() == 2) {
8213 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8214 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8215 // We have two non-adjacent or clobbered inputs we need to extract from
8216 // the source half. To do this, we need to map them into some adjacent
8217 // dword slot in the source mask.
8218 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8219 IncomingInputs[1] - SourceOffset};
8221 // If there is a free slot in the source half mask adjacent to one of
8222 // the inputs, place the other input in it. We use (Index XOR 1) to
8223 // compute an adjacent index.
8224 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8225 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8226 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8227 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8228 InputsFixed[1] = InputsFixed[0] ^ 1;
8229 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8230 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8231 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8232 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8233 InputsFixed[0] = InputsFixed[1] ^ 1;
8234 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8235 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8236 // The two inputs are in the same DWord but it is clobbered and the
8237 // adjacent DWord isn't used at all. Move both inputs to the free
8239 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8240 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8241 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8242 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8244 // The only way we hit this point is if there is no clobbering
8245 // (because there are no off-half inputs to this half) and there is no
8246 // free slot adjacent to one of the inputs. In this case, we have to
8247 // swap an input with a non-input.
8248 for (int i = 0; i < 4; ++i)
8249 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8250 "We can't handle any clobbers here!");
8251 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8252 "Cannot have adjacent inputs here!");
8254 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8255 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8257 // We also have to update the final source mask in this case because
8258 // it may need to undo the above swap.
8259 for (int &M : FinalSourceHalfMask)
8260 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8261 M = InputsFixed[1] + SourceOffset;
8262 else if (M == InputsFixed[1] + SourceOffset)
8263 M = (InputsFixed[0] ^ 1) + SourceOffset;
8265 InputsFixed[1] = InputsFixed[0] ^ 1;
8268 // Point everything at the fixed inputs.
8269 for (int &M : HalfMask)
8270 if (M == IncomingInputs[0])
8271 M = InputsFixed[0] + SourceOffset;
8272 else if (M == IncomingInputs[1])
8273 M = InputsFixed[1] + SourceOffset;
8275 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8276 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8279 llvm_unreachable("Unhandled input size!");
8282 // Now hoist the DWord down to the right half.
8283 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8284 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8285 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8286 for (int &M : HalfMask)
8287 for (int Input : IncomingInputs)
8289 M = FreeDWord * 2 + Input % 2;
8291 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8292 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8293 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8294 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8296 // Now enact all the shuffles we've computed to move the inputs into their
8298 if (!isNoopShuffleMask(PSHUFLMask))
8299 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8300 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8301 if (!isNoopShuffleMask(PSHUFHMask))
8302 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8303 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8304 if (!isNoopShuffleMask(PSHUFDMask))
8305 V = DAG.getNode(ISD::BITCAST, DL, VT,
8306 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8307 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8308 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8311 // At this point, each half should contain all its inputs, and we can then
8312 // just shuffle them into their final position.
8313 assert(std::count_if(LoMask.begin(), LoMask.end(),
8314 [](int M) { return M >= 4; }) == 0 &&
8315 "Failed to lift all the high half inputs to the low mask!");
8316 assert(std::count_if(HiMask.begin(), HiMask.end(),
8317 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8318 "Failed to lift all the low half inputs to the high mask!");
8320 // Do a half shuffle for the low mask.
8321 if (!isNoopShuffleMask(LoMask))
8322 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8323 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8325 // Do a half shuffle with the high mask after shifting its values down.
8326 for (int &M : HiMask)
8329 if (!isNoopShuffleMask(HiMask))
8330 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8331 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8336 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8337 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8338 SDValue V2, ArrayRef<int> Mask,
8339 SelectionDAG &DAG, bool &V1InUse,
8341 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8347 int Size = Mask.size();
8348 int Scale = 16 / Size;
8349 for (int i = 0; i < 16; ++i) {
8350 if (Mask[i / Scale] == -1) {
8351 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8353 const int ZeroMask = 0x80;
8354 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8356 int V2Idx = Mask[i / Scale] < Size
8358 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8359 if (Zeroable[i / Scale])
8360 V1Idx = V2Idx = ZeroMask;
8361 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8362 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8363 V1InUse |= (ZeroMask != V1Idx);
8364 V2InUse |= (ZeroMask != V2Idx);
8369 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8370 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8371 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8373 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8374 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8375 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8377 // If we need shuffled inputs from both, blend the two.
8379 if (V1InUse && V2InUse)
8380 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8382 V = V1InUse ? V1 : V2;
8384 // Cast the result back to the correct type.
8385 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8388 /// \brief Generic lowering of 8-lane i16 shuffles.
8390 /// This handles both single-input shuffles and combined shuffle/blends with
8391 /// two inputs. The single input shuffles are immediately delegated to
8392 /// a dedicated lowering routine.
8394 /// The blends are lowered in one of three fundamental ways. If there are few
8395 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8396 /// of the input is significantly cheaper when lowered as an interleaving of
8397 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8398 /// halves of the inputs separately (making them have relatively few inputs)
8399 /// and then concatenate them.
8400 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8401 const X86Subtarget *Subtarget,
8402 SelectionDAG &DAG) {
8404 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8405 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8406 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8407 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8408 ArrayRef<int> OrigMask = SVOp->getMask();
8409 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8410 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8411 MutableArrayRef<int> Mask(MaskStorage);
8413 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8415 // Whenever we can lower this as a zext, that instruction is strictly faster
8416 // than any alternative.
8417 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8418 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8421 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8423 auto isV2 = [](int M) { return M >= 8; };
8425 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8427 if (NumV2Inputs == 0) {
8428 // Check for being able to broadcast a single element.
8429 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8430 Mask, Subtarget, DAG))
8433 // Try to use shift instructions.
8435 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8438 // Use dedicated unpack instructions for masks that match their pattern.
8439 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8440 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8441 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8442 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8444 // Try to use byte rotation instructions.
8445 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8446 Mask, Subtarget, DAG))
8449 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8453 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8454 "All single-input shuffles should be canonicalized to be V1-input "
8457 // Try to use shift instructions.
8459 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8462 // There are special ways we can lower some single-element blends.
8463 if (NumV2Inputs == 1)
8464 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8465 Mask, Subtarget, DAG))
8468 // We have different paths for blend lowering, but they all must use the
8469 // *exact* same predicate.
8470 bool IsBlendSupported = Subtarget->hasSSE41();
8471 if (IsBlendSupported)
8472 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8476 if (SDValue Masked =
8477 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8480 // Use dedicated unpack instructions for masks that match their pattern.
8481 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8482 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8483 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8484 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8486 // Try to use byte rotation instructions.
8487 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8488 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8491 if (SDValue BitBlend =
8492 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8495 if (SDValue Unpack =
8496 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8499 // If we can't directly blend but can use PSHUFB, that will be better as it
8500 // can both shuffle and set up the inefficient blend.
8501 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8502 bool V1InUse, V2InUse;
8503 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8507 // We can always bit-blend if we have to so the fallback strategy is to
8508 // decompose into single-input permutes and blends.
8509 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8513 /// \brief Check whether a compaction lowering can be done by dropping even
8514 /// elements and compute how many times even elements must be dropped.
8516 /// This handles shuffles which take every Nth element where N is a power of
8517 /// two. Example shuffle masks:
8519 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8520 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8521 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8522 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8523 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8524 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8526 /// Any of these lanes can of course be undef.
8528 /// This routine only supports N <= 3.
8529 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8532 /// \returns N above, or the number of times even elements must be dropped if
8533 /// there is such a number. Otherwise returns zero.
8534 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8535 // Figure out whether we're looping over two inputs or just one.
8536 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8538 // The modulus for the shuffle vector entries is based on whether this is
8539 // a single input or not.
8540 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8541 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8542 "We should only be called with masks with a power-of-2 size!");
8544 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8546 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8547 // and 2^3 simultaneously. This is because we may have ambiguity with
8548 // partially undef inputs.
8549 bool ViableForN[3] = {true, true, true};
8551 for (int i = 0, e = Mask.size(); i < e; ++i) {
8552 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8557 bool IsAnyViable = false;
8558 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8559 if (ViableForN[j]) {
8562 // The shuffle mask must be equal to (i * 2^N) % M.
8563 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8566 ViableForN[j] = false;
8568 // Early exit if we exhaust the possible powers of two.
8573 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8577 // Return 0 as there is no viable power of two.
8581 /// \brief Generic lowering of v16i8 shuffles.
8583 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8584 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8585 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8586 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8588 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8589 const X86Subtarget *Subtarget,
8590 SelectionDAG &DAG) {
8592 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8593 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8594 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8595 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8596 ArrayRef<int> Mask = SVOp->getMask();
8597 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8599 // Try to use shift instructions.
8601 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8604 // Try to use byte rotation instructions.
8605 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8606 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8609 // Try to use a zext lowering.
8610 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8611 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8615 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8617 // For single-input shuffles, there are some nicer lowering tricks we can use.
8618 if (NumV2Elements == 0) {
8619 // Check for being able to broadcast a single element.
8620 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8621 Mask, Subtarget, DAG))
8624 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8625 // Notably, this handles splat and partial-splat shuffles more efficiently.
8626 // However, it only makes sense if the pre-duplication shuffle simplifies
8627 // things significantly. Currently, this means we need to be able to
8628 // express the pre-duplication shuffle as an i16 shuffle.
8630 // FIXME: We should check for other patterns which can be widened into an
8631 // i16 shuffle as well.
8632 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8633 for (int i = 0; i < 16; i += 2)
8634 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8639 auto tryToWidenViaDuplication = [&]() -> SDValue {
8640 if (!canWidenViaDuplication(Mask))
8642 SmallVector<int, 4> LoInputs;
8643 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8644 [](int M) { return M >= 0 && M < 8; });
8645 std::sort(LoInputs.begin(), LoInputs.end());
8646 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8648 SmallVector<int, 4> HiInputs;
8649 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8650 [](int M) { return M >= 8; });
8651 std::sort(HiInputs.begin(), HiInputs.end());
8652 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8655 bool TargetLo = LoInputs.size() >= HiInputs.size();
8656 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8657 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8659 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8660 SmallDenseMap<int, int, 8> LaneMap;
8661 for (int I : InPlaceInputs) {
8662 PreDupI16Shuffle[I/2] = I/2;
8665 int j = TargetLo ? 0 : 4, je = j + 4;
8666 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8667 // Check if j is already a shuffle of this input. This happens when
8668 // there are two adjacent bytes after we move the low one.
8669 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8670 // If we haven't yet mapped the input, search for a slot into which
8672 while (j < je && PreDupI16Shuffle[j] != -1)
8676 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8679 // Map this input with the i16 shuffle.
8680 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8683 // Update the lane map based on the mapping we ended up with.
8684 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8687 ISD::BITCAST, DL, MVT::v16i8,
8688 DAG.getVectorShuffle(MVT::v8i16, DL,
8689 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8690 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8692 // Unpack the bytes to form the i16s that will be shuffled into place.
8693 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8694 MVT::v16i8, V1, V1);
8696 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8697 for (int i = 0; i < 16; ++i)
8698 if (Mask[i] != -1) {
8699 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8700 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8701 if (PostDupI16Shuffle[i / 2] == -1)
8702 PostDupI16Shuffle[i / 2] = MappedMask;
8704 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8705 "Conflicting entrties in the original shuffle!");
8708 ISD::BITCAST, DL, MVT::v16i8,
8709 DAG.getVectorShuffle(MVT::v8i16, DL,
8710 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8711 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8713 if (SDValue V = tryToWidenViaDuplication())
8717 // Use dedicated unpack instructions for masks that match their pattern.
8718 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8719 0, 16, 1, 17, 2, 18, 3, 19,
8721 4, 20, 5, 21, 6, 22, 7, 23}))
8722 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8723 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8724 8, 24, 9, 25, 10, 26, 11, 27,
8726 12, 28, 13, 29, 14, 30, 15, 31}))
8727 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8729 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8730 // with PSHUFB. It is important to do this before we attempt to generate any
8731 // blends but after all of the single-input lowerings. If the single input
8732 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8733 // want to preserve that and we can DAG combine any longer sequences into
8734 // a PSHUFB in the end. But once we start blending from multiple inputs,
8735 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8736 // and there are *very* few patterns that would actually be faster than the
8737 // PSHUFB approach because of its ability to zero lanes.
8739 // FIXME: The only exceptions to the above are blends which are exact
8740 // interleavings with direct instructions supporting them. We currently don't
8741 // handle those well here.
8742 if (Subtarget->hasSSSE3()) {
8743 bool V1InUse = false;
8744 bool V2InUse = false;
8746 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8747 DAG, V1InUse, V2InUse);
8749 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8750 // do so. This avoids using them to handle blends-with-zero which is
8751 // important as a single pshufb is significantly faster for that.
8752 if (V1InUse && V2InUse) {
8753 if (Subtarget->hasSSE41())
8754 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8755 Mask, Subtarget, DAG))
8758 // We can use an unpack to do the blending rather than an or in some
8759 // cases. Even though the or may be (very minorly) more efficient, we
8760 // preference this lowering because there are common cases where part of
8761 // the complexity of the shuffles goes away when we do the final blend as
8763 // FIXME: It might be worth trying to detect if the unpack-feeding
8764 // shuffles will both be pshufb, in which case we shouldn't bother with
8766 if (SDValue Unpack =
8767 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8774 // There are special ways we can lower some single-element blends.
8775 if (NumV2Elements == 1)
8776 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8777 Mask, Subtarget, DAG))
8780 if (SDValue BitBlend =
8781 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8784 // Check whether a compaction lowering can be done. This handles shuffles
8785 // which take every Nth element for some even N. See the helper function for
8788 // We special case these as they can be particularly efficiently handled with
8789 // the PACKUSB instruction on x86 and they show up in common patterns of
8790 // rearranging bytes to truncate wide elements.
8791 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8792 // NumEvenDrops is the power of two stride of the elements. Another way of
8793 // thinking about it is that we need to drop the even elements this many
8794 // times to get the original input.
8795 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8797 // First we need to zero all the dropped bytes.
8798 assert(NumEvenDrops <= 3 &&
8799 "No support for dropping even elements more than 3 times.");
8800 // We use the mask type to pick which bytes are preserved based on how many
8801 // elements are dropped.
8802 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8803 SDValue ByteClearMask =
8804 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8805 DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8806 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8808 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8810 // Now pack things back together.
8811 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8812 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8813 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8814 for (int i = 1; i < NumEvenDrops; ++i) {
8815 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8816 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8822 // Handle multi-input cases by blending single-input shuffles.
8823 if (NumV2Elements > 0)
8824 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8827 // The fallback path for single-input shuffles widens this into two v8i16
8828 // vectors with unpacks, shuffles those, and then pulls them back together
8832 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8833 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8834 for (int i = 0; i < 16; ++i)
8836 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8838 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8840 SDValue VLoHalf, VHiHalf;
8841 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8842 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8844 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8845 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8846 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8847 [](int M) { return M >= 0 && M % 2 == 1; })) {
8848 // Use a mask to drop the high bytes.
8849 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8850 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8851 DAG.getConstant(0x00FF, DL, MVT::v8i16));
8853 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8854 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8856 // Squash the masks to point directly into VLoHalf.
8857 for (int &M : LoBlendMask)
8860 for (int &M : HiBlendMask)
8864 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8865 // VHiHalf so that we can blend them as i16s.
8866 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8867 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8868 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8869 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8872 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8873 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8875 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8878 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8880 /// This routine breaks down the specific type of 128-bit shuffle and
8881 /// dispatches to the lowering routines accordingly.
8882 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8883 MVT VT, const X86Subtarget *Subtarget,
8884 SelectionDAG &DAG) {
8885 switch (VT.SimpleTy) {
8887 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8889 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8891 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8893 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8895 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8897 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8900 llvm_unreachable("Unimplemented!");
8904 /// \brief Helper function to test whether a shuffle mask could be
8905 /// simplified by widening the elements being shuffled.
8907 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8908 /// leaves it in an unspecified state.
8910 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8911 /// shuffle masks. The latter have the special property of a '-2' representing
8912 /// a zero-ed lane of a vector.
8913 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8914 SmallVectorImpl<int> &WidenedMask) {
8915 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8916 // If both elements are undef, its trivial.
8917 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8918 WidenedMask.push_back(SM_SentinelUndef);
8922 // Check for an undef mask and a mask value properly aligned to fit with
8923 // a pair of values. If we find such a case, use the non-undef mask's value.
8924 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8925 WidenedMask.push_back(Mask[i + 1] / 2);
8928 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8929 WidenedMask.push_back(Mask[i] / 2);
8933 // When zeroing, we need to spread the zeroing across both lanes to widen.
8934 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8935 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8936 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8937 WidenedMask.push_back(SM_SentinelZero);
8943 // Finally check if the two mask values are adjacent and aligned with
8945 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8946 WidenedMask.push_back(Mask[i] / 2);
8950 // Otherwise we can't safely widen the elements used in this shuffle.
8953 assert(WidenedMask.size() == Mask.size() / 2 &&
8954 "Incorrect size of mask after widening the elements!");
8959 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8961 /// This routine just extracts two subvectors, shuffles them independently, and
8962 /// then concatenates them back together. This should work effectively with all
8963 /// AVX vector shuffle types.
8964 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8965 SDValue V2, ArrayRef<int> Mask,
8966 SelectionDAG &DAG) {
8967 assert(VT.getSizeInBits() >= 256 &&
8968 "Only for 256-bit or wider vector shuffles!");
8969 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8970 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8972 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8973 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8975 int NumElements = VT.getVectorNumElements();
8976 int SplitNumElements = NumElements / 2;
8977 MVT ScalarVT = VT.getScalarType();
8978 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8980 // Rather than splitting build-vectors, just build two narrower build
8981 // vectors. This helps shuffling with splats and zeros.
8982 auto SplitVector = [&](SDValue V) {
8983 while (V.getOpcode() == ISD::BITCAST)
8984 V = V->getOperand(0);
8986 MVT OrigVT = V.getSimpleValueType();
8987 int OrigNumElements = OrigVT.getVectorNumElements();
8988 int OrigSplitNumElements = OrigNumElements / 2;
8989 MVT OrigScalarVT = OrigVT.getScalarType();
8990 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8994 auto *BV = dyn_cast<BuildVectorSDNode>(V);
8996 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8997 DAG.getIntPtrConstant(0, DL));
8998 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8999 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9002 SmallVector<SDValue, 16> LoOps, HiOps;
9003 for (int i = 0; i < OrigSplitNumElements; ++i) {
9004 LoOps.push_back(BV->getOperand(i));
9005 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9007 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9008 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9010 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9011 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9014 SDValue LoV1, HiV1, LoV2, HiV2;
9015 std::tie(LoV1, HiV1) = SplitVector(V1);
9016 std::tie(LoV2, HiV2) = SplitVector(V2);
9018 // Now create two 4-way blends of these half-width vectors.
9019 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9020 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9021 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9022 for (int i = 0; i < SplitNumElements; ++i) {
9023 int M = HalfMask[i];
9024 if (M >= NumElements) {
9025 if (M >= NumElements + SplitNumElements)
9029 V2BlendMask.push_back(M - NumElements);
9030 V1BlendMask.push_back(-1);
9031 BlendMask.push_back(SplitNumElements + i);
9032 } else if (M >= 0) {
9033 if (M >= SplitNumElements)
9037 V2BlendMask.push_back(-1);
9038 V1BlendMask.push_back(M);
9039 BlendMask.push_back(i);
9041 V2BlendMask.push_back(-1);
9042 V1BlendMask.push_back(-1);
9043 BlendMask.push_back(-1);
9047 // Because the lowering happens after all combining takes place, we need to
9048 // manually combine these blend masks as much as possible so that we create
9049 // a minimal number of high-level vector shuffle nodes.
9051 // First try just blending the halves of V1 or V2.
9052 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9053 return DAG.getUNDEF(SplitVT);
9054 if (!UseLoV2 && !UseHiV2)
9055 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9056 if (!UseLoV1 && !UseHiV1)
9057 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9059 SDValue V1Blend, V2Blend;
9060 if (UseLoV1 && UseHiV1) {
9062 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9064 // We only use half of V1 so map the usage down into the final blend mask.
9065 V1Blend = UseLoV1 ? LoV1 : HiV1;
9066 for (int i = 0; i < SplitNumElements; ++i)
9067 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9068 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9070 if (UseLoV2 && UseHiV2) {
9072 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9074 // We only use half of V2 so map the usage down into the final blend mask.
9075 V2Blend = UseLoV2 ? LoV2 : HiV2;
9076 for (int i = 0; i < SplitNumElements; ++i)
9077 if (BlendMask[i] >= SplitNumElements)
9078 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9080 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9082 SDValue Lo = HalfBlend(LoMask);
9083 SDValue Hi = HalfBlend(HiMask);
9084 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9087 /// \brief Either split a vector in halves or decompose the shuffles and the
9090 /// This is provided as a good fallback for many lowerings of non-single-input
9091 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9092 /// between splitting the shuffle into 128-bit components and stitching those
9093 /// back together vs. extracting the single-input shuffles and blending those
9095 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9096 SDValue V2, ArrayRef<int> Mask,
9097 SelectionDAG &DAG) {
9098 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9099 "lower single-input shuffles as it "
9100 "could then recurse on itself.");
9101 int Size = Mask.size();
9103 // If this can be modeled as a broadcast of two elements followed by a blend,
9104 // prefer that lowering. This is especially important because broadcasts can
9105 // often fold with memory operands.
9106 auto DoBothBroadcast = [&] {
9107 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9110 if (V2BroadcastIdx == -1)
9111 V2BroadcastIdx = M - Size;
9112 else if (M - Size != V2BroadcastIdx)
9114 } else if (M >= 0) {
9115 if (V1BroadcastIdx == -1)
9117 else if (M != V1BroadcastIdx)
9122 if (DoBothBroadcast())
9123 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9126 // If the inputs all stem from a single 128-bit lane of each input, then we
9127 // split them rather than blending because the split will decompose to
9128 // unusually few instructions.
9129 int LaneCount = VT.getSizeInBits() / 128;
9130 int LaneSize = Size / LaneCount;
9131 SmallBitVector LaneInputs[2];
9132 LaneInputs[0].resize(LaneCount, false);
9133 LaneInputs[1].resize(LaneCount, false);
9134 for (int i = 0; i < Size; ++i)
9136 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9137 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9138 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9140 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9141 // that the decomposed single-input shuffles don't end up here.
9142 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9145 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9146 /// a permutation and blend of those lanes.
9148 /// This essentially blends the out-of-lane inputs to each lane into the lane
9149 /// from a permuted copy of the vector. This lowering strategy results in four
9150 /// instructions in the worst case for a single-input cross lane shuffle which
9151 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9152 /// of. Special cases for each particular shuffle pattern should be handled
9153 /// prior to trying this lowering.
9154 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9155 SDValue V1, SDValue V2,
9157 SelectionDAG &DAG) {
9158 // FIXME: This should probably be generalized for 512-bit vectors as well.
9159 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9160 int LaneSize = Mask.size() / 2;
9162 // If there are only inputs from one 128-bit lane, splitting will in fact be
9163 // less expensive. The flags track whether the given lane contains an element
9164 // that crosses to another lane.
9165 bool LaneCrossing[2] = {false, false};
9166 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9167 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9168 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9169 if (!LaneCrossing[0] || !LaneCrossing[1])
9170 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9172 if (isSingleInputShuffleMask(Mask)) {
9173 SmallVector<int, 32> FlippedBlendMask;
9174 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9175 FlippedBlendMask.push_back(
9176 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9178 : Mask[i] % LaneSize +
9179 (i / LaneSize) * LaneSize + Size));
9181 // Flip the vector, and blend the results which should now be in-lane. The
9182 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9183 // 5 for the high source. The value 3 selects the high half of source 2 and
9184 // the value 2 selects the low half of source 2. We only use source 2 to
9185 // allow folding it into a memory operand.
9186 unsigned PERMMask = 3 | 2 << 4;
9187 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9188 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9189 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9192 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9193 // will be handled by the above logic and a blend of the results, much like
9194 // other patterns in AVX.
9195 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9198 /// \brief Handle lowering 2-lane 128-bit shuffles.
9199 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9200 SDValue V2, ArrayRef<int> Mask,
9201 const X86Subtarget *Subtarget,
9202 SelectionDAG &DAG) {
9203 // TODO: If minimizing size and one of the inputs is a zero vector and the
9204 // the zero vector has only one use, we could use a VPERM2X128 to save the
9205 // instruction bytes needed to explicitly generate the zero vector.
9207 // Blends are faster and handle all the non-lane-crossing cases.
9208 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9212 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9213 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9215 // If either input operand is a zero vector, use VPERM2X128 because its mask
9216 // allows us to replace the zero input with an implicit zero.
9217 if (!IsV1Zero && !IsV2Zero) {
9218 // Check for patterns which can be matched with a single insert of a 128-bit
9220 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9221 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9222 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9223 VT.getVectorNumElements() / 2);
9224 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9225 DAG.getIntPtrConstant(0, DL));
9226 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9227 OnlyUsesV1 ? V1 : V2,
9228 DAG.getIntPtrConstant(0, DL));
9229 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9233 // Otherwise form a 128-bit permutation. After accounting for undefs,
9234 // convert the 64-bit shuffle mask selection values into 128-bit
9235 // selection bits by dividing the indexes by 2 and shifting into positions
9236 // defined by a vperm2*128 instruction's immediate control byte.
9238 // The immediate permute control byte looks like this:
9239 // [1:0] - select 128 bits from sources for low half of destination
9241 // [3] - zero low half of destination
9242 // [5:4] - select 128 bits from sources for high half of destination
9244 // [7] - zero high half of destination
9246 int MaskLO = Mask[0];
9247 if (MaskLO == SM_SentinelUndef)
9248 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9250 int MaskHI = Mask[2];
9251 if (MaskHI == SM_SentinelUndef)
9252 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9254 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9256 // If either input is a zero vector, replace it with an undef input.
9257 // Shuffle mask values < 4 are selecting elements of V1.
9258 // Shuffle mask values >= 4 are selecting elements of V2.
9259 // Adjust each half of the permute mask by clearing the half that was
9260 // selecting the zero vector and setting the zero mask bit.
9262 V1 = DAG.getUNDEF(VT);
9264 PermMask = (PermMask & 0xf0) | 0x08;
9266 PermMask = (PermMask & 0x0f) | 0x80;
9269 V2 = DAG.getUNDEF(VT);
9271 PermMask = (PermMask & 0xf0) | 0x08;
9273 PermMask = (PermMask & 0x0f) | 0x80;
9276 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9277 DAG.getConstant(PermMask, DL, MVT::i8));
9280 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9281 /// shuffling each lane.
9283 /// This will only succeed when the result of fixing the 128-bit lanes results
9284 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9285 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9286 /// the lane crosses early and then use simpler shuffles within each lane.
9288 /// FIXME: It might be worthwhile at some point to support this without
9289 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9290 /// in x86 only floating point has interesting non-repeating shuffles, and even
9291 /// those are still *marginally* more expensive.
9292 static SDValue lowerVectorShuffleByMerging128BitLanes(
9293 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9294 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9295 assert(!isSingleInputShuffleMask(Mask) &&
9296 "This is only useful with multiple inputs.");
9298 int Size = Mask.size();
9299 int LaneSize = 128 / VT.getScalarSizeInBits();
9300 int NumLanes = Size / LaneSize;
9301 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9303 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9304 // check whether the in-128-bit lane shuffles share a repeating pattern.
9305 SmallVector<int, 4> Lanes;
9306 Lanes.resize(NumLanes, -1);
9307 SmallVector<int, 4> InLaneMask;
9308 InLaneMask.resize(LaneSize, -1);
9309 for (int i = 0; i < Size; ++i) {
9313 int j = i / LaneSize;
9316 // First entry we've seen for this lane.
9317 Lanes[j] = Mask[i] / LaneSize;
9318 } else if (Lanes[j] != Mask[i] / LaneSize) {
9319 // This doesn't match the lane selected previously!
9323 // Check that within each lane we have a consistent shuffle mask.
9324 int k = i % LaneSize;
9325 if (InLaneMask[k] < 0) {
9326 InLaneMask[k] = Mask[i] % LaneSize;
9327 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9328 // This doesn't fit a repeating in-lane mask.
9333 // First shuffle the lanes into place.
9334 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9335 VT.getSizeInBits() / 64);
9336 SmallVector<int, 8> LaneMask;
9337 LaneMask.resize(NumLanes * 2, -1);
9338 for (int i = 0; i < NumLanes; ++i)
9339 if (Lanes[i] >= 0) {
9340 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9341 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9344 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9345 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9346 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9348 // Cast it back to the type we actually want.
9349 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9351 // Now do a simple shuffle that isn't lane crossing.
9352 SmallVector<int, 8> NewMask;
9353 NewMask.resize(Size, -1);
9354 for (int i = 0; i < Size; ++i)
9356 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9357 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9358 "Must not introduce lane crosses at this point!");
9360 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9363 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9366 /// This returns true if the elements from a particular input are already in the
9367 /// slot required by the given mask and require no permutation.
9368 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9369 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9370 int Size = Mask.size();
9371 for (int i = 0; i < Size; ++i)
9372 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9378 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9380 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9381 /// isn't available.
9382 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9383 const X86Subtarget *Subtarget,
9384 SelectionDAG &DAG) {
9386 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9387 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9388 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9389 ArrayRef<int> Mask = SVOp->getMask();
9390 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9392 SmallVector<int, 4> WidenedMask;
9393 if (canWidenShuffleElements(Mask, WidenedMask))
9394 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9397 if (isSingleInputShuffleMask(Mask)) {
9398 // Check for being able to broadcast a single element.
9399 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9400 Mask, Subtarget, DAG))
9403 // Use low duplicate instructions for masks that match their pattern.
9404 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9405 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9407 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9408 // Non-half-crossing single input shuffles can be lowerid with an
9409 // interleaved permutation.
9410 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9411 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9412 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9413 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9416 // With AVX2 we have direct support for this permutation.
9417 if (Subtarget->hasAVX2())
9418 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9419 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9421 // Otherwise, fall back.
9422 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9426 // X86 has dedicated unpack instructions that can handle specific blend
9427 // operations: UNPCKH and UNPCKL.
9428 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9429 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9430 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9431 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9432 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9433 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9434 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9435 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9437 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9441 // Check if the blend happens to exactly fit that of SHUFPD.
9442 if ((Mask[0] == -1 || Mask[0] < 2) &&
9443 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9444 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9445 (Mask[3] == -1 || Mask[3] >= 6)) {
9446 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9447 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9448 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9449 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9451 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9452 (Mask[1] == -1 || Mask[1] < 2) &&
9453 (Mask[2] == -1 || Mask[2] >= 6) &&
9454 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9455 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9456 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9457 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9458 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9461 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9462 // shuffle. However, if we have AVX2 and either inputs are already in place,
9463 // we will be able to shuffle even across lanes the other input in a single
9464 // instruction so skip this pattern.
9465 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9466 isShuffleMaskInputInPlace(1, Mask))))
9467 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9468 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9471 // If we have AVX2 then we always want to lower with a blend because an v4 we
9472 // can fully permute the elements.
9473 if (Subtarget->hasAVX2())
9474 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9477 // Otherwise fall back on generic lowering.
9478 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9481 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9483 /// This routine is only called when we have AVX2 and thus a reasonable
9484 /// instruction set for v4i64 shuffling..
9485 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9486 const X86Subtarget *Subtarget,
9487 SelectionDAG &DAG) {
9489 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9490 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9491 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9492 ArrayRef<int> Mask = SVOp->getMask();
9493 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9494 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9496 SmallVector<int, 4> WidenedMask;
9497 if (canWidenShuffleElements(Mask, WidenedMask))
9498 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9501 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9505 // Check for being able to broadcast a single element.
9506 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9507 Mask, Subtarget, DAG))
9510 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9511 // use lower latency instructions that will operate on both 128-bit lanes.
9512 SmallVector<int, 2> RepeatedMask;
9513 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9514 if (isSingleInputShuffleMask(Mask)) {
9515 int PSHUFDMask[] = {-1, -1, -1, -1};
9516 for (int i = 0; i < 2; ++i)
9517 if (RepeatedMask[i] >= 0) {
9518 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9519 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9522 ISD::BITCAST, DL, MVT::v4i64,
9523 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9524 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9525 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9529 // AVX2 provides a direct instruction for permuting a single input across
9531 if (isSingleInputShuffleMask(Mask))
9532 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9533 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9535 // Try to use shift instructions.
9537 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9540 // Use dedicated unpack instructions for masks that match their pattern.
9541 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9542 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9543 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9544 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9545 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9546 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9547 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9548 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9550 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9551 // shuffle. However, if we have AVX2 and either inputs are already in place,
9552 // we will be able to shuffle even across lanes the other input in a single
9553 // instruction so skip this pattern.
9554 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9555 isShuffleMaskInputInPlace(1, Mask))))
9556 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9557 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9560 // Otherwise fall back on generic blend lowering.
9561 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9565 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9567 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9568 /// isn't available.
9569 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9570 const X86Subtarget *Subtarget,
9571 SelectionDAG &DAG) {
9573 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9574 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9575 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9576 ArrayRef<int> Mask = SVOp->getMask();
9577 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9579 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9583 // Check for being able to broadcast a single element.
9584 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9585 Mask, Subtarget, DAG))
9588 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9589 // options to efficiently lower the shuffle.
9590 SmallVector<int, 4> RepeatedMask;
9591 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9592 assert(RepeatedMask.size() == 4 &&
9593 "Repeated masks must be half the mask width!");
9595 // Use even/odd duplicate instructions for masks that match their pattern.
9596 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9597 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9598 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9599 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9601 if (isSingleInputShuffleMask(Mask))
9602 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9603 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9605 // Use dedicated unpack instructions for masks that match their pattern.
9606 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9607 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9608 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9609 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9610 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9611 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9612 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9613 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9615 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9616 // have already handled any direct blends. We also need to squash the
9617 // repeated mask into a simulated v4f32 mask.
9618 for (int i = 0; i < 4; ++i)
9619 if (RepeatedMask[i] >= 8)
9620 RepeatedMask[i] -= 4;
9621 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9624 // If we have a single input shuffle with different shuffle patterns in the
9625 // two 128-bit lanes use the variable mask to VPERMILPS.
9626 if (isSingleInputShuffleMask(Mask)) {
9627 SDValue VPermMask[8];
9628 for (int i = 0; i < 8; ++i)
9629 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9630 : DAG.getConstant(Mask[i], DL, MVT::i32);
9631 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9633 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9634 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9636 if (Subtarget->hasAVX2())
9637 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9638 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9639 DAG.getNode(ISD::BUILD_VECTOR, DL,
9640 MVT::v8i32, VPermMask)),
9643 // Otherwise, fall back.
9644 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9648 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9650 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9651 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9654 // If we have AVX2 then we always want to lower with a blend because at v8 we
9655 // can fully permute the elements.
9656 if (Subtarget->hasAVX2())
9657 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9660 // Otherwise fall back on generic lowering.
9661 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9664 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9666 /// This routine is only called when we have AVX2 and thus a reasonable
9667 /// instruction set for v8i32 shuffling..
9668 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9669 const X86Subtarget *Subtarget,
9670 SelectionDAG &DAG) {
9672 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9673 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9674 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9675 ArrayRef<int> Mask = SVOp->getMask();
9676 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9677 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9679 // Whenever we can lower this as a zext, that instruction is strictly faster
9680 // than any alternative. It also allows us to fold memory operands into the
9681 // shuffle in many cases.
9682 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9683 Mask, Subtarget, DAG))
9686 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9690 // Check for being able to broadcast a single element.
9691 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9692 Mask, Subtarget, DAG))
9695 // If the shuffle mask is repeated in each 128-bit lane we can use more
9696 // efficient instructions that mirror the shuffles across the two 128-bit
9698 SmallVector<int, 4> RepeatedMask;
9699 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9700 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9701 if (isSingleInputShuffleMask(Mask))
9702 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9703 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9705 // Use dedicated unpack instructions for masks that match their pattern.
9706 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9707 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9708 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9709 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9710 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9711 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9712 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9713 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9716 // Try to use shift instructions.
9718 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9721 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9722 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9725 // If the shuffle patterns aren't repeated but it is a single input, directly
9726 // generate a cross-lane VPERMD instruction.
9727 if (isSingleInputShuffleMask(Mask)) {
9728 SDValue VPermMask[8];
9729 for (int i = 0; i < 8; ++i)
9730 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9731 : DAG.getConstant(Mask[i], DL, MVT::i32);
9733 X86ISD::VPERMV, DL, MVT::v8i32,
9734 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9737 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9739 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9740 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9743 // Otherwise fall back on generic blend lowering.
9744 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9748 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9750 /// This routine is only called when we have AVX2 and thus a reasonable
9751 /// instruction set for v16i16 shuffling..
9752 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9753 const X86Subtarget *Subtarget,
9754 SelectionDAG &DAG) {
9756 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9757 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9758 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9759 ArrayRef<int> Mask = SVOp->getMask();
9760 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9761 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9763 // Whenever we can lower this as a zext, that instruction is strictly faster
9764 // than any alternative. It also allows us to fold memory operands into the
9765 // shuffle in many cases.
9766 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9767 Mask, Subtarget, DAG))
9770 // Check for being able to broadcast a single element.
9771 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9772 Mask, Subtarget, DAG))
9775 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9779 // Use dedicated unpack instructions for masks that match their pattern.
9780 if (isShuffleEquivalent(V1, V2, Mask,
9781 {// First 128-bit lane:
9782 0, 16, 1, 17, 2, 18, 3, 19,
9783 // Second 128-bit lane:
9784 8, 24, 9, 25, 10, 26, 11, 27}))
9785 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9786 if (isShuffleEquivalent(V1, V2, Mask,
9787 {// First 128-bit lane:
9788 4, 20, 5, 21, 6, 22, 7, 23,
9789 // Second 128-bit lane:
9790 12, 28, 13, 29, 14, 30, 15, 31}))
9791 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9793 // Try to use shift instructions.
9795 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9798 // Try to use byte rotation instructions.
9799 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9800 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9803 if (isSingleInputShuffleMask(Mask)) {
9804 // There are no generalized cross-lane shuffle operations available on i16
9806 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9807 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9810 SmallVector<int, 8> RepeatedMask;
9811 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9812 // As this is a single-input shuffle, the repeated mask should be
9813 // a strictly valid v8i16 mask that we can pass through to the v8i16
9814 // lowering to handle even the v16 case.
9815 return lowerV8I16GeneralSingleInputVectorShuffle(
9816 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9819 SDValue PSHUFBMask[32];
9820 for (int i = 0; i < 16; ++i) {
9821 if (Mask[i] == -1) {
9822 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9826 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9827 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9828 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9829 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9832 ISD::BITCAST, DL, MVT::v16i16,
9834 X86ISD::PSHUFB, DL, MVT::v32i8,
9835 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9836 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9839 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9841 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9842 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9845 // Otherwise fall back on generic lowering.
9846 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9849 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9851 /// This routine is only called when we have AVX2 and thus a reasonable
9852 /// instruction set for v32i8 shuffling..
9853 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9854 const X86Subtarget *Subtarget,
9855 SelectionDAG &DAG) {
9857 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9858 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9859 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9860 ArrayRef<int> Mask = SVOp->getMask();
9861 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9862 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9864 // Whenever we can lower this as a zext, that instruction is strictly faster
9865 // than any alternative. It also allows us to fold memory operands into the
9866 // shuffle in many cases.
9867 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9868 Mask, Subtarget, DAG))
9871 // Check for being able to broadcast a single element.
9872 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9873 Mask, Subtarget, DAG))
9876 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9880 // Use dedicated unpack instructions for masks that match their pattern.
9881 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9883 if (isShuffleEquivalent(
9885 {// First 128-bit lane:
9886 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9887 // Second 128-bit lane:
9888 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9889 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9890 if (isShuffleEquivalent(
9892 {// First 128-bit lane:
9893 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9894 // Second 128-bit lane:
9895 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9896 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9898 // Try to use shift instructions.
9900 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9903 // Try to use byte rotation instructions.
9904 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9905 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9908 if (isSingleInputShuffleMask(Mask)) {
9909 // There are no generalized cross-lane shuffle operations available on i8
9911 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9912 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9915 SDValue PSHUFBMask[32];
9916 for (int i = 0; i < 32; ++i)
9919 ? DAG.getUNDEF(MVT::i8)
9920 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9924 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9925 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9928 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9930 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9931 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9934 // Otherwise fall back on generic lowering.
9935 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9938 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9940 /// This routine either breaks down the specific type of a 256-bit x86 vector
9941 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9942 /// together based on the available instructions.
9943 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9944 MVT VT, const X86Subtarget *Subtarget,
9945 SelectionDAG &DAG) {
9947 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9948 ArrayRef<int> Mask = SVOp->getMask();
9950 // If we have a single input to the zero element, insert that into V1 if we
9951 // can do so cheaply.
9952 int NumElts = VT.getVectorNumElements();
9953 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9954 return M >= NumElts;
9957 if (NumV2Elements == 1 && Mask[0] >= NumElts)
9958 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9959 DL, VT, V1, V2, Mask, Subtarget, DAG))
9962 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9963 // check for those subtargets here and avoid much of the subtarget querying in
9964 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9965 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9966 // floating point types there eventually, just immediately cast everything to
9967 // a float and operate entirely in that domain.
9968 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9969 int ElementBits = VT.getScalarSizeInBits();
9970 if (ElementBits < 32)
9971 // No floating point type available, decompose into 128-bit vectors.
9972 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9974 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9975 VT.getVectorNumElements());
9976 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9977 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9978 return DAG.getNode(ISD::BITCAST, DL, VT,
9979 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9982 switch (VT.SimpleTy) {
9984 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9986 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9988 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9990 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9992 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9994 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9997 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10001 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10002 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10003 const X86Subtarget *Subtarget,
10004 SelectionDAG &DAG) {
10006 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10007 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10008 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10009 ArrayRef<int> Mask = SVOp->getMask();
10010 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10012 // X86 has dedicated unpack instructions that can handle specific blend
10013 // operations: UNPCKH and UNPCKL.
10014 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10015 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10016 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10017 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10019 // FIXME: Implement direct support for this type!
10020 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10023 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10024 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10025 const X86Subtarget *Subtarget,
10026 SelectionDAG &DAG) {
10028 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10029 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10030 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10031 ArrayRef<int> Mask = SVOp->getMask();
10032 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10034 // Use dedicated unpack instructions for masks that match their pattern.
10035 if (isShuffleEquivalent(V1, V2, Mask,
10036 {// First 128-bit lane.
10037 0, 16, 1, 17, 4, 20, 5, 21,
10038 // Second 128-bit lane.
10039 8, 24, 9, 25, 12, 28, 13, 29}))
10040 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10041 if (isShuffleEquivalent(V1, V2, Mask,
10042 {// First 128-bit lane.
10043 2, 18, 3, 19, 6, 22, 7, 23,
10044 // Second 128-bit lane.
10045 10, 26, 11, 27, 14, 30, 15, 31}))
10046 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10048 // FIXME: Implement direct support for this type!
10049 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10052 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10053 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10054 const X86Subtarget *Subtarget,
10055 SelectionDAG &DAG) {
10057 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10058 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10059 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10060 ArrayRef<int> Mask = SVOp->getMask();
10061 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10063 // X86 has dedicated unpack instructions that can handle specific blend
10064 // operations: UNPCKH and UNPCKL.
10065 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10066 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10067 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10068 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10070 // FIXME: Implement direct support for this type!
10071 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10074 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10075 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10076 const X86Subtarget *Subtarget,
10077 SelectionDAG &DAG) {
10079 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10080 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10081 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10082 ArrayRef<int> Mask = SVOp->getMask();
10083 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10085 // Use dedicated unpack instructions for masks that match their pattern.
10086 if (isShuffleEquivalent(V1, V2, Mask,
10087 {// First 128-bit lane.
10088 0, 16, 1, 17, 4, 20, 5, 21,
10089 // Second 128-bit lane.
10090 8, 24, 9, 25, 12, 28, 13, 29}))
10091 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10092 if (isShuffleEquivalent(V1, V2, Mask,
10093 {// First 128-bit lane.
10094 2, 18, 3, 19, 6, 22, 7, 23,
10095 // Second 128-bit lane.
10096 10, 26, 11, 27, 14, 30, 15, 31}))
10097 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10099 // FIXME: Implement direct support for this type!
10100 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10103 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10104 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10105 const X86Subtarget *Subtarget,
10106 SelectionDAG &DAG) {
10108 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10109 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10110 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10111 ArrayRef<int> Mask = SVOp->getMask();
10112 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10113 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10115 // FIXME: Implement direct support for this type!
10116 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10119 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10120 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10121 const X86Subtarget *Subtarget,
10122 SelectionDAG &DAG) {
10124 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10125 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10126 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10127 ArrayRef<int> Mask = SVOp->getMask();
10128 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10129 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10131 // FIXME: Implement direct support for this type!
10132 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10135 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10137 /// This routine either breaks down the specific type of a 512-bit x86 vector
10138 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10139 /// together based on the available instructions.
10140 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10141 MVT VT, const X86Subtarget *Subtarget,
10142 SelectionDAG &DAG) {
10144 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10145 ArrayRef<int> Mask = SVOp->getMask();
10146 assert(Subtarget->hasAVX512() &&
10147 "Cannot lower 512-bit vectors w/ basic ISA!");
10149 // Check for being able to broadcast a single element.
10150 if (SDValue Broadcast =
10151 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10154 // Dispatch to each element type for lowering. If we don't have supprot for
10155 // specific element type shuffles at 512 bits, immediately split them and
10156 // lower them. Each lowering routine of a given type is allowed to assume that
10157 // the requisite ISA extensions for that element type are available.
10158 switch (VT.SimpleTy) {
10160 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10162 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10164 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10166 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10168 if (Subtarget->hasBWI())
10169 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10172 if (Subtarget->hasBWI())
10173 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10177 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10180 // Otherwise fall back on splitting.
10181 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10184 /// \brief Top-level lowering for x86 vector shuffles.
10186 /// This handles decomposition, canonicalization, and lowering of all x86
10187 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10188 /// above in helper routines. The canonicalization attempts to widen shuffles
10189 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10190 /// s.t. only one of the two inputs needs to be tested, etc.
10191 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10192 SelectionDAG &DAG) {
10193 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10194 ArrayRef<int> Mask = SVOp->getMask();
10195 SDValue V1 = Op.getOperand(0);
10196 SDValue V2 = Op.getOperand(1);
10197 MVT VT = Op.getSimpleValueType();
10198 int NumElements = VT.getVectorNumElements();
10201 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10203 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10204 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10205 if (V1IsUndef && V2IsUndef)
10206 return DAG.getUNDEF(VT);
10208 // When we create a shuffle node we put the UNDEF node to second operand,
10209 // but in some cases the first operand may be transformed to UNDEF.
10210 // In this case we should just commute the node.
10212 return DAG.getCommutedVectorShuffle(*SVOp);
10214 // Check for non-undef masks pointing at an undef vector and make the masks
10215 // undef as well. This makes it easier to match the shuffle based solely on
10219 if (M >= NumElements) {
10220 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10221 for (int &M : NewMask)
10222 if (M >= NumElements)
10224 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10227 // We actually see shuffles that are entirely re-arrangements of a set of
10228 // zero inputs. This mostly happens while decomposing complex shuffles into
10229 // simple ones. Directly lower these as a buildvector of zeros.
10230 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10231 if (Zeroable.all())
10232 return getZeroVector(VT, Subtarget, DAG, dl);
10234 // Try to collapse shuffles into using a vector type with fewer elements but
10235 // wider element types. We cap this to not form integers or floating point
10236 // elements wider than 64 bits, but it might be interesting to form i128
10237 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10238 SmallVector<int, 16> WidenedMask;
10239 if (VT.getScalarSizeInBits() < 64 &&
10240 canWidenShuffleElements(Mask, WidenedMask)) {
10241 MVT NewEltVT = VT.isFloatingPoint()
10242 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10243 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10244 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10245 // Make sure that the new vector type is legal. For example, v2f64 isn't
10247 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10248 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10249 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10250 return DAG.getNode(ISD::BITCAST, dl, VT,
10251 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10255 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10256 for (int M : SVOp->getMask())
10258 ++NumUndefElements;
10259 else if (M < NumElements)
10264 // Commute the shuffle as needed such that more elements come from V1 than
10265 // V2. This allows us to match the shuffle pattern strictly on how many
10266 // elements come from V1 without handling the symmetric cases.
10267 if (NumV2Elements > NumV1Elements)
10268 return DAG.getCommutedVectorShuffle(*SVOp);
10270 // When the number of V1 and V2 elements are the same, try to minimize the
10271 // number of uses of V2 in the low half of the vector. When that is tied,
10272 // ensure that the sum of indices for V1 is equal to or lower than the sum
10273 // indices for V2. When those are equal, try to ensure that the number of odd
10274 // indices for V1 is lower than the number of odd indices for V2.
10275 if (NumV1Elements == NumV2Elements) {
10276 int LowV1Elements = 0, LowV2Elements = 0;
10277 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10278 if (M >= NumElements)
10282 if (LowV2Elements > LowV1Elements) {
10283 return DAG.getCommutedVectorShuffle(*SVOp);
10284 } else if (LowV2Elements == LowV1Elements) {
10285 int SumV1Indices = 0, SumV2Indices = 0;
10286 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10287 if (SVOp->getMask()[i] >= NumElements)
10289 else if (SVOp->getMask()[i] >= 0)
10291 if (SumV2Indices < SumV1Indices) {
10292 return DAG.getCommutedVectorShuffle(*SVOp);
10293 } else if (SumV2Indices == SumV1Indices) {
10294 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10295 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10296 if (SVOp->getMask()[i] >= NumElements)
10297 NumV2OddIndices += i % 2;
10298 else if (SVOp->getMask()[i] >= 0)
10299 NumV1OddIndices += i % 2;
10300 if (NumV2OddIndices < NumV1OddIndices)
10301 return DAG.getCommutedVectorShuffle(*SVOp);
10306 // For each vector width, delegate to a specialized lowering routine.
10307 if (VT.getSizeInBits() == 128)
10308 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10310 if (VT.getSizeInBits() == 256)
10311 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10313 // Force AVX-512 vectors to be scalarized for now.
10314 // FIXME: Implement AVX-512 support!
10315 if (VT.getSizeInBits() == 512)
10316 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10318 llvm_unreachable("Unimplemented!");
10321 // This function assumes its argument is a BUILD_VECTOR of constants or
10322 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10324 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10325 unsigned &MaskValue) {
10327 unsigned NumElems = BuildVector->getNumOperands();
10328 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10329 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10330 unsigned NumElemsInLane = NumElems / NumLanes;
10332 // Blend for v16i16 should be symetric for the both lanes.
10333 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10334 SDValue EltCond = BuildVector->getOperand(i);
10335 SDValue SndLaneEltCond =
10336 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10338 int Lane1Cond = -1, Lane2Cond = -1;
10339 if (isa<ConstantSDNode>(EltCond))
10340 Lane1Cond = !isZero(EltCond);
10341 if (isa<ConstantSDNode>(SndLaneEltCond))
10342 Lane2Cond = !isZero(SndLaneEltCond);
10344 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10345 // Lane1Cond != 0, means we want the first argument.
10346 // Lane1Cond == 0, means we want the second argument.
10347 // The encoding of this argument is 0 for the first argument, 1
10348 // for the second. Therefore, invert the condition.
10349 MaskValue |= !Lane1Cond << i;
10350 else if (Lane1Cond < 0)
10351 MaskValue |= !Lane2Cond << i;
10358 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10359 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10360 const X86Subtarget *Subtarget,
10361 SelectionDAG &DAG) {
10362 SDValue Cond = Op.getOperand(0);
10363 SDValue LHS = Op.getOperand(1);
10364 SDValue RHS = Op.getOperand(2);
10366 MVT VT = Op.getSimpleValueType();
10368 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10370 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10372 // Only non-legal VSELECTs reach this lowering, convert those into generic
10373 // shuffles and re-use the shuffle lowering path for blends.
10374 SmallVector<int, 32> Mask;
10375 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10376 SDValue CondElt = CondBV->getOperand(i);
10378 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10380 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10383 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10384 // A vselect where all conditions and data are constants can be optimized into
10385 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10386 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10387 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10388 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10391 // Try to lower this to a blend-style vector shuffle. This can handle all
10392 // constant condition cases.
10393 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10396 // Variable blends are only legal from SSE4.1 onward.
10397 if (!Subtarget->hasSSE41())
10400 // Only some types will be legal on some subtargets. If we can emit a legal
10401 // VSELECT-matching blend, return Op, and but if we need to expand, return
10403 switch (Op.getSimpleValueType().SimpleTy) {
10405 // Most of the vector types have blends past SSE4.1.
10409 // The byte blends for AVX vectors were introduced only in AVX2.
10410 if (Subtarget->hasAVX2())
10417 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10418 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10421 // FIXME: We should custom lower this by fixing the condition and using i8
10427 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10428 MVT VT = Op.getSimpleValueType();
10431 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10434 if (VT.getSizeInBits() == 8) {
10435 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10436 Op.getOperand(0), Op.getOperand(1));
10437 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10438 DAG.getValueType(VT));
10439 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10442 if (VT.getSizeInBits() == 16) {
10443 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10444 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10446 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10447 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10448 DAG.getNode(ISD::BITCAST, dl,
10451 Op.getOperand(1)));
10452 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10453 Op.getOperand(0), Op.getOperand(1));
10454 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10455 DAG.getValueType(VT));
10456 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10459 if (VT == MVT::f32) {
10460 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10461 // the result back to FR32 register. It's only worth matching if the
10462 // result has a single use which is a store or a bitcast to i32. And in
10463 // the case of a store, it's not worth it if the index is a constant 0,
10464 // because a MOVSSmr can be used instead, which is smaller and faster.
10465 if (!Op.hasOneUse())
10467 SDNode *User = *Op.getNode()->use_begin();
10468 if ((User->getOpcode() != ISD::STORE ||
10469 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10470 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10471 (User->getOpcode() != ISD::BITCAST ||
10472 User->getValueType(0) != MVT::i32))
10474 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10475 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10478 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10481 if (VT == MVT::i32 || VT == MVT::i64) {
10482 // ExtractPS/pextrq works with constant index.
10483 if (isa<ConstantSDNode>(Op.getOperand(1)))
10489 /// Extract one bit from mask vector, like v16i1 or v8i1.
10490 /// AVX-512 feature.
10492 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10493 SDValue Vec = Op.getOperand(0);
10495 MVT VecVT = Vec.getSimpleValueType();
10496 SDValue Idx = Op.getOperand(1);
10497 MVT EltVT = Op.getSimpleValueType();
10499 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10500 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10501 "Unexpected vector type in ExtractBitFromMaskVector");
10503 // variable index can't be handled in mask registers,
10504 // extend vector to VR512
10505 if (!isa<ConstantSDNode>(Idx)) {
10506 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10507 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10508 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10509 ExtVT.getVectorElementType(), Ext, Idx);
10510 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10513 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10514 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10515 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10516 rc = getRegClassFor(MVT::v16i1);
10517 unsigned MaxSift = rc->getSize()*8 - 1;
10518 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10519 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10520 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10521 DAG.getConstant(MaxSift, dl, MVT::i8));
10522 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10523 DAG.getIntPtrConstant(0, dl));
10527 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10528 SelectionDAG &DAG) const {
10530 SDValue Vec = Op.getOperand(0);
10531 MVT VecVT = Vec.getSimpleValueType();
10532 SDValue Idx = Op.getOperand(1);
10534 if (Op.getSimpleValueType() == MVT::i1)
10535 return ExtractBitFromMaskVector(Op, DAG);
10537 if (!isa<ConstantSDNode>(Idx)) {
10538 if (VecVT.is512BitVector() ||
10539 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10540 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10543 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10544 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10545 MaskEltVT.getSizeInBits());
10547 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10548 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10549 getZeroVector(MaskVT, Subtarget, DAG, dl),
10550 Idx, DAG.getConstant(0, dl, getPointerTy()));
10551 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10552 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10553 Perm, DAG.getConstant(0, dl, getPointerTy()));
10558 // If this is a 256-bit vector result, first extract the 128-bit vector and
10559 // then extract the element from the 128-bit vector.
10560 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10562 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10563 // Get the 128-bit vector.
10564 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10565 MVT EltVT = VecVT.getVectorElementType();
10567 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10569 //if (IdxVal >= NumElems/2)
10570 // IdxVal -= NumElems/2;
10571 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10572 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10573 DAG.getConstant(IdxVal, dl, MVT::i32));
10576 assert(VecVT.is128BitVector() && "Unexpected vector length");
10578 if (Subtarget->hasSSE41()) {
10579 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10584 MVT VT = Op.getSimpleValueType();
10585 // TODO: handle v16i8.
10586 if (VT.getSizeInBits() == 16) {
10587 SDValue Vec = Op.getOperand(0);
10588 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10590 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10591 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10592 DAG.getNode(ISD::BITCAST, dl,
10594 Op.getOperand(1)));
10595 // Transform it so it match pextrw which produces a 32-bit result.
10596 MVT EltVT = MVT::i32;
10597 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10598 Op.getOperand(0), Op.getOperand(1));
10599 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10600 DAG.getValueType(VT));
10601 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10604 if (VT.getSizeInBits() == 32) {
10605 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10609 // SHUFPS the element to the lowest double word, then movss.
10610 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10611 MVT VVT = Op.getOperand(0).getSimpleValueType();
10612 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10613 DAG.getUNDEF(VVT), Mask);
10614 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10615 DAG.getIntPtrConstant(0, dl));
10618 if (VT.getSizeInBits() == 64) {
10619 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10620 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10621 // to match extract_elt for f64.
10622 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10626 // UNPCKHPD the element to the lowest double word, then movsd.
10627 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10628 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10629 int Mask[2] = { 1, -1 };
10630 MVT VVT = Op.getOperand(0).getSimpleValueType();
10631 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10632 DAG.getUNDEF(VVT), Mask);
10633 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10634 DAG.getIntPtrConstant(0, dl));
10640 /// Insert one bit to mask vector, like v16i1 or v8i1.
10641 /// AVX-512 feature.
10643 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10645 SDValue Vec = Op.getOperand(0);
10646 SDValue Elt = Op.getOperand(1);
10647 SDValue Idx = Op.getOperand(2);
10648 MVT VecVT = Vec.getSimpleValueType();
10650 if (!isa<ConstantSDNode>(Idx)) {
10651 // Non constant index. Extend source and destination,
10652 // insert element and then truncate the result.
10653 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10654 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10655 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10656 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10657 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10658 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10661 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10662 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10663 if (Vec.getOpcode() == ISD::UNDEF)
10664 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10665 DAG.getConstant(IdxVal, dl, MVT::i8));
10666 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10667 unsigned MaxSift = rc->getSize()*8 - 1;
10668 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10669 DAG.getConstant(MaxSift, dl, MVT::i8));
10670 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10671 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10672 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10675 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10676 SelectionDAG &DAG) const {
10677 MVT VT = Op.getSimpleValueType();
10678 MVT EltVT = VT.getVectorElementType();
10680 if (EltVT == MVT::i1)
10681 return InsertBitToMaskVector(Op, DAG);
10684 SDValue N0 = Op.getOperand(0);
10685 SDValue N1 = Op.getOperand(1);
10686 SDValue N2 = Op.getOperand(2);
10687 if (!isa<ConstantSDNode>(N2))
10689 auto *N2C = cast<ConstantSDNode>(N2);
10690 unsigned IdxVal = N2C->getZExtValue();
10692 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10693 // into that, and then insert the subvector back into the result.
10694 if (VT.is256BitVector() || VT.is512BitVector()) {
10695 // With a 256-bit vector, we can insert into the zero element efficiently
10696 // using a blend if we have AVX or AVX2 and the right data type.
10697 if (VT.is256BitVector() && IdxVal == 0) {
10698 // TODO: It is worthwhile to cast integer to floating point and back
10699 // and incur a domain crossing penalty if that's what we'll end up
10700 // doing anyway after extracting to a 128-bit vector.
10701 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10702 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10703 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10704 N2 = DAG.getIntPtrConstant(1, dl);
10705 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10709 // Get the desired 128-bit vector chunk.
10710 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10712 // Insert the element into the desired chunk.
10713 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10714 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10716 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10717 DAG.getConstant(IdxIn128, dl, MVT::i32));
10719 // Insert the changed part back into the bigger vector
10720 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10722 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10724 if (Subtarget->hasSSE41()) {
10725 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10727 if (VT == MVT::v8i16) {
10728 Opc = X86ISD::PINSRW;
10730 assert(VT == MVT::v16i8);
10731 Opc = X86ISD::PINSRB;
10734 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10736 if (N1.getValueType() != MVT::i32)
10737 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10738 if (N2.getValueType() != MVT::i32)
10739 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10740 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10743 if (EltVT == MVT::f32) {
10744 // Bits [7:6] of the constant are the source select. This will always be
10745 // zero here. The DAG Combiner may combine an extract_elt index into
10746 // these bits. For example (insert (extract, 3), 2) could be matched by
10747 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10748 // Bits [5:4] of the constant are the destination select. This is the
10749 // value of the incoming immediate.
10750 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10751 // combine either bitwise AND or insert of float 0.0 to set these bits.
10753 const Function *F = DAG.getMachineFunction().getFunction();
10754 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10755 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10756 // If this is an insertion of 32-bits into the low 32-bits of
10757 // a vector, we prefer to generate a blend with immediate rather
10758 // than an insertps. Blends are simpler operations in hardware and so
10759 // will always have equal or better performance than insertps.
10760 // But if optimizing for size and there's a load folding opportunity,
10761 // generate insertps because blendps does not have a 32-bit memory
10763 N2 = DAG.getIntPtrConstant(1, dl);
10764 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10765 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10767 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10768 // Create this as a scalar to vector..
10769 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10770 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10773 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10774 // PINSR* works with constant index.
10779 if (EltVT == MVT::i8)
10782 if (EltVT.getSizeInBits() == 16) {
10783 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10784 // as its second argument.
10785 if (N1.getValueType() != MVT::i32)
10786 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10787 if (N2.getValueType() != MVT::i32)
10788 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10789 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10794 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10796 MVT OpVT = Op.getSimpleValueType();
10798 // If this is a 256-bit vector result, first insert into a 128-bit
10799 // vector and then insert into the 256-bit vector.
10800 if (!OpVT.is128BitVector()) {
10801 // Insert into a 128-bit vector.
10802 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10803 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10804 OpVT.getVectorNumElements() / SizeFactor);
10806 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10808 // Insert the 128-bit vector.
10809 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10812 if (OpVT == MVT::v1i64 &&
10813 Op.getOperand(0).getValueType() == MVT::i64)
10814 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10816 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10817 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10818 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10819 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10822 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10823 // a simple subregister reference or explicit instructions to grab
10824 // upper bits of a vector.
10825 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10826 SelectionDAG &DAG) {
10828 SDValue In = Op.getOperand(0);
10829 SDValue Idx = Op.getOperand(1);
10830 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10831 MVT ResVT = Op.getSimpleValueType();
10832 MVT InVT = In.getSimpleValueType();
10834 if (Subtarget->hasFp256()) {
10835 if (ResVT.is128BitVector() &&
10836 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10837 isa<ConstantSDNode>(Idx)) {
10838 return Extract128BitVector(In, IdxVal, DAG, dl);
10840 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10841 isa<ConstantSDNode>(Idx)) {
10842 return Extract256BitVector(In, IdxVal, DAG, dl);
10848 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10849 // simple superregister reference or explicit instructions to insert
10850 // the upper bits of a vector.
10851 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10852 SelectionDAG &DAG) {
10853 if (!Subtarget->hasAVX())
10857 SDValue Vec = Op.getOperand(0);
10858 SDValue SubVec = Op.getOperand(1);
10859 SDValue Idx = Op.getOperand(2);
10861 if (!isa<ConstantSDNode>(Idx))
10864 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10865 MVT OpVT = Op.getSimpleValueType();
10866 MVT SubVecVT = SubVec.getSimpleValueType();
10868 // Fold two 16-byte subvector loads into one 32-byte load:
10869 // (insert_subvector (insert_subvector undef, (load addr), 0),
10870 // (load addr + 16), Elts/2)
10872 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10873 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10874 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10875 !Subtarget->isUnalignedMem32Slow()) {
10876 SDValue SubVec2 = Vec.getOperand(1);
10877 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10878 if (Idx2->getZExtValue() == 0) {
10879 SDValue Ops[] = { SubVec2, SubVec };
10880 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10887 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10888 SubVecVT.is128BitVector())
10889 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10891 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10892 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10894 if (OpVT.getVectorElementType() == MVT::i1) {
10895 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10897 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10898 SDValue Undef = DAG.getUNDEF(OpVT);
10899 unsigned NumElems = OpVT.getVectorNumElements();
10900 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10902 if (IdxVal == OpVT.getVectorNumElements() / 2) {
10903 // Zero upper bits of the Vec
10904 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10905 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10907 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10909 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10910 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10913 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10915 // Zero upper bits of the Vec2
10916 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10917 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10918 // Zero lower bits of the Vec
10919 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10920 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10921 // Merge them together
10922 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10928 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10929 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10930 // one of the above mentioned nodes. It has to be wrapped because otherwise
10931 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10932 // be used to form addressing mode. These wrapped nodes will be selected
10935 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10936 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10938 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10939 // global base reg.
10940 unsigned char OpFlag = 0;
10941 unsigned WrapperKind = X86ISD::Wrapper;
10942 CodeModel::Model M = DAG.getTarget().getCodeModel();
10944 if (Subtarget->isPICStyleRIPRel() &&
10945 (M == CodeModel::Small || M == CodeModel::Kernel))
10946 WrapperKind = X86ISD::WrapperRIP;
10947 else if (Subtarget->isPICStyleGOT())
10948 OpFlag = X86II::MO_GOTOFF;
10949 else if (Subtarget->isPICStyleStubPIC())
10950 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10952 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10953 CP->getAlignment(),
10954 CP->getOffset(), OpFlag);
10956 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10957 // With PIC, the address is actually $g + Offset.
10959 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10960 DAG.getNode(X86ISD::GlobalBaseReg,
10961 SDLoc(), getPointerTy()),
10968 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10969 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10971 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10972 // global base reg.
10973 unsigned char OpFlag = 0;
10974 unsigned WrapperKind = X86ISD::Wrapper;
10975 CodeModel::Model M = DAG.getTarget().getCodeModel();
10977 if (Subtarget->isPICStyleRIPRel() &&
10978 (M == CodeModel::Small || M == CodeModel::Kernel))
10979 WrapperKind = X86ISD::WrapperRIP;
10980 else if (Subtarget->isPICStyleGOT())
10981 OpFlag = X86II::MO_GOTOFF;
10982 else if (Subtarget->isPICStyleStubPIC())
10983 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10985 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10988 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10990 // With PIC, the address is actually $g + Offset.
10992 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10993 DAG.getNode(X86ISD::GlobalBaseReg,
10994 SDLoc(), getPointerTy()),
11001 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11002 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11004 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11005 // global base reg.
11006 unsigned char OpFlag = 0;
11007 unsigned WrapperKind = X86ISD::Wrapper;
11008 CodeModel::Model M = DAG.getTarget().getCodeModel();
11010 if (Subtarget->isPICStyleRIPRel() &&
11011 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11012 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11013 OpFlag = X86II::MO_GOTPCREL;
11014 WrapperKind = X86ISD::WrapperRIP;
11015 } else if (Subtarget->isPICStyleGOT()) {
11016 OpFlag = X86II::MO_GOT;
11017 } else if (Subtarget->isPICStyleStubPIC()) {
11018 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11019 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11020 OpFlag = X86II::MO_DARWIN_NONLAZY;
11023 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11026 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11028 // With PIC, the address is actually $g + Offset.
11029 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11030 !Subtarget->is64Bit()) {
11031 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11032 DAG.getNode(X86ISD::GlobalBaseReg,
11033 SDLoc(), getPointerTy()),
11037 // For symbols that require a load from a stub to get the address, emit the
11039 if (isGlobalStubReference(OpFlag))
11040 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11041 MachinePointerInfo::getGOT(), false, false, false, 0);
11047 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11048 // Create the TargetBlockAddressAddress node.
11049 unsigned char OpFlags =
11050 Subtarget->ClassifyBlockAddressReference();
11051 CodeModel::Model M = DAG.getTarget().getCodeModel();
11052 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11053 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11055 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11058 if (Subtarget->isPICStyleRIPRel() &&
11059 (M == CodeModel::Small || M == CodeModel::Kernel))
11060 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11062 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11064 // With PIC, the address is actually $g + Offset.
11065 if (isGlobalRelativeToPICBase(OpFlags)) {
11066 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11067 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11075 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11076 int64_t Offset, SelectionDAG &DAG) const {
11077 // Create the TargetGlobalAddress node, folding in the constant
11078 // offset if it is legal.
11079 unsigned char OpFlags =
11080 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11081 CodeModel::Model M = DAG.getTarget().getCodeModel();
11083 if (OpFlags == X86II::MO_NO_FLAG &&
11084 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11085 // A direct static reference to a global.
11086 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11089 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11092 if (Subtarget->isPICStyleRIPRel() &&
11093 (M == CodeModel::Small || M == CodeModel::Kernel))
11094 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11096 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11098 // With PIC, the address is actually $g + Offset.
11099 if (isGlobalRelativeToPICBase(OpFlags)) {
11100 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11101 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11105 // For globals that require a load from a stub to get the address, emit the
11107 if (isGlobalStubReference(OpFlags))
11108 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11109 MachinePointerInfo::getGOT(), false, false, false, 0);
11111 // If there was a non-zero offset that we didn't fold, create an explicit
11112 // addition for it.
11114 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11115 DAG.getConstant(Offset, dl, getPointerTy()));
11121 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11122 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11123 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11124 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11128 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11129 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11130 unsigned char OperandFlags, bool LocalDynamic = false) {
11131 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11132 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11134 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11135 GA->getValueType(0),
11139 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11143 SDValue Ops[] = { Chain, TGA, *InFlag };
11144 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11146 SDValue Ops[] = { Chain, TGA };
11147 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11150 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11151 MFI->setAdjustsStack(true);
11152 MFI->setHasCalls(true);
11154 SDValue Flag = Chain.getValue(1);
11155 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11158 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11160 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11163 SDLoc dl(GA); // ? function entry point might be better
11164 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11165 DAG.getNode(X86ISD::GlobalBaseReg,
11166 SDLoc(), PtrVT), InFlag);
11167 InFlag = Chain.getValue(1);
11169 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11172 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11174 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11176 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11177 X86::RAX, X86II::MO_TLSGD);
11180 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11186 // Get the start address of the TLS block for this module.
11187 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11188 .getInfo<X86MachineFunctionInfo>();
11189 MFI->incNumLocalDynamicTLSAccesses();
11193 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11194 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11197 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11198 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11199 InFlag = Chain.getValue(1);
11200 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11201 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11204 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11208 unsigned char OperandFlags = X86II::MO_DTPOFF;
11209 unsigned WrapperKind = X86ISD::Wrapper;
11210 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11211 GA->getValueType(0),
11212 GA->getOffset(), OperandFlags);
11213 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11215 // Add x@dtpoff with the base.
11216 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11219 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11220 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11221 const EVT PtrVT, TLSModel::Model model,
11222 bool is64Bit, bool isPIC) {
11225 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11226 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11227 is64Bit ? 257 : 256));
11229 SDValue ThreadPointer =
11230 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11231 MachinePointerInfo(Ptr), false, false, false, 0);
11233 unsigned char OperandFlags = 0;
11234 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11236 unsigned WrapperKind = X86ISD::Wrapper;
11237 if (model == TLSModel::LocalExec) {
11238 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11239 } else if (model == TLSModel::InitialExec) {
11241 OperandFlags = X86II::MO_GOTTPOFF;
11242 WrapperKind = X86ISD::WrapperRIP;
11244 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11247 llvm_unreachable("Unexpected model");
11250 // emit "addl x@ntpoff,%eax" (local exec)
11251 // or "addl x@indntpoff,%eax" (initial exec)
11252 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11254 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11255 GA->getOffset(), OperandFlags);
11256 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11258 if (model == TLSModel::InitialExec) {
11259 if (isPIC && !is64Bit) {
11260 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11261 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11265 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11266 MachinePointerInfo::getGOT(), false, false, false, 0);
11269 // The address of the thread local variable is the add of the thread
11270 // pointer with the offset of the variable.
11271 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11275 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11277 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11278 const GlobalValue *GV = GA->getGlobal();
11280 if (Subtarget->isTargetELF()) {
11281 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11284 case TLSModel::GeneralDynamic:
11285 if (Subtarget->is64Bit())
11286 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11287 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11288 case TLSModel::LocalDynamic:
11289 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11290 Subtarget->is64Bit());
11291 case TLSModel::InitialExec:
11292 case TLSModel::LocalExec:
11293 return LowerToTLSExecModel(
11294 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11295 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11297 llvm_unreachable("Unknown TLS model.");
11300 if (Subtarget->isTargetDarwin()) {
11301 // Darwin only has one model of TLS. Lower to that.
11302 unsigned char OpFlag = 0;
11303 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11304 X86ISD::WrapperRIP : X86ISD::Wrapper;
11306 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11307 // global base reg.
11308 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11309 !Subtarget->is64Bit();
11311 OpFlag = X86II::MO_TLVP_PIC_BASE;
11313 OpFlag = X86II::MO_TLVP;
11315 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11316 GA->getValueType(0),
11317 GA->getOffset(), OpFlag);
11318 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11320 // With PIC32, the address is actually $g + Offset.
11322 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11323 DAG.getNode(X86ISD::GlobalBaseReg,
11324 SDLoc(), getPointerTy()),
11327 // Lowering the machine isd will make sure everything is in the right
11329 SDValue Chain = DAG.getEntryNode();
11330 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11331 SDValue Args[] = { Chain, Offset };
11332 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11334 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11335 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11336 MFI->setAdjustsStack(true);
11338 // And our return value (tls address) is in the standard call return value
11340 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11341 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11342 Chain.getValue(1));
11345 if (Subtarget->isTargetKnownWindowsMSVC() ||
11346 Subtarget->isTargetWindowsGNU()) {
11347 // Just use the implicit TLS architecture
11348 // Need to generate someting similar to:
11349 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11351 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11352 // mov rcx, qword [rdx+rcx*8]
11353 // mov eax, .tls$:tlsvar
11354 // [rax+rcx] contains the address
11355 // Windows 64bit: gs:0x58
11356 // Windows 32bit: fs:__tls_array
11359 SDValue Chain = DAG.getEntryNode();
11361 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11362 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11363 // use its literal value of 0x2C.
11364 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11365 ? Type::getInt8PtrTy(*DAG.getContext(),
11367 : Type::getInt32PtrTy(*DAG.getContext(),
11371 Subtarget->is64Bit()
11372 ? DAG.getIntPtrConstant(0x58, dl)
11373 : (Subtarget->isTargetWindowsGNU()
11374 ? DAG.getIntPtrConstant(0x2C, dl)
11375 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11377 SDValue ThreadPointer =
11378 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11379 MachinePointerInfo(Ptr), false, false, false, 0);
11381 // Load the _tls_index variable
11382 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11383 if (Subtarget->is64Bit())
11384 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11385 IDX, MachinePointerInfo(), MVT::i32,
11386 false, false, false, 0);
11388 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11389 false, false, false, 0);
11391 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11393 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11395 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11396 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11397 false, false, false, 0);
11399 // Get the offset of start of .tls section
11400 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11401 GA->getValueType(0),
11402 GA->getOffset(), X86II::MO_SECREL);
11403 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11405 // The address of the thread local variable is the add of the thread
11406 // pointer with the offset of the variable.
11407 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11410 llvm_unreachable("TLS not implemented for this target.");
11413 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11414 /// and take a 2 x i32 value to shift plus a shift amount.
11415 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11416 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11417 MVT VT = Op.getSimpleValueType();
11418 unsigned VTBits = VT.getSizeInBits();
11420 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11421 SDValue ShOpLo = Op.getOperand(0);
11422 SDValue ShOpHi = Op.getOperand(1);
11423 SDValue ShAmt = Op.getOperand(2);
11424 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11425 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11427 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11428 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11429 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11430 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11431 : DAG.getConstant(0, dl, VT);
11433 SDValue Tmp2, Tmp3;
11434 if (Op.getOpcode() == ISD::SHL_PARTS) {
11435 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11436 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11438 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11439 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11442 // If the shift amount is larger or equal than the width of a part we can't
11443 // rely on the results of shld/shrd. Insert a test and select the appropriate
11444 // values for large shift amounts.
11445 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11446 DAG.getConstant(VTBits, dl, MVT::i8));
11447 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11448 AndNode, DAG.getConstant(0, dl, MVT::i8));
11451 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11452 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11453 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11455 if (Op.getOpcode() == ISD::SHL_PARTS) {
11456 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11457 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11459 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11460 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11463 SDValue Ops[2] = { Lo, Hi };
11464 return DAG.getMergeValues(Ops, dl);
11467 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11468 SelectionDAG &DAG) const {
11469 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11472 if (SrcVT.isVector()) {
11473 if (SrcVT.getVectorElementType() == MVT::i1) {
11474 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11475 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11476 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11477 Op.getOperand(0)));
11482 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11483 "Unknown SINT_TO_FP to lower!");
11485 // These are really Legal; return the operand so the caller accepts it as
11487 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11489 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11490 Subtarget->is64Bit()) {
11494 unsigned Size = SrcVT.getSizeInBits()/8;
11495 MachineFunction &MF = DAG.getMachineFunction();
11496 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11497 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11498 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11500 MachinePointerInfo::getFixedStack(SSFI),
11502 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11505 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11507 SelectionDAG &DAG) const {
11511 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11513 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11515 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11517 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11519 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11520 MachineMemOperand *MMO;
11522 int SSFI = FI->getIndex();
11524 DAG.getMachineFunction()
11525 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11526 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11528 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11529 StackSlot = StackSlot.getOperand(1);
11531 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11532 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11534 Tys, Ops, SrcVT, MMO);
11537 Chain = Result.getValue(1);
11538 SDValue InFlag = Result.getValue(2);
11540 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11541 // shouldn't be necessary except that RFP cannot be live across
11542 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11543 MachineFunction &MF = DAG.getMachineFunction();
11544 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11545 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11546 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11547 Tys = DAG.getVTList(MVT::Other);
11549 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11551 MachineMemOperand *MMO =
11552 DAG.getMachineFunction()
11553 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11554 MachineMemOperand::MOStore, SSFISize, SSFISize);
11556 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11557 Ops, Op.getValueType(), MMO);
11558 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11559 MachinePointerInfo::getFixedStack(SSFI),
11560 false, false, false, 0);
11566 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11567 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11568 SelectionDAG &DAG) const {
11569 // This algorithm is not obvious. Here it is what we're trying to output:
11572 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11573 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11575 haddpd %xmm0, %xmm0
11577 pshufd $0x4e, %xmm0, %xmm1
11583 LLVMContext *Context = DAG.getContext();
11585 // Build some magic constants.
11586 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11587 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11588 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11590 SmallVector<Constant*,2> CV1;
11592 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11593 APInt(64, 0x4330000000000000ULL))));
11595 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11596 APInt(64, 0x4530000000000000ULL))));
11597 Constant *C1 = ConstantVector::get(CV1);
11598 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11600 // Load the 64-bit value into an XMM register.
11601 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11603 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11604 MachinePointerInfo::getConstantPool(),
11605 false, false, false, 16);
11606 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11607 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11610 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11611 MachinePointerInfo::getConstantPool(),
11612 false, false, false, 16);
11613 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11614 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11617 if (Subtarget->hasSSE3()) {
11618 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11619 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11621 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11622 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11624 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11625 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11629 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11630 DAG.getIntPtrConstant(0, dl));
11633 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11634 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11635 SelectionDAG &DAG) const {
11637 // FP constant to bias correct the final result.
11638 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11641 // Load the 32-bit value into an XMM register.
11642 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11645 // Zero out the upper parts of the register.
11646 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11648 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11649 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11650 DAG.getIntPtrConstant(0, dl));
11652 // Or the load with the bias.
11653 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11654 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11655 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11656 MVT::v2f64, Load)),
11657 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11658 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11659 MVT::v2f64, Bias)));
11660 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11661 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11662 DAG.getIntPtrConstant(0, dl));
11664 // Subtract the bias.
11665 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11667 // Handle final rounding.
11668 EVT DestVT = Op.getValueType();
11670 if (DestVT.bitsLT(MVT::f64))
11671 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11672 DAG.getIntPtrConstant(0, dl));
11673 if (DestVT.bitsGT(MVT::f64))
11674 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11676 // Handle final rounding.
11680 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11681 const X86Subtarget &Subtarget) {
11682 // The algorithm is the following:
11683 // #ifdef __SSE4_1__
11684 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11685 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11686 // (uint4) 0x53000000, 0xaa);
11688 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11689 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11691 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11692 // return (float4) lo + fhi;
11695 SDValue V = Op->getOperand(0);
11696 EVT VecIntVT = V.getValueType();
11697 bool Is128 = VecIntVT == MVT::v4i32;
11698 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11699 // If we convert to something else than the supported type, e.g., to v4f64,
11701 if (VecFloatVT != Op->getValueType(0))
11704 unsigned NumElts = VecIntVT.getVectorNumElements();
11705 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11706 "Unsupported custom type");
11707 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11709 // In the #idef/#else code, we have in common:
11710 // - The vector of constants:
11716 // Create the splat vector for 0x4b000000.
11717 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11718 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11719 CstLow, CstLow, CstLow, CstLow};
11720 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11721 makeArrayRef(&CstLowArray[0], NumElts));
11722 // Create the splat vector for 0x53000000.
11723 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11724 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11725 CstHigh, CstHigh, CstHigh, CstHigh};
11726 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11727 makeArrayRef(&CstHighArray[0], NumElts));
11729 // Create the right shift.
11730 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11731 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11732 CstShift, CstShift, CstShift, CstShift};
11733 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11734 makeArrayRef(&CstShiftArray[0], NumElts));
11735 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11738 if (Subtarget.hasSSE41()) {
11739 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11740 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11741 SDValue VecCstLowBitcast =
11742 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11743 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11744 // Low will be bitcasted right away, so do not bother bitcasting back to its
11746 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11747 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11748 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11749 // (uint4) 0x53000000, 0xaa);
11750 SDValue VecCstHighBitcast =
11751 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11752 SDValue VecShiftBitcast =
11753 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11754 // High will be bitcasted right away, so do not bother bitcasting back to
11755 // its original type.
11756 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11757 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11759 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11760 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11761 CstMask, CstMask, CstMask);
11762 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11763 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11764 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11766 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11767 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11770 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11771 SDValue CstFAdd = DAG.getConstantFP(
11772 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11773 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11774 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11775 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11776 makeArrayRef(&CstFAddArray[0], NumElts));
11778 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11779 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11781 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11782 // return (float4) lo + fhi;
11783 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11784 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11787 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11788 SelectionDAG &DAG) const {
11789 SDValue N0 = Op.getOperand(0);
11790 MVT SVT = N0.getSimpleValueType();
11793 switch (SVT.SimpleTy) {
11795 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11800 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11801 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11802 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11806 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11809 if (Subtarget->hasAVX512())
11810 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11811 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11813 llvm_unreachable(nullptr);
11816 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11817 SelectionDAG &DAG) const {
11818 SDValue N0 = Op.getOperand(0);
11821 if (Op.getValueType().isVector())
11822 return lowerUINT_TO_FP_vec(Op, DAG);
11824 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11825 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11826 // the optimization here.
11827 if (DAG.SignBitIsZero(N0))
11828 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11830 MVT SrcVT = N0.getSimpleValueType();
11831 MVT DstVT = Op.getSimpleValueType();
11832 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11833 return LowerUINT_TO_FP_i64(Op, DAG);
11834 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11835 return LowerUINT_TO_FP_i32(Op, DAG);
11836 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11839 // Make a 64-bit buffer, and use it to build an FILD.
11840 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11841 if (SrcVT == MVT::i32) {
11842 SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11843 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11844 getPointerTy(), StackSlot, WordOff);
11845 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11846 StackSlot, MachinePointerInfo(),
11848 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11849 OffsetSlot, MachinePointerInfo(),
11851 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11855 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11856 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11857 StackSlot, MachinePointerInfo(),
11859 // For i64 source, we need to add the appropriate power of 2 if the input
11860 // was negative. This is the same as the optimization in
11861 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11862 // we must be careful to do the computation in x87 extended precision, not
11863 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11864 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11865 MachineMemOperand *MMO =
11866 DAG.getMachineFunction()
11867 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11868 MachineMemOperand::MOLoad, 8, 8);
11870 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11871 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11872 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11875 APInt FF(32, 0x5F800000ULL);
11877 // Check whether the sign bit is set.
11878 SDValue SignSet = DAG.getSetCC(dl,
11879 getSetCCResultType(*DAG.getContext(), MVT::i64),
11881 DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11883 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11884 SDValue FudgePtr = DAG.getConstantPool(
11885 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11888 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11889 SDValue Zero = DAG.getIntPtrConstant(0, dl);
11890 SDValue Four = DAG.getIntPtrConstant(4, dl);
11891 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11893 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11895 // Load the value out, extending it from f32 to f80.
11896 // FIXME: Avoid the extend by constructing the right constant pool?
11897 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11898 FudgePtr, MachinePointerInfo::getConstantPool(),
11899 MVT::f32, false, false, false, 4);
11900 // Extend everything to 80 bits to force it to be done on x87.
11901 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11902 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11903 DAG.getIntPtrConstant(0, dl));
11906 std::pair<SDValue,SDValue>
11907 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11908 bool IsSigned, bool IsReplace) const {
11911 EVT DstTy = Op.getValueType();
11913 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11914 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11918 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11919 DstTy.getSimpleVT() >= MVT::i16 &&
11920 "Unknown FP_TO_INT to lower!");
11922 // These are really Legal.
11923 if (DstTy == MVT::i32 &&
11924 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11925 return std::make_pair(SDValue(), SDValue());
11926 if (Subtarget->is64Bit() &&
11927 DstTy == MVT::i64 &&
11928 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11929 return std::make_pair(SDValue(), SDValue());
11931 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11932 // stack slot, or into the FTOL runtime function.
11933 MachineFunction &MF = DAG.getMachineFunction();
11934 unsigned MemSize = DstTy.getSizeInBits()/8;
11935 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11936 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11939 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11940 Opc = X86ISD::WIN_FTOL;
11942 switch (DstTy.getSimpleVT().SimpleTy) {
11943 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11944 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11945 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11946 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11949 SDValue Chain = DAG.getEntryNode();
11950 SDValue Value = Op.getOperand(0);
11951 EVT TheVT = Op.getOperand(0).getValueType();
11952 // FIXME This causes a redundant load/store if the SSE-class value is already
11953 // in memory, such as if it is on the callstack.
11954 if (isScalarFPTypeInSSEReg(TheVT)) {
11955 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11956 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11957 MachinePointerInfo::getFixedStack(SSFI),
11959 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11961 Chain, StackSlot, DAG.getValueType(TheVT)
11964 MachineMemOperand *MMO =
11965 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11966 MachineMemOperand::MOLoad, MemSize, MemSize);
11967 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11968 Chain = Value.getValue(1);
11969 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11970 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11973 MachineMemOperand *MMO =
11974 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11975 MachineMemOperand::MOStore, MemSize, MemSize);
11977 if (Opc != X86ISD::WIN_FTOL) {
11978 // Build the FP_TO_INT*_IN_MEM
11979 SDValue Ops[] = { Chain, Value, StackSlot };
11980 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11982 return std::make_pair(FIST, StackSlot);
11984 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11985 DAG.getVTList(MVT::Other, MVT::Glue),
11987 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11988 MVT::i32, ftol.getValue(1));
11989 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11990 MVT::i32, eax.getValue(2));
11991 SDValue Ops[] = { eax, edx };
11992 SDValue pair = IsReplace
11993 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11994 : DAG.getMergeValues(Ops, DL);
11995 return std::make_pair(pair, SDValue());
11999 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12000 const X86Subtarget *Subtarget) {
12001 MVT VT = Op->getSimpleValueType(0);
12002 SDValue In = Op->getOperand(0);
12003 MVT InVT = In.getSimpleValueType();
12006 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12007 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12009 // Optimize vectors in AVX mode:
12012 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12013 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12014 // Concat upper and lower parts.
12017 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12018 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12019 // Concat upper and lower parts.
12022 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12023 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12024 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12027 if (Subtarget->hasInt256())
12028 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12030 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12031 SDValue Undef = DAG.getUNDEF(InVT);
12032 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12033 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12034 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12036 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12037 VT.getVectorNumElements()/2);
12039 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12040 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12042 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12045 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12046 SelectionDAG &DAG) {
12047 MVT VT = Op->getSimpleValueType(0);
12048 SDValue In = Op->getOperand(0);
12049 MVT InVT = In.getSimpleValueType();
12051 unsigned int NumElts = VT.getVectorNumElements();
12052 if (NumElts != 8 && NumElts != 16)
12055 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12056 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12058 assert(InVT.getVectorElementType() == MVT::i1);
12059 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12061 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12063 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12065 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12066 if (VT.is512BitVector())
12068 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12071 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12072 SelectionDAG &DAG) {
12073 if (Subtarget->hasFp256()) {
12074 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12082 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12083 SelectionDAG &DAG) {
12085 MVT VT = Op.getSimpleValueType();
12086 SDValue In = Op.getOperand(0);
12087 MVT SVT = In.getSimpleValueType();
12089 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12090 return LowerZERO_EXTEND_AVX512(Op, DAG);
12092 if (Subtarget->hasFp256()) {
12093 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12098 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12099 VT.getVectorNumElements() != SVT.getVectorNumElements());
12103 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12105 MVT VT = Op.getSimpleValueType();
12106 SDValue In = Op.getOperand(0);
12107 MVT InVT = In.getSimpleValueType();
12109 if (VT == MVT::i1) {
12110 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12111 "Invalid scalar TRUNCATE operation");
12112 if (InVT.getSizeInBits() >= 32)
12114 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12115 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12117 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12118 "Invalid TRUNCATE operation");
12120 // move vector to mask - truncate solution for SKX
12121 if (VT.getVectorElementType() == MVT::i1) {
12122 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12123 Subtarget->hasBWI())
12124 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12125 if ((InVT.is256BitVector() || InVT.is128BitVector())
12126 && InVT.getScalarSizeInBits() <= 16 &&
12127 Subtarget->hasBWI() && Subtarget->hasVLX())
12128 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12129 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12130 Subtarget->hasDQI())
12131 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12132 if ((InVT.is256BitVector() || InVT.is128BitVector())
12133 && InVT.getScalarSizeInBits() >= 32 &&
12134 Subtarget->hasDQI() && Subtarget->hasVLX())
12135 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12137 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12138 if (VT.getVectorElementType().getSizeInBits() >=8)
12139 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12141 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12142 unsigned NumElts = InVT.getVectorNumElements();
12143 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12144 if (InVT.getSizeInBits() < 512) {
12145 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12146 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12151 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12152 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12153 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12156 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12157 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12158 if (Subtarget->hasInt256()) {
12159 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12160 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12161 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12163 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12164 DAG.getIntPtrConstant(0, DL));
12167 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12168 DAG.getIntPtrConstant(0, DL));
12169 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12170 DAG.getIntPtrConstant(2, DL));
12171 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12172 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12173 static const int ShufMask[] = {0, 2, 4, 6};
12174 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12177 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12178 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12179 if (Subtarget->hasInt256()) {
12180 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12182 SmallVector<SDValue,32> pshufbMask;
12183 for (unsigned i = 0; i < 2; ++i) {
12184 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12185 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12186 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12187 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12188 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12189 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12190 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12191 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12192 for (unsigned j = 0; j < 8; ++j)
12193 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12195 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12196 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12197 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12199 static const int ShufMask[] = {0, 2, -1, -1};
12200 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12202 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12203 DAG.getIntPtrConstant(0, DL));
12204 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12207 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12208 DAG.getIntPtrConstant(0, DL));
12210 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12211 DAG.getIntPtrConstant(4, DL));
12213 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12214 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12216 // The PSHUFB mask:
12217 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12218 -1, -1, -1, -1, -1, -1, -1, -1};
12220 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12221 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12222 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12224 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12225 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12227 // The MOVLHPS Mask:
12228 static const int ShufMask2[] = {0, 1, 4, 5};
12229 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12230 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12233 // Handle truncation of V256 to V128 using shuffles.
12234 if (!VT.is128BitVector() || !InVT.is256BitVector())
12237 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12239 unsigned NumElems = VT.getVectorNumElements();
12240 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12242 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12243 // Prepare truncation shuffle mask
12244 for (unsigned i = 0; i != NumElems; ++i)
12245 MaskVec[i] = i * 2;
12246 SDValue V = DAG.getVectorShuffle(NVT, DL,
12247 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12248 DAG.getUNDEF(NVT), &MaskVec[0]);
12249 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12250 DAG.getIntPtrConstant(0, DL));
12253 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12254 SelectionDAG &DAG) const {
12255 assert(!Op.getSimpleValueType().isVector());
12257 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12258 /*IsSigned=*/ true, /*IsReplace=*/ false);
12259 SDValue FIST = Vals.first, StackSlot = Vals.second;
12260 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12261 if (!FIST.getNode()) return Op;
12263 if (StackSlot.getNode())
12264 // Load the result.
12265 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12266 FIST, StackSlot, MachinePointerInfo(),
12267 false, false, false, 0);
12269 // The node is the result.
12273 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12274 SelectionDAG &DAG) const {
12275 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12276 /*IsSigned=*/ false, /*IsReplace=*/ false);
12277 SDValue FIST = Vals.first, StackSlot = Vals.second;
12278 assert(FIST.getNode() && "Unexpected failure");
12280 if (StackSlot.getNode())
12281 // Load the result.
12282 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12283 FIST, StackSlot, MachinePointerInfo(),
12284 false, false, false, 0);
12286 // The node is the result.
12290 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12292 MVT VT = Op.getSimpleValueType();
12293 SDValue In = Op.getOperand(0);
12294 MVT SVT = In.getSimpleValueType();
12296 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12298 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12299 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12300 In, DAG.getUNDEF(SVT)));
12303 /// The only differences between FABS and FNEG are the mask and the logic op.
12304 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12305 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12306 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12307 "Wrong opcode for lowering FABS or FNEG.");
12309 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12311 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12312 // into an FNABS. We'll lower the FABS after that if it is still in use.
12314 for (SDNode *User : Op->uses())
12315 if (User->getOpcode() == ISD::FNEG)
12318 SDValue Op0 = Op.getOperand(0);
12319 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12322 MVT VT = Op.getSimpleValueType();
12323 // Assume scalar op for initialization; update for vector if needed.
12324 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12325 // generate a 16-byte vector constant and logic op even for the scalar case.
12326 // Using a 16-byte mask allows folding the load of the mask with
12327 // the logic op, so it can save (~4 bytes) on code size.
12329 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12330 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12331 // decide if we should generate a 16-byte constant mask when we only need 4 or
12332 // 8 bytes for the scalar case.
12333 if (VT.isVector()) {
12334 EltVT = VT.getVectorElementType();
12335 NumElts = VT.getVectorNumElements();
12338 unsigned EltBits = EltVT.getSizeInBits();
12339 LLVMContext *Context = DAG.getContext();
12340 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12342 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12343 Constant *C = ConstantInt::get(*Context, MaskElt);
12344 C = ConstantVector::getSplat(NumElts, C);
12345 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12346 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12347 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12348 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12349 MachinePointerInfo::getConstantPool(),
12350 false, false, false, Alignment);
12352 if (VT.isVector()) {
12353 // For a vector, cast operands to a vector type, perform the logic op,
12354 // and cast the result back to the original value type.
12355 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12356 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12357 SDValue Operand = IsFNABS ?
12358 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12359 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12360 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12361 return DAG.getNode(ISD::BITCAST, dl, VT,
12362 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12365 // If not vector, then scalar.
12366 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12367 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12368 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12371 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12372 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12373 LLVMContext *Context = DAG.getContext();
12374 SDValue Op0 = Op.getOperand(0);
12375 SDValue Op1 = Op.getOperand(1);
12377 MVT VT = Op.getSimpleValueType();
12378 MVT SrcVT = Op1.getSimpleValueType();
12380 // If second operand is smaller, extend it first.
12381 if (SrcVT.bitsLT(VT)) {
12382 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12385 // And if it is bigger, shrink it first.
12386 if (SrcVT.bitsGT(VT)) {
12387 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12391 // At this point the operands and the result should have the same
12392 // type, and that won't be f80 since that is not custom lowered.
12394 const fltSemantics &Sem =
12395 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12396 const unsigned SizeInBits = VT.getSizeInBits();
12398 SmallVector<Constant *, 4> CV(
12399 VT == MVT::f64 ? 2 : 4,
12400 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12402 // First, clear all bits but the sign bit from the second operand (sign).
12403 CV[0] = ConstantFP::get(*Context,
12404 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12405 Constant *C = ConstantVector::get(CV);
12406 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12407 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12408 MachinePointerInfo::getConstantPool(),
12409 false, false, false, 16);
12410 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12412 // Next, clear the sign bit from the first operand (magnitude).
12413 // If it's a constant, we can clear it here.
12414 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12415 APFloat APF = Op0CN->getValueAPF();
12416 // If the magnitude is a positive zero, the sign bit alone is enough.
12417 if (APF.isPosZero())
12420 CV[0] = ConstantFP::get(*Context, APF);
12422 CV[0] = ConstantFP::get(
12424 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12426 C = ConstantVector::get(CV);
12427 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12428 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12429 MachinePointerInfo::getConstantPool(),
12430 false, false, false, 16);
12431 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12432 if (!isa<ConstantFPSDNode>(Op0))
12433 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12435 // OR the magnitude value with the sign bit.
12436 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12439 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12440 SDValue N0 = Op.getOperand(0);
12442 MVT VT = Op.getSimpleValueType();
12444 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12445 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12446 DAG.getConstant(1, dl, VT));
12447 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12450 // Check whether an OR'd tree is PTEST-able.
12451 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12452 SelectionDAG &DAG) {
12453 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12455 if (!Subtarget->hasSSE41())
12458 if (!Op->hasOneUse())
12461 SDNode *N = Op.getNode();
12464 SmallVector<SDValue, 8> Opnds;
12465 DenseMap<SDValue, unsigned> VecInMap;
12466 SmallVector<SDValue, 8> VecIns;
12467 EVT VT = MVT::Other;
12469 // Recognize a special case where a vector is casted into wide integer to
12471 Opnds.push_back(N->getOperand(0));
12472 Opnds.push_back(N->getOperand(1));
12474 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12475 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12476 // BFS traverse all OR'd operands.
12477 if (I->getOpcode() == ISD::OR) {
12478 Opnds.push_back(I->getOperand(0));
12479 Opnds.push_back(I->getOperand(1));
12480 // Re-evaluate the number of nodes to be traversed.
12481 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12485 // Quit if a non-EXTRACT_VECTOR_ELT
12486 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12489 // Quit if without a constant index.
12490 SDValue Idx = I->getOperand(1);
12491 if (!isa<ConstantSDNode>(Idx))
12494 SDValue ExtractedFromVec = I->getOperand(0);
12495 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12496 if (M == VecInMap.end()) {
12497 VT = ExtractedFromVec.getValueType();
12498 // Quit if not 128/256-bit vector.
12499 if (!VT.is128BitVector() && !VT.is256BitVector())
12501 // Quit if not the same type.
12502 if (VecInMap.begin() != VecInMap.end() &&
12503 VT != VecInMap.begin()->first.getValueType())
12505 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12506 VecIns.push_back(ExtractedFromVec);
12508 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12511 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12512 "Not extracted from 128-/256-bit vector.");
12514 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12516 for (DenseMap<SDValue, unsigned>::const_iterator
12517 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12518 // Quit if not all elements are used.
12519 if (I->second != FullMask)
12523 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12525 // Cast all vectors into TestVT for PTEST.
12526 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12527 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12529 // If more than one full vectors are evaluated, OR them first before PTEST.
12530 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12531 // Each iteration will OR 2 nodes and append the result until there is only
12532 // 1 node left, i.e. the final OR'd value of all vectors.
12533 SDValue LHS = VecIns[Slot];
12534 SDValue RHS = VecIns[Slot + 1];
12535 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12538 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12539 VecIns.back(), VecIns.back());
12542 /// \brief return true if \c Op has a use that doesn't just read flags.
12543 static bool hasNonFlagsUse(SDValue Op) {
12544 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12546 SDNode *User = *UI;
12547 unsigned UOpNo = UI.getOperandNo();
12548 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12549 // Look pass truncate.
12550 UOpNo = User->use_begin().getOperandNo();
12551 User = *User->use_begin();
12554 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12555 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12561 /// Emit nodes that will be selected as "test Op0,Op0", or something
12563 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12564 SelectionDAG &DAG) const {
12565 if (Op.getValueType() == MVT::i1) {
12566 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12567 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12568 DAG.getConstant(0, dl, MVT::i8));
12570 // CF and OF aren't always set the way we want. Determine which
12571 // of these we need.
12572 bool NeedCF = false;
12573 bool NeedOF = false;
12576 case X86::COND_A: case X86::COND_AE:
12577 case X86::COND_B: case X86::COND_BE:
12580 case X86::COND_G: case X86::COND_GE:
12581 case X86::COND_L: case X86::COND_LE:
12582 case X86::COND_O: case X86::COND_NO: {
12583 // Check if we really need to set the
12584 // Overflow flag. If NoSignedWrap is present
12585 // that is not actually needed.
12586 switch (Op->getOpcode()) {
12591 const BinaryWithFlagsSDNode *BinNode =
12592 cast<BinaryWithFlagsSDNode>(Op.getNode());
12593 if (BinNode->Flags.hasNoSignedWrap())
12603 // See if we can use the EFLAGS value from the operand instead of
12604 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12605 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12606 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12607 // Emit a CMP with 0, which is the TEST pattern.
12608 //if (Op.getValueType() == MVT::i1)
12609 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12610 // DAG.getConstant(0, MVT::i1));
12611 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12612 DAG.getConstant(0, dl, Op.getValueType()));
12614 unsigned Opcode = 0;
12615 unsigned NumOperands = 0;
12617 // Truncate operations may prevent the merge of the SETCC instruction
12618 // and the arithmetic instruction before it. Attempt to truncate the operands
12619 // of the arithmetic instruction and use a reduced bit-width instruction.
12620 bool NeedTruncation = false;
12621 SDValue ArithOp = Op;
12622 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12623 SDValue Arith = Op->getOperand(0);
12624 // Both the trunc and the arithmetic op need to have one user each.
12625 if (Arith->hasOneUse())
12626 switch (Arith.getOpcode()) {
12633 NeedTruncation = true;
12639 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12640 // which may be the result of a CAST. We use the variable 'Op', which is the
12641 // non-casted variable when we check for possible users.
12642 switch (ArithOp.getOpcode()) {
12644 // Due to an isel shortcoming, be conservative if this add is likely to be
12645 // selected as part of a load-modify-store instruction. When the root node
12646 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12647 // uses of other nodes in the match, such as the ADD in this case. This
12648 // leads to the ADD being left around and reselected, with the result being
12649 // two adds in the output. Alas, even if none our users are stores, that
12650 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12651 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12652 // climbing the DAG back to the root, and it doesn't seem to be worth the
12654 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12655 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12656 if (UI->getOpcode() != ISD::CopyToReg &&
12657 UI->getOpcode() != ISD::SETCC &&
12658 UI->getOpcode() != ISD::STORE)
12661 if (ConstantSDNode *C =
12662 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12663 // An add of one will be selected as an INC.
12664 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12665 Opcode = X86ISD::INC;
12670 // An add of negative one (subtract of one) will be selected as a DEC.
12671 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12672 Opcode = X86ISD::DEC;
12678 // Otherwise use a regular EFLAGS-setting add.
12679 Opcode = X86ISD::ADD;
12684 // If we have a constant logical shift that's only used in a comparison
12685 // against zero turn it into an equivalent AND. This allows turning it into
12686 // a TEST instruction later.
12687 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12688 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12689 EVT VT = Op.getValueType();
12690 unsigned BitWidth = VT.getSizeInBits();
12691 unsigned ShAmt = Op->getConstantOperandVal(1);
12692 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12694 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12695 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12696 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12697 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12699 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12700 DAG.getConstant(Mask, dl, VT));
12701 DAG.ReplaceAllUsesWith(Op, New);
12707 // If the primary and result isn't used, don't bother using X86ISD::AND,
12708 // because a TEST instruction will be better.
12709 if (!hasNonFlagsUse(Op))
12715 // Due to the ISEL shortcoming noted above, be conservative if this op is
12716 // likely to be selected as part of a load-modify-store instruction.
12717 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12718 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12719 if (UI->getOpcode() == ISD::STORE)
12722 // Otherwise use a regular EFLAGS-setting instruction.
12723 switch (ArithOp.getOpcode()) {
12724 default: llvm_unreachable("unexpected operator!");
12725 case ISD::SUB: Opcode = X86ISD::SUB; break;
12726 case ISD::XOR: Opcode = X86ISD::XOR; break;
12727 case ISD::AND: Opcode = X86ISD::AND; break;
12729 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12730 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12731 if (EFLAGS.getNode())
12734 Opcode = X86ISD::OR;
12748 return SDValue(Op.getNode(), 1);
12754 // If we found that truncation is beneficial, perform the truncation and
12756 if (NeedTruncation) {
12757 EVT VT = Op.getValueType();
12758 SDValue WideVal = Op->getOperand(0);
12759 EVT WideVT = WideVal.getValueType();
12760 unsigned ConvertedOp = 0;
12761 // Use a target machine opcode to prevent further DAGCombine
12762 // optimizations that may separate the arithmetic operations
12763 // from the setcc node.
12764 switch (WideVal.getOpcode()) {
12766 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12767 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12768 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12769 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12770 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12774 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12775 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12776 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12777 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12778 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12784 // Emit a CMP with 0, which is the TEST pattern.
12785 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12786 DAG.getConstant(0, dl, Op.getValueType()));
12788 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12789 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12791 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12792 DAG.ReplaceAllUsesWith(Op, New);
12793 return SDValue(New.getNode(), 1);
12796 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12798 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12799 SDLoc dl, SelectionDAG &DAG) const {
12800 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12801 if (C->getAPIntValue() == 0)
12802 return EmitTest(Op0, X86CC, dl, DAG);
12804 if (Op0.getValueType() == MVT::i1)
12805 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12808 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12809 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12810 // Do the comparison at i32 if it's smaller, besides the Atom case.
12811 // This avoids subregister aliasing issues. Keep the smaller reference
12812 // if we're optimizing for size, however, as that'll allow better folding
12813 // of memory operations.
12814 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12815 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12816 Attribute::MinSize) &&
12817 !Subtarget->isAtom()) {
12818 unsigned ExtendOp =
12819 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12820 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12821 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12823 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12824 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12825 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12827 return SDValue(Sub.getNode(), 1);
12829 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12832 /// Convert a comparison if required by the subtarget.
12833 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12834 SelectionDAG &DAG) const {
12835 // If the subtarget does not support the FUCOMI instruction, floating-point
12836 // comparisons have to be converted.
12837 if (Subtarget->hasCMov() ||
12838 Cmp.getOpcode() != X86ISD::CMP ||
12839 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12840 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12843 // The instruction selector will select an FUCOM instruction instead of
12844 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12845 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12846 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12848 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12849 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12850 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12851 DAG.getConstant(8, dl, MVT::i8));
12852 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12853 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12856 /// The minimum architected relative accuracy is 2^-12. We need one
12857 /// Newton-Raphson step to have a good float result (24 bits of precision).
12858 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12859 DAGCombinerInfo &DCI,
12860 unsigned &RefinementSteps,
12861 bool &UseOneConstNR) const {
12862 // FIXME: We should use instruction latency models to calculate the cost of
12863 // each potential sequence, but this is very hard to do reliably because
12864 // at least Intel's Core* chips have variable timing based on the number of
12865 // significant digits in the divisor and/or sqrt operand.
12866 if (!Subtarget->useSqrtEst())
12869 EVT VT = Op.getValueType();
12871 // SSE1 has rsqrtss and rsqrtps.
12872 // TODO: Add support for AVX512 (v16f32).
12873 // It is likely not profitable to do this for f64 because a double-precision
12874 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12875 // instructions: convert to single, rsqrtss, convert back to double, refine
12876 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12877 // along with FMA, this could be a throughput win.
12878 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12879 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12880 RefinementSteps = 1;
12881 UseOneConstNR = false;
12882 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12887 /// The minimum architected relative accuracy is 2^-12. We need one
12888 /// Newton-Raphson step to have a good float result (24 bits of precision).
12889 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12890 DAGCombinerInfo &DCI,
12891 unsigned &RefinementSteps) const {
12892 // FIXME: We should use instruction latency models to calculate the cost of
12893 // each potential sequence, but this is very hard to do reliably because
12894 // at least Intel's Core* chips have variable timing based on the number of
12895 // significant digits in the divisor.
12896 if (!Subtarget->useReciprocalEst())
12899 EVT VT = Op.getValueType();
12901 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12902 // TODO: Add support for AVX512 (v16f32).
12903 // It is likely not profitable to do this for f64 because a double-precision
12904 // reciprocal estimate with refinement on x86 prior to FMA requires
12905 // 15 instructions: convert to single, rcpss, convert back to double, refine
12906 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12907 // along with FMA, this could be a throughput win.
12908 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12909 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12910 RefinementSteps = ReciprocalEstimateRefinementSteps;
12911 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12916 /// If we have at least two divisions that use the same divisor, convert to
12917 /// multplication by a reciprocal. This may need to be adjusted for a given
12918 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12919 /// This is because we still need one division to calculate the reciprocal and
12920 /// then we need two multiplies by that reciprocal as replacements for the
12921 /// original divisions.
12922 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12923 return NumUsers > 1;
12926 static bool isAllOnes(SDValue V) {
12927 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12928 return C && C->isAllOnesValue();
12931 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12932 /// if it's possible.
12933 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12934 SDLoc dl, SelectionDAG &DAG) const {
12935 SDValue Op0 = And.getOperand(0);
12936 SDValue Op1 = And.getOperand(1);
12937 if (Op0.getOpcode() == ISD::TRUNCATE)
12938 Op0 = Op0.getOperand(0);
12939 if (Op1.getOpcode() == ISD::TRUNCATE)
12940 Op1 = Op1.getOperand(0);
12943 if (Op1.getOpcode() == ISD::SHL)
12944 std::swap(Op0, Op1);
12945 if (Op0.getOpcode() == ISD::SHL) {
12946 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12947 if (And00C->getZExtValue() == 1) {
12948 // If we looked past a truncate, check that it's only truncating away
12950 unsigned BitWidth = Op0.getValueSizeInBits();
12951 unsigned AndBitWidth = And.getValueSizeInBits();
12952 if (BitWidth > AndBitWidth) {
12954 DAG.computeKnownBits(Op0, Zeros, Ones);
12955 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12959 RHS = Op0.getOperand(1);
12961 } else if (Op1.getOpcode() == ISD::Constant) {
12962 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12963 uint64_t AndRHSVal = AndRHS->getZExtValue();
12964 SDValue AndLHS = Op0;
12966 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12967 LHS = AndLHS.getOperand(0);
12968 RHS = AndLHS.getOperand(1);
12971 // Use BT if the immediate can't be encoded in a TEST instruction.
12972 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12974 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12978 if (LHS.getNode()) {
12979 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12980 // instruction. Since the shift amount is in-range-or-undefined, we know
12981 // that doing a bittest on the i32 value is ok. We extend to i32 because
12982 // the encoding for the i16 version is larger than the i32 version.
12983 // Also promote i16 to i32 for performance / code size reason.
12984 if (LHS.getValueType() == MVT::i8 ||
12985 LHS.getValueType() == MVT::i16)
12986 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12988 // If the operand types disagree, extend the shift amount to match. Since
12989 // BT ignores high bits (like shifts) we can use anyextend.
12990 if (LHS.getValueType() != RHS.getValueType())
12991 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12993 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12994 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12995 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12996 DAG.getConstant(Cond, dl, MVT::i8), BT);
13002 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13004 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13009 // SSE Condition code mapping:
13018 switch (SetCCOpcode) {
13019 default: llvm_unreachable("Unexpected SETCC condition");
13021 case ISD::SETEQ: SSECC = 0; break;
13023 case ISD::SETGT: Swap = true; // Fallthrough
13025 case ISD::SETOLT: SSECC = 1; break;
13027 case ISD::SETGE: Swap = true; // Fallthrough
13029 case ISD::SETOLE: SSECC = 2; break;
13030 case ISD::SETUO: SSECC = 3; break;
13032 case ISD::SETNE: SSECC = 4; break;
13033 case ISD::SETULE: Swap = true; // Fallthrough
13034 case ISD::SETUGE: SSECC = 5; break;
13035 case ISD::SETULT: Swap = true; // Fallthrough
13036 case ISD::SETUGT: SSECC = 6; break;
13037 case ISD::SETO: SSECC = 7; break;
13039 case ISD::SETONE: SSECC = 8; break;
13042 std::swap(Op0, Op1);
13047 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13048 // ones, and then concatenate the result back.
13049 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13050 MVT VT = Op.getSimpleValueType();
13052 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13053 "Unsupported value type for operation");
13055 unsigned NumElems = VT.getVectorNumElements();
13057 SDValue CC = Op.getOperand(2);
13059 // Extract the LHS vectors
13060 SDValue LHS = Op.getOperand(0);
13061 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13062 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13064 // Extract the RHS vectors
13065 SDValue RHS = Op.getOperand(1);
13066 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13067 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13069 // Issue the operation on the smaller types and concatenate the result back
13070 MVT EltVT = VT.getVectorElementType();
13071 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13072 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13073 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13074 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13077 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13078 SDValue Op0 = Op.getOperand(0);
13079 SDValue Op1 = Op.getOperand(1);
13080 SDValue CC = Op.getOperand(2);
13081 MVT VT = Op.getSimpleValueType();
13084 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13085 "Unexpected type for boolean compare operation");
13086 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13087 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13088 DAG.getConstant(-1, dl, VT));
13089 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13090 DAG.getConstant(-1, dl, VT));
13091 switch (SetCCOpcode) {
13092 default: llvm_unreachable("Unexpected SETCC condition");
13094 // (x != y) -> ~(x ^ y)
13095 return DAG.getNode(ISD::XOR, dl, VT,
13096 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13097 DAG.getConstant(-1, dl, VT));
13099 // (x == y) -> (x ^ y)
13100 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13103 // (x > y) -> (x & ~y)
13104 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13107 // (x < y) -> (~x & y)
13108 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13111 // (x <= y) -> (~x | y)
13112 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13115 // (x >=y) -> (x | ~y)
13116 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13120 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13121 const X86Subtarget *Subtarget) {
13122 SDValue Op0 = Op.getOperand(0);
13123 SDValue Op1 = Op.getOperand(1);
13124 SDValue CC = Op.getOperand(2);
13125 MVT VT = Op.getSimpleValueType();
13128 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13129 Op.getValueType().getScalarType() == MVT::i1 &&
13130 "Cannot set masked compare for this operation");
13132 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13134 bool Unsigned = false;
13137 switch (SetCCOpcode) {
13138 default: llvm_unreachable("Unexpected SETCC condition");
13139 case ISD::SETNE: SSECC = 4; break;
13140 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13141 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13142 case ISD::SETLT: Swap = true; //fall-through
13143 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13144 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13145 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13146 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13147 case ISD::SETULE: Unsigned = true; //fall-through
13148 case ISD::SETLE: SSECC = 2; break;
13152 std::swap(Op0, Op1);
13154 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13155 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13156 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13157 DAG.getConstant(SSECC, dl, MVT::i8));
13160 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13161 /// operand \p Op1. If non-trivial (for example because it's not constant)
13162 /// return an empty value.
13163 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13165 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13169 MVT VT = Op1.getSimpleValueType();
13170 MVT EVT = VT.getVectorElementType();
13171 unsigned n = VT.getVectorNumElements();
13172 SmallVector<SDValue, 8> ULTOp1;
13174 for (unsigned i = 0; i < n; ++i) {
13175 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13176 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13179 // Avoid underflow.
13180 APInt Val = Elt->getAPIntValue();
13184 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13187 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13190 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13191 SelectionDAG &DAG) {
13192 SDValue Op0 = Op.getOperand(0);
13193 SDValue Op1 = Op.getOperand(1);
13194 SDValue CC = Op.getOperand(2);
13195 MVT VT = Op.getSimpleValueType();
13196 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13197 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13202 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13203 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13206 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13207 unsigned Opc = X86ISD::CMPP;
13208 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13209 assert(VT.getVectorNumElements() <= 16);
13210 Opc = X86ISD::CMPM;
13212 // In the two special cases we can't handle, emit two comparisons.
13215 unsigned CombineOpc;
13216 if (SetCCOpcode == ISD::SETUEQ) {
13217 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13219 assert(SetCCOpcode == ISD::SETONE);
13220 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13223 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13224 DAG.getConstant(CC0, dl, MVT::i8));
13225 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13226 DAG.getConstant(CC1, dl, MVT::i8));
13227 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13229 // Handle all other FP comparisons here.
13230 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13231 DAG.getConstant(SSECC, dl, MVT::i8));
13234 // Break 256-bit integer vector compare into smaller ones.
13235 if (VT.is256BitVector() && !Subtarget->hasInt256())
13236 return Lower256IntVSETCC(Op, DAG);
13238 EVT OpVT = Op1.getValueType();
13239 if (OpVT.getVectorElementType() == MVT::i1)
13240 return LowerBoolVSETCC_AVX512(Op, DAG);
13242 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13243 if (Subtarget->hasAVX512()) {
13244 if (Op1.getValueType().is512BitVector() ||
13245 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13246 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13247 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13249 // In AVX-512 architecture setcc returns mask with i1 elements,
13250 // But there is no compare instruction for i8 and i16 elements in KNL.
13251 // We are not talking about 512-bit operands in this case, these
13252 // types are illegal.
13254 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13255 OpVT.getVectorElementType().getSizeInBits() >= 8))
13256 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13257 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13260 // We are handling one of the integer comparisons here. Since SSE only has
13261 // GT and EQ comparisons for integer, swapping operands and multiple
13262 // operations may be required for some comparisons.
13264 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13265 bool Subus = false;
13267 switch (SetCCOpcode) {
13268 default: llvm_unreachable("Unexpected SETCC condition");
13269 case ISD::SETNE: Invert = true;
13270 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13271 case ISD::SETLT: Swap = true;
13272 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13273 case ISD::SETGE: Swap = true;
13274 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13275 Invert = true; break;
13276 case ISD::SETULT: Swap = true;
13277 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13278 FlipSigns = true; break;
13279 case ISD::SETUGE: Swap = true;
13280 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13281 FlipSigns = true; Invert = true; break;
13284 // Special case: Use min/max operations for SETULE/SETUGE
13285 MVT VET = VT.getVectorElementType();
13287 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13288 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13291 switch (SetCCOpcode) {
13293 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13294 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13297 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13300 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13301 if (!MinMax && hasSubus) {
13302 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13304 // t = psubus Op0, Op1
13305 // pcmpeq t, <0..0>
13306 switch (SetCCOpcode) {
13308 case ISD::SETULT: {
13309 // If the comparison is against a constant we can turn this into a
13310 // setule. With psubus, setule does not require a swap. This is
13311 // beneficial because the constant in the register is no longer
13312 // destructed as the destination so it can be hoisted out of a loop.
13313 // Only do this pre-AVX since vpcmp* is no longer destructive.
13314 if (Subtarget->hasAVX())
13316 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13317 if (ULEOp1.getNode()) {
13319 Subus = true; Invert = false; Swap = false;
13323 // Psubus is better than flip-sign because it requires no inversion.
13324 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13325 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13329 Opc = X86ISD::SUBUS;
13335 std::swap(Op0, Op1);
13337 // Check that the operation in question is available (most are plain SSE2,
13338 // but PCMPGTQ and PCMPEQQ have different requirements).
13339 if (VT == MVT::v2i64) {
13340 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13341 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13343 // First cast everything to the right type.
13344 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13345 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13347 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13348 // bits of the inputs before performing those operations. The lower
13349 // compare is always unsigned.
13352 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13354 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13355 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13356 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13357 Sign, Zero, Sign, Zero);
13359 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13360 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13362 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13363 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13364 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13366 // Create masks for only the low parts/high parts of the 64 bit integers.
13367 static const int MaskHi[] = { 1, 1, 3, 3 };
13368 static const int MaskLo[] = { 0, 0, 2, 2 };
13369 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13370 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13371 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13373 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13374 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13377 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13379 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13382 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13383 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13384 // pcmpeqd + pshufd + pand.
13385 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13387 // First cast everything to the right type.
13388 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13389 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13392 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13394 // Make sure the lower and upper halves are both all-ones.
13395 static const int Mask[] = { 1, 0, 3, 2 };
13396 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13397 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13400 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13402 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13406 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13407 // bits of the inputs before performing those operations.
13409 EVT EltVT = VT.getVectorElementType();
13410 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13412 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13413 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13416 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13418 // If the logical-not of the result is required, perform that now.
13420 Result = DAG.getNOT(dl, Result, VT);
13423 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13426 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13427 getZeroVector(VT, Subtarget, DAG, dl));
13432 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13434 MVT VT = Op.getSimpleValueType();
13436 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13438 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13439 && "SetCC type must be 8-bit or 1-bit integer");
13440 SDValue Op0 = Op.getOperand(0);
13441 SDValue Op1 = Op.getOperand(1);
13443 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13445 // Optimize to BT if possible.
13446 // Lower (X & (1 << N)) == 0 to BT(X, N).
13447 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13448 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13449 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13450 Op1.getOpcode() == ISD::Constant &&
13451 cast<ConstantSDNode>(Op1)->isNullValue() &&
13452 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13453 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13454 if (NewSetCC.getNode()) {
13456 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13461 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13463 if (Op1.getOpcode() == ISD::Constant &&
13464 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13465 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13466 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13468 // If the input is a setcc, then reuse the input setcc or use a new one with
13469 // the inverted condition.
13470 if (Op0.getOpcode() == X86ISD::SETCC) {
13471 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13472 bool Invert = (CC == ISD::SETNE) ^
13473 cast<ConstantSDNode>(Op1)->isNullValue();
13477 CCode = X86::GetOppositeBranchCondition(CCode);
13478 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13479 DAG.getConstant(CCode, dl, MVT::i8),
13480 Op0.getOperand(1));
13482 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13486 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13487 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13488 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13490 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13491 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13494 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13495 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13496 if (X86CC == X86::COND_INVALID)
13499 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13500 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13501 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13502 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13504 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13508 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13509 static bool isX86LogicalCmp(SDValue Op) {
13510 unsigned Opc = Op.getNode()->getOpcode();
13511 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13512 Opc == X86ISD::SAHF)
13514 if (Op.getResNo() == 1 &&
13515 (Opc == X86ISD::ADD ||
13516 Opc == X86ISD::SUB ||
13517 Opc == X86ISD::ADC ||
13518 Opc == X86ISD::SBB ||
13519 Opc == X86ISD::SMUL ||
13520 Opc == X86ISD::UMUL ||
13521 Opc == X86ISD::INC ||
13522 Opc == X86ISD::DEC ||
13523 Opc == X86ISD::OR ||
13524 Opc == X86ISD::XOR ||
13525 Opc == X86ISD::AND))
13528 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13534 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13535 if (V.getOpcode() != ISD::TRUNCATE)
13538 SDValue VOp0 = V.getOperand(0);
13539 unsigned InBits = VOp0.getValueSizeInBits();
13540 unsigned Bits = V.getValueSizeInBits();
13541 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13544 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13545 bool addTest = true;
13546 SDValue Cond = Op.getOperand(0);
13547 SDValue Op1 = Op.getOperand(1);
13548 SDValue Op2 = Op.getOperand(2);
13550 EVT VT = Op1.getValueType();
13553 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13554 // are available or VBLENDV if AVX is available.
13555 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13556 if (Cond.getOpcode() == ISD::SETCC &&
13557 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13558 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13559 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13560 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13561 int SSECC = translateX86FSETCC(
13562 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13565 if (Subtarget->hasAVX512()) {
13566 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13567 DAG.getConstant(SSECC, DL, MVT::i8));
13568 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13571 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13572 DAG.getConstant(SSECC, DL, MVT::i8));
13574 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13575 // of 3 logic instructions for size savings and potentially speed.
13576 // Unfortunately, there is no scalar form of VBLENDV.
13578 // If either operand is a constant, don't try this. We can expect to
13579 // optimize away at least one of the logic instructions later in that
13580 // case, so that sequence would be faster than a variable blend.
13582 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13583 // uses XMM0 as the selection register. That may need just as many
13584 // instructions as the AND/ANDN/OR sequence due to register moves, so
13587 if (Subtarget->hasAVX() &&
13588 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13590 // Convert to vectors, do a VSELECT, and convert back to scalar.
13591 // All of the conversions should be optimized away.
13593 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13594 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13595 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13596 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13598 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13599 VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13601 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13603 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13604 VSel, DAG.getIntPtrConstant(0, DL));
13606 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13607 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13608 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13612 if (Cond.getOpcode() == ISD::SETCC) {
13613 SDValue NewCond = LowerSETCC(Cond, DAG);
13614 if (NewCond.getNode())
13618 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13619 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13620 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13621 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13622 if (Cond.getOpcode() == X86ISD::SETCC &&
13623 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13624 isZero(Cond.getOperand(1).getOperand(1))) {
13625 SDValue Cmp = Cond.getOperand(1);
13627 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13629 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13630 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13631 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13633 SDValue CmpOp0 = Cmp.getOperand(0);
13634 // Apply further optimizations for special cases
13635 // (select (x != 0), -1, 0) -> neg & sbb
13636 // (select (x == 0), 0, -1) -> neg & sbb
13637 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13638 if (YC->isNullValue() &&
13639 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13640 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13641 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13642 DAG.getConstant(0, DL,
13643 CmpOp0.getValueType()),
13645 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13646 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13647 SDValue(Neg.getNode(), 1));
13651 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13652 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13653 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13655 SDValue Res = // Res = 0 or -1.
13656 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13657 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13659 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13660 Res = DAG.getNOT(DL, Res, Res.getValueType());
13662 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13663 if (!N2C || !N2C->isNullValue())
13664 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13669 // Look past (and (setcc_carry (cmp ...)), 1).
13670 if (Cond.getOpcode() == ISD::AND &&
13671 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13672 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13673 if (C && C->getAPIntValue() == 1)
13674 Cond = Cond.getOperand(0);
13677 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13678 // setting operand in place of the X86ISD::SETCC.
13679 unsigned CondOpcode = Cond.getOpcode();
13680 if (CondOpcode == X86ISD::SETCC ||
13681 CondOpcode == X86ISD::SETCC_CARRY) {
13682 CC = Cond.getOperand(0);
13684 SDValue Cmp = Cond.getOperand(1);
13685 unsigned Opc = Cmp.getOpcode();
13686 MVT VT = Op.getSimpleValueType();
13688 bool IllegalFPCMov = false;
13689 if (VT.isFloatingPoint() && !VT.isVector() &&
13690 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13691 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13693 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13694 Opc == X86ISD::BT) { // FIXME
13698 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13699 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13700 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13701 Cond.getOperand(0).getValueType() != MVT::i8)) {
13702 SDValue LHS = Cond.getOperand(0);
13703 SDValue RHS = Cond.getOperand(1);
13704 unsigned X86Opcode;
13707 switch (CondOpcode) {
13708 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13709 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13710 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13711 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13712 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13713 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13714 default: llvm_unreachable("unexpected overflowing operator");
13716 if (CondOpcode == ISD::UMULO)
13717 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13720 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13722 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13724 if (CondOpcode == ISD::UMULO)
13725 Cond = X86Op.getValue(2);
13727 Cond = X86Op.getValue(1);
13729 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13734 // Look pass the truncate if the high bits are known zero.
13735 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13736 Cond = Cond.getOperand(0);
13738 // We know the result of AND is compared against zero. Try to match
13740 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13741 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13742 if (NewSetCC.getNode()) {
13743 CC = NewSetCC.getOperand(0);
13744 Cond = NewSetCC.getOperand(1);
13751 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13752 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13755 // a < b ? -1 : 0 -> RES = ~setcc_carry
13756 // a < b ? 0 : -1 -> RES = setcc_carry
13757 // a >= b ? -1 : 0 -> RES = setcc_carry
13758 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13759 if (Cond.getOpcode() == X86ISD::SUB) {
13760 Cond = ConvertCmpIfNecessary(Cond, DAG);
13761 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13763 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13764 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13765 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13766 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13768 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13769 return DAG.getNOT(DL, Res, Res.getValueType());
13774 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13775 // widen the cmov and push the truncate through. This avoids introducing a new
13776 // branch during isel and doesn't add any extensions.
13777 if (Op.getValueType() == MVT::i8 &&
13778 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13779 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13780 if (T1.getValueType() == T2.getValueType() &&
13781 // Blacklist CopyFromReg to avoid partial register stalls.
13782 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13783 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13784 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13785 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13789 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13790 // condition is true.
13791 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13792 SDValue Ops[] = { Op2, Op1, CC, Cond };
13793 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13796 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13797 SelectionDAG &DAG) {
13798 MVT VT = Op->getSimpleValueType(0);
13799 SDValue In = Op->getOperand(0);
13800 MVT InVT = In.getSimpleValueType();
13801 MVT VTElt = VT.getVectorElementType();
13802 MVT InVTElt = InVT.getVectorElementType();
13806 if ((InVTElt == MVT::i1) &&
13807 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13808 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13810 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13811 VTElt.getSizeInBits() <= 16)) ||
13813 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13814 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13816 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13817 VTElt.getSizeInBits() >= 32))))
13818 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13820 unsigned int NumElts = VT.getVectorNumElements();
13822 if (NumElts != 8 && NumElts != 16)
13825 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13826 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13827 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13828 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13831 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13832 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13834 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13837 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13839 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13840 if (VT.is512BitVector())
13842 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13845 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13846 SelectionDAG &DAG) {
13847 MVT VT = Op->getSimpleValueType(0);
13848 SDValue In = Op->getOperand(0);
13849 MVT InVT = In.getSimpleValueType();
13852 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13853 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13855 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13856 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13857 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13860 if (Subtarget->hasInt256())
13861 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13863 // Optimize vectors in AVX mode
13864 // Sign extend v8i16 to v8i32 and
13867 // Divide input vector into two parts
13868 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13869 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13870 // concat the vectors to original VT
13872 unsigned NumElems = InVT.getVectorNumElements();
13873 SDValue Undef = DAG.getUNDEF(InVT);
13875 SmallVector<int,8> ShufMask1(NumElems, -1);
13876 for (unsigned i = 0; i != NumElems/2; ++i)
13879 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13881 SmallVector<int,8> ShufMask2(NumElems, -1);
13882 for (unsigned i = 0; i != NumElems/2; ++i)
13883 ShufMask2[i] = i + NumElems/2;
13885 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13887 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13888 VT.getVectorNumElements()/2);
13890 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13891 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13893 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13896 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13897 // may emit an illegal shuffle but the expansion is still better than scalar
13898 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13899 // we'll emit a shuffle and a arithmetic shift.
13900 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13901 // TODO: It is possible to support ZExt by zeroing the undef values during
13902 // the shuffle phase or after the shuffle.
13903 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13904 SelectionDAG &DAG) {
13905 MVT RegVT = Op.getSimpleValueType();
13906 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13907 assert(RegVT.isInteger() &&
13908 "We only custom lower integer vector sext loads.");
13910 // Nothing useful we can do without SSE2 shuffles.
13911 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13913 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13915 EVT MemVT = Ld->getMemoryVT();
13916 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13917 unsigned RegSz = RegVT.getSizeInBits();
13919 ISD::LoadExtType Ext = Ld->getExtensionType();
13921 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13922 && "Only anyext and sext are currently implemented.");
13923 assert(MemVT != RegVT && "Cannot extend to the same type");
13924 assert(MemVT.isVector() && "Must load a vector from memory");
13926 unsigned NumElems = RegVT.getVectorNumElements();
13927 unsigned MemSz = MemVT.getSizeInBits();
13928 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13930 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13931 // The only way in which we have a legal 256-bit vector result but not the
13932 // integer 256-bit operations needed to directly lower a sextload is if we
13933 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13934 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13935 // correctly legalized. We do this late to allow the canonical form of
13936 // sextload to persist throughout the rest of the DAG combiner -- it wants
13937 // to fold together any extensions it can, and so will fuse a sign_extend
13938 // of an sextload into a sextload targeting a wider value.
13940 if (MemSz == 128) {
13941 // Just switch this to a normal load.
13942 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13943 "it must be a legal 128-bit vector "
13945 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13946 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13947 Ld->isInvariant(), Ld->getAlignment());
13949 assert(MemSz < 128 &&
13950 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13951 // Do an sext load to a 128-bit vector type. We want to use the same
13952 // number of elements, but elements half as wide. This will end up being
13953 // recursively lowered by this routine, but will succeed as we definitely
13954 // have all the necessary features if we're using AVX1.
13956 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13957 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13959 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13960 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13961 Ld->isNonTemporal(), Ld->isInvariant(),
13962 Ld->getAlignment());
13965 // Replace chain users with the new chain.
13966 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13967 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13969 // Finally, do a normal sign-extend to the desired register.
13970 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13973 // All sizes must be a power of two.
13974 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13975 "Non-power-of-two elements are not custom lowered!");
13977 // Attempt to load the original value using scalar loads.
13978 // Find the largest scalar type that divides the total loaded size.
13979 MVT SclrLoadTy = MVT::i8;
13980 for (MVT Tp : MVT::integer_valuetypes()) {
13981 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13986 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13987 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13989 SclrLoadTy = MVT::f64;
13991 // Calculate the number of scalar loads that we need to perform
13992 // in order to load our vector from memory.
13993 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13995 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13996 "Can only lower sext loads with a single scalar load!");
13998 unsigned loadRegZize = RegSz;
13999 if (Ext == ISD::SEXTLOAD && RegSz == 256)
14002 // Represent our vector as a sequence of elements which are the
14003 // largest scalar that we can load.
14004 EVT LoadUnitVecVT = EVT::getVectorVT(
14005 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14007 // Represent the data using the same element type that is stored in
14008 // memory. In practice, we ''widen'' MemVT.
14010 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14011 loadRegZize / MemVT.getScalarType().getSizeInBits());
14013 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14014 "Invalid vector type");
14016 // We can't shuffle using an illegal type.
14017 assert(TLI.isTypeLegal(WideVecVT) &&
14018 "We only lower types that form legal widened vector types");
14020 SmallVector<SDValue, 8> Chains;
14021 SDValue Ptr = Ld->getBasePtr();
14022 SDValue Increment =
14023 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14024 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14026 for (unsigned i = 0; i < NumLoads; ++i) {
14027 // Perform a single load.
14028 SDValue ScalarLoad =
14029 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14030 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14031 Ld->getAlignment());
14032 Chains.push_back(ScalarLoad.getValue(1));
14033 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14034 // another round of DAGCombining.
14036 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14038 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14039 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14041 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14044 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14046 // Bitcast the loaded value to a vector of the original element type, in
14047 // the size of the target vector type.
14048 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14049 unsigned SizeRatio = RegSz / MemSz;
14051 if (Ext == ISD::SEXTLOAD) {
14052 // If we have SSE4.1, we can directly emit a VSEXT node.
14053 if (Subtarget->hasSSE41()) {
14054 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14055 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14059 // Otherwise we'll shuffle the small elements in the high bits of the
14060 // larger type and perform an arithmetic shift. If the shift is not legal
14061 // it's better to scalarize.
14062 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14063 "We can't implement a sext load without an arithmetic right shift!");
14065 // Redistribute the loaded elements into the different locations.
14066 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14067 for (unsigned i = 0; i != NumElems; ++i)
14068 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14070 SDValue Shuff = DAG.getVectorShuffle(
14071 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14073 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14075 // Build the arithmetic shift.
14076 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14077 MemVT.getVectorElementType().getSizeInBits();
14079 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14080 DAG.getConstant(Amt, dl, RegVT));
14082 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14086 // Redistribute the loaded elements into the different locations.
14087 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14088 for (unsigned i = 0; i != NumElems; ++i)
14089 ShuffleVec[i * SizeRatio] = i;
14091 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14092 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14094 // Bitcast to the requested type.
14095 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14096 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14100 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14101 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14102 // from the AND / OR.
14103 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14104 Opc = Op.getOpcode();
14105 if (Opc != ISD::OR && Opc != ISD::AND)
14107 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14108 Op.getOperand(0).hasOneUse() &&
14109 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14110 Op.getOperand(1).hasOneUse());
14113 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14114 // 1 and that the SETCC node has a single use.
14115 static bool isXor1OfSetCC(SDValue Op) {
14116 if (Op.getOpcode() != ISD::XOR)
14118 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14119 if (N1C && N1C->getAPIntValue() == 1) {
14120 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14121 Op.getOperand(0).hasOneUse();
14126 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14127 bool addTest = true;
14128 SDValue Chain = Op.getOperand(0);
14129 SDValue Cond = Op.getOperand(1);
14130 SDValue Dest = Op.getOperand(2);
14133 bool Inverted = false;
14135 if (Cond.getOpcode() == ISD::SETCC) {
14136 // Check for setcc([su]{add,sub,mul}o == 0).
14137 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14138 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14139 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14140 Cond.getOperand(0).getResNo() == 1 &&
14141 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14142 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14143 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14144 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14145 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14146 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14148 Cond = Cond.getOperand(0);
14150 SDValue NewCond = LowerSETCC(Cond, DAG);
14151 if (NewCond.getNode())
14156 // FIXME: LowerXALUO doesn't handle these!!
14157 else if (Cond.getOpcode() == X86ISD::ADD ||
14158 Cond.getOpcode() == X86ISD::SUB ||
14159 Cond.getOpcode() == X86ISD::SMUL ||
14160 Cond.getOpcode() == X86ISD::UMUL)
14161 Cond = LowerXALUO(Cond, DAG);
14164 // Look pass (and (setcc_carry (cmp ...)), 1).
14165 if (Cond.getOpcode() == ISD::AND &&
14166 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14167 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14168 if (C && C->getAPIntValue() == 1)
14169 Cond = Cond.getOperand(0);
14172 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14173 // setting operand in place of the X86ISD::SETCC.
14174 unsigned CondOpcode = Cond.getOpcode();
14175 if (CondOpcode == X86ISD::SETCC ||
14176 CondOpcode == X86ISD::SETCC_CARRY) {
14177 CC = Cond.getOperand(0);
14179 SDValue Cmp = Cond.getOperand(1);
14180 unsigned Opc = Cmp.getOpcode();
14181 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14182 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14186 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14190 // These can only come from an arithmetic instruction with overflow,
14191 // e.g. SADDO, UADDO.
14192 Cond = Cond.getNode()->getOperand(1);
14198 CondOpcode = Cond.getOpcode();
14199 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14200 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14201 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14202 Cond.getOperand(0).getValueType() != MVT::i8)) {
14203 SDValue LHS = Cond.getOperand(0);
14204 SDValue RHS = Cond.getOperand(1);
14205 unsigned X86Opcode;
14208 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14209 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14211 switch (CondOpcode) {
14212 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14214 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14216 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14219 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14220 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14222 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14224 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14227 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14228 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14229 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14230 default: llvm_unreachable("unexpected overflowing operator");
14233 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14234 if (CondOpcode == ISD::UMULO)
14235 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14238 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14240 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14242 if (CondOpcode == ISD::UMULO)
14243 Cond = X86Op.getValue(2);
14245 Cond = X86Op.getValue(1);
14247 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14251 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14252 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14253 if (CondOpc == ISD::OR) {
14254 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14255 // two branches instead of an explicit OR instruction with a
14257 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14258 isX86LogicalCmp(Cmp)) {
14259 CC = Cond.getOperand(0).getOperand(0);
14260 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14261 Chain, Dest, CC, Cmp);
14262 CC = Cond.getOperand(1).getOperand(0);
14266 } else { // ISD::AND
14267 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14268 // two branches instead of an explicit AND instruction with a
14269 // separate test. However, we only do this if this block doesn't
14270 // have a fall-through edge, because this requires an explicit
14271 // jmp when the condition is false.
14272 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14273 isX86LogicalCmp(Cmp) &&
14274 Op.getNode()->hasOneUse()) {
14275 X86::CondCode CCode =
14276 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14277 CCode = X86::GetOppositeBranchCondition(CCode);
14278 CC = DAG.getConstant(CCode, dl, MVT::i8);
14279 SDNode *User = *Op.getNode()->use_begin();
14280 // Look for an unconditional branch following this conditional branch.
14281 // We need this because we need to reverse the successors in order
14282 // to implement FCMP_OEQ.
14283 if (User->getOpcode() == ISD::BR) {
14284 SDValue FalseBB = User->getOperand(1);
14286 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14287 assert(NewBR == User);
14291 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14292 Chain, Dest, CC, Cmp);
14293 X86::CondCode CCode =
14294 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14295 CCode = X86::GetOppositeBranchCondition(CCode);
14296 CC = DAG.getConstant(CCode, dl, MVT::i8);
14302 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14303 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14304 // It should be transformed during dag combiner except when the condition
14305 // is set by a arithmetics with overflow node.
14306 X86::CondCode CCode =
14307 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14308 CCode = X86::GetOppositeBranchCondition(CCode);
14309 CC = DAG.getConstant(CCode, dl, MVT::i8);
14310 Cond = Cond.getOperand(0).getOperand(1);
14312 } else if (Cond.getOpcode() == ISD::SETCC &&
14313 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14314 // For FCMP_OEQ, we can emit
14315 // two branches instead of an explicit AND instruction with a
14316 // separate test. However, we only do this if this block doesn't
14317 // have a fall-through edge, because this requires an explicit
14318 // jmp when the condition is false.
14319 if (Op.getNode()->hasOneUse()) {
14320 SDNode *User = *Op.getNode()->use_begin();
14321 // Look for an unconditional branch following this conditional branch.
14322 // We need this because we need to reverse the successors in order
14323 // to implement FCMP_OEQ.
14324 if (User->getOpcode() == ISD::BR) {
14325 SDValue FalseBB = User->getOperand(1);
14327 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14328 assert(NewBR == User);
14332 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14333 Cond.getOperand(0), Cond.getOperand(1));
14334 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14335 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14336 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14337 Chain, Dest, CC, Cmp);
14338 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14343 } else if (Cond.getOpcode() == ISD::SETCC &&
14344 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14345 // For FCMP_UNE, we can emit
14346 // two branches instead of an explicit AND instruction with a
14347 // separate test. However, we only do this if this block doesn't
14348 // have a fall-through edge, because this requires an explicit
14349 // jmp when the condition is false.
14350 if (Op.getNode()->hasOneUse()) {
14351 SDNode *User = *Op.getNode()->use_begin();
14352 // Look for an unconditional branch following this conditional branch.
14353 // We need this because we need to reverse the successors in order
14354 // to implement FCMP_UNE.
14355 if (User->getOpcode() == ISD::BR) {
14356 SDValue FalseBB = User->getOperand(1);
14358 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14359 assert(NewBR == User);
14362 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14363 Cond.getOperand(0), Cond.getOperand(1));
14364 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14365 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14366 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14367 Chain, Dest, CC, Cmp);
14368 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14378 // Look pass the truncate if the high bits are known zero.
14379 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14380 Cond = Cond.getOperand(0);
14382 // We know the result of AND is compared against zero. Try to match
14384 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14385 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14386 if (NewSetCC.getNode()) {
14387 CC = NewSetCC.getOperand(0);
14388 Cond = NewSetCC.getOperand(1);
14395 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14396 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14397 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14399 Cond = ConvertCmpIfNecessary(Cond, DAG);
14400 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14401 Chain, Dest, CC, Cond);
14404 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14405 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14406 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14407 // that the guard pages used by the OS virtual memory manager are allocated in
14408 // correct sequence.
14410 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14411 SelectionDAG &DAG) const {
14412 MachineFunction &MF = DAG.getMachineFunction();
14413 bool SplitStack = MF.shouldSplitStack();
14414 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14420 SDNode* Node = Op.getNode();
14422 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14423 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14424 " not tell us which reg is the stack pointer!");
14425 EVT VT = Node->getValueType(0);
14426 SDValue Tmp1 = SDValue(Node, 0);
14427 SDValue Tmp2 = SDValue(Node, 1);
14428 SDValue Tmp3 = Node->getOperand(2);
14429 SDValue Chain = Tmp1.getOperand(0);
14431 // Chain the dynamic stack allocation so that it doesn't modify the stack
14432 // pointer when other instructions are using the stack.
14433 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14436 SDValue Size = Tmp2.getOperand(1);
14437 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14438 Chain = SP.getValue(1);
14439 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14440 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14441 unsigned StackAlign = TFI.getStackAlignment();
14442 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14443 if (Align > StackAlign)
14444 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14445 DAG.getConstant(-(uint64_t)Align, dl, VT));
14446 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14448 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14449 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14452 SDValue Ops[2] = { Tmp1, Tmp2 };
14453 return DAG.getMergeValues(Ops, dl);
14457 SDValue Chain = Op.getOperand(0);
14458 SDValue Size = Op.getOperand(1);
14459 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14460 EVT VT = Op.getNode()->getValueType(0);
14462 bool Is64Bit = Subtarget->is64Bit();
14463 EVT SPTy = getPointerTy();
14466 MachineRegisterInfo &MRI = MF.getRegInfo();
14469 // The 64 bit implementation of segmented stacks needs to clobber both r10
14470 // r11. This makes it impossible to use it along with nested parameters.
14471 const Function *F = MF.getFunction();
14473 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14475 if (I->hasNestAttr())
14476 report_fatal_error("Cannot use segmented stacks with functions that "
14477 "have nested arguments.");
14480 const TargetRegisterClass *AddrRegClass =
14481 getRegClassFor(getPointerTy());
14482 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14483 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14484 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14485 DAG.getRegister(Vreg, SPTy));
14486 SDValue Ops1[2] = { Value, Chain };
14487 return DAG.getMergeValues(Ops1, dl);
14490 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14492 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14493 Flag = Chain.getValue(1);
14494 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14496 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14498 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14499 unsigned SPReg = RegInfo->getStackRegister();
14500 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14501 Chain = SP.getValue(1);
14504 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14505 DAG.getConstant(-(uint64_t)Align, dl, VT));
14506 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14509 SDValue Ops1[2] = { SP, Chain };
14510 return DAG.getMergeValues(Ops1, dl);
14514 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14515 MachineFunction &MF = DAG.getMachineFunction();
14516 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14518 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14521 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14522 // vastart just stores the address of the VarArgsFrameIndex slot into the
14523 // memory location argument.
14524 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14526 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14527 MachinePointerInfo(SV), false, false, 0);
14531 // gp_offset (0 - 6 * 8)
14532 // fp_offset (48 - 48 + 8 * 16)
14533 // overflow_arg_area (point to parameters coming in memory).
14535 SmallVector<SDValue, 8> MemOps;
14536 SDValue FIN = Op.getOperand(1);
14538 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14539 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14541 FIN, MachinePointerInfo(SV), false, false, 0);
14542 MemOps.push_back(Store);
14545 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14546 FIN, DAG.getIntPtrConstant(4, DL));
14547 Store = DAG.getStore(Op.getOperand(0), DL,
14548 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14550 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14551 MemOps.push_back(Store);
14553 // Store ptr to overflow_arg_area
14554 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14555 FIN, DAG.getIntPtrConstant(4, DL));
14556 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14558 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14559 MachinePointerInfo(SV, 8),
14561 MemOps.push_back(Store);
14563 // Store ptr to reg_save_area.
14564 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14565 FIN, DAG.getIntPtrConstant(8, DL));
14566 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14568 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14569 MachinePointerInfo(SV, 16), false, false, 0);
14570 MemOps.push_back(Store);
14571 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14574 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14575 assert(Subtarget->is64Bit() &&
14576 "LowerVAARG only handles 64-bit va_arg!");
14577 assert((Subtarget->isTargetLinux() ||
14578 Subtarget->isTargetDarwin()) &&
14579 "Unhandled target in LowerVAARG");
14580 assert(Op.getNode()->getNumOperands() == 4);
14581 SDValue Chain = Op.getOperand(0);
14582 SDValue SrcPtr = Op.getOperand(1);
14583 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14584 unsigned Align = Op.getConstantOperandVal(3);
14587 EVT ArgVT = Op.getNode()->getValueType(0);
14588 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14589 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14592 // Decide which area this value should be read from.
14593 // TODO: Implement the AMD64 ABI in its entirety. This simple
14594 // selection mechanism works only for the basic types.
14595 if (ArgVT == MVT::f80) {
14596 llvm_unreachable("va_arg for f80 not yet implemented");
14597 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14598 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14599 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14600 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14602 llvm_unreachable("Unhandled argument type in LowerVAARG");
14605 if (ArgMode == 2) {
14606 // Sanity Check: Make sure using fp_offset makes sense.
14607 assert(!Subtarget->useSoftFloat() &&
14608 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14609 Attribute::NoImplicitFloat)) &&
14610 Subtarget->hasSSE1());
14613 // Insert VAARG_64 node into the DAG
14614 // VAARG_64 returns two values: Variable Argument Address, Chain
14615 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14616 DAG.getConstant(ArgMode, dl, MVT::i8),
14617 DAG.getConstant(Align, dl, MVT::i32)};
14618 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14619 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14620 VTs, InstOps, MVT::i64,
14621 MachinePointerInfo(SV),
14623 /*Volatile=*/false,
14625 /*WriteMem=*/true);
14626 Chain = VAARG.getValue(1);
14628 // Load the next argument and return it
14629 return DAG.getLoad(ArgVT, dl,
14632 MachinePointerInfo(),
14633 false, false, false, 0);
14636 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14637 SelectionDAG &DAG) {
14638 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14639 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14640 SDValue Chain = Op.getOperand(0);
14641 SDValue DstPtr = Op.getOperand(1);
14642 SDValue SrcPtr = Op.getOperand(2);
14643 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14644 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14647 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14648 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14650 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14653 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14654 // amount is a constant. Takes immediate version of shift as input.
14655 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14656 SDValue SrcOp, uint64_t ShiftAmt,
14657 SelectionDAG &DAG) {
14658 MVT ElementType = VT.getVectorElementType();
14660 // Fold this packed shift into its first operand if ShiftAmt is 0.
14664 // Check for ShiftAmt >= element width
14665 if (ShiftAmt >= ElementType.getSizeInBits()) {
14666 if (Opc == X86ISD::VSRAI)
14667 ShiftAmt = ElementType.getSizeInBits() - 1;
14669 return DAG.getConstant(0, dl, VT);
14672 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14673 && "Unknown target vector shift-by-constant node");
14675 // Fold this packed vector shift into a build vector if SrcOp is a
14676 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14677 if (VT == SrcOp.getSimpleValueType() &&
14678 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14679 SmallVector<SDValue, 8> Elts;
14680 unsigned NumElts = SrcOp->getNumOperands();
14681 ConstantSDNode *ND;
14684 default: llvm_unreachable(nullptr);
14685 case X86ISD::VSHLI:
14686 for (unsigned i=0; i!=NumElts; ++i) {
14687 SDValue CurrentOp = SrcOp->getOperand(i);
14688 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14689 Elts.push_back(CurrentOp);
14692 ND = cast<ConstantSDNode>(CurrentOp);
14693 const APInt &C = ND->getAPIntValue();
14694 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14697 case X86ISD::VSRLI:
14698 for (unsigned i=0; i!=NumElts; ++i) {
14699 SDValue CurrentOp = SrcOp->getOperand(i);
14700 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14701 Elts.push_back(CurrentOp);
14704 ND = cast<ConstantSDNode>(CurrentOp);
14705 const APInt &C = ND->getAPIntValue();
14706 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14709 case X86ISD::VSRAI:
14710 for (unsigned i=0; i!=NumElts; ++i) {
14711 SDValue CurrentOp = SrcOp->getOperand(i);
14712 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14713 Elts.push_back(CurrentOp);
14716 ND = cast<ConstantSDNode>(CurrentOp);
14717 const APInt &C = ND->getAPIntValue();
14718 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14723 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14726 return DAG.getNode(Opc, dl, VT, SrcOp,
14727 DAG.getConstant(ShiftAmt, dl, MVT::i8));
14730 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14731 // may or may not be a constant. Takes immediate version of shift as input.
14732 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14733 SDValue SrcOp, SDValue ShAmt,
14734 SelectionDAG &DAG) {
14735 MVT SVT = ShAmt.getSimpleValueType();
14736 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14738 // Catch shift-by-constant.
14739 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14740 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14741 CShAmt->getZExtValue(), DAG);
14743 // Change opcode to non-immediate version
14745 default: llvm_unreachable("Unknown target vector shift node");
14746 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14747 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14748 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14751 const X86Subtarget &Subtarget =
14752 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14753 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14754 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14755 // Let the shuffle legalizer expand this shift amount node.
14756 SDValue Op0 = ShAmt.getOperand(0);
14757 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14758 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14760 // Need to build a vector containing shift amount.
14761 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14762 SmallVector<SDValue, 4> ShOps;
14763 ShOps.push_back(ShAmt);
14764 if (SVT == MVT::i32) {
14765 ShOps.push_back(DAG.getConstant(0, dl, SVT));
14766 ShOps.push_back(DAG.getUNDEF(SVT));
14768 ShOps.push_back(DAG.getUNDEF(SVT));
14770 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14771 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14774 // The return type has to be a 128-bit type with the same element
14775 // type as the input type.
14776 MVT EltVT = VT.getVectorElementType();
14777 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14779 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14780 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14783 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14784 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14785 /// necessary casting for \p Mask when lowering masking intrinsics.
14786 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14787 SDValue PreservedSrc,
14788 const X86Subtarget *Subtarget,
14789 SelectionDAG &DAG) {
14790 EVT VT = Op.getValueType();
14791 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14792 MVT::i1, VT.getVectorNumElements());
14793 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14794 Mask.getValueType().getSizeInBits());
14797 assert(MaskVT.isSimple() && "invalid mask type");
14799 if (isAllOnes(Mask))
14802 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14803 // are extracted by EXTRACT_SUBVECTOR.
14804 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14805 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14806 DAG.getIntPtrConstant(0, dl));
14808 switch (Op.getOpcode()) {
14810 case X86ISD::PCMPEQM:
14811 case X86ISD::PCMPGTM:
14813 case X86ISD::CMPMU:
14814 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14816 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14817 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14818 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14821 /// \brief Creates an SDNode for a predicated scalar operation.
14822 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14823 /// The mask is comming as MVT::i8 and it should be truncated
14824 /// to MVT::i1 while lowering masking intrinsics.
14825 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14826 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14827 /// a scalar instruction.
14828 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14829 SDValue PreservedSrc,
14830 const X86Subtarget *Subtarget,
14831 SelectionDAG &DAG) {
14832 if (isAllOnes(Mask))
14835 EVT VT = Op.getValueType();
14837 // The mask should be of type MVT::i1
14838 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14840 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14841 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14842 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14845 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14846 SelectionDAG &DAG) {
14848 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14849 EVT VT = Op.getValueType();
14850 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14852 switch(IntrData->Type) {
14853 case INTR_TYPE_1OP:
14854 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14855 case INTR_TYPE_2OP:
14856 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14858 case INTR_TYPE_3OP:
14859 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14860 Op.getOperand(2), Op.getOperand(3));
14861 case INTR_TYPE_1OP_MASK_RM: {
14862 SDValue Src = Op.getOperand(1);
14863 SDValue Src0 = Op.getOperand(2);
14864 SDValue Mask = Op.getOperand(3);
14865 SDValue RoundingMode = Op.getOperand(4);
14866 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14868 Mask, Src0, Subtarget, DAG);
14870 case INTR_TYPE_SCALAR_MASK_RM: {
14871 SDValue Src1 = Op.getOperand(1);
14872 SDValue Src2 = Op.getOperand(2);
14873 SDValue Src0 = Op.getOperand(3);
14874 SDValue Mask = Op.getOperand(4);
14875 // There are 2 kinds of intrinsics in this group:
14876 // (1) With supress-all-exceptions (sae) - 6 operands
14877 // (2) With rounding mode and sae - 7 operands.
14878 if (Op.getNumOperands() == 6) {
14879 SDValue Sae = Op.getOperand(5);
14880 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14882 Mask, Src0, Subtarget, DAG);
14884 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14885 SDValue RoundingMode = Op.getOperand(5);
14886 SDValue Sae = Op.getOperand(6);
14887 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14888 RoundingMode, Sae),
14889 Mask, Src0, Subtarget, DAG);
14891 case INTR_TYPE_2OP_MASK: {
14892 SDValue Src1 = Op.getOperand(1);
14893 SDValue Src2 = Op.getOperand(2);
14894 SDValue PassThru = Op.getOperand(3);
14895 SDValue Mask = Op.getOperand(4);
14896 // We specify 2 possible opcodes for intrinsics with rounding modes.
14897 // First, we check if the intrinsic may have non-default rounding mode,
14898 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14899 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14900 if (IntrWithRoundingModeOpcode != 0) {
14901 SDValue Rnd = Op.getOperand(5);
14902 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14903 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14904 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14905 dl, Op.getValueType(),
14907 Mask, PassThru, Subtarget, DAG);
14910 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14912 Mask, PassThru, Subtarget, DAG);
14914 case FMA_OP_MASK: {
14915 SDValue Src1 = Op.getOperand(1);
14916 SDValue Src2 = Op.getOperand(2);
14917 SDValue Src3 = Op.getOperand(3);
14918 SDValue Mask = Op.getOperand(4);
14919 // We specify 2 possible opcodes for intrinsics with rounding modes.
14920 // First, we check if the intrinsic may have non-default rounding mode,
14921 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14922 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14923 if (IntrWithRoundingModeOpcode != 0) {
14924 SDValue Rnd = Op.getOperand(5);
14925 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14926 X86::STATIC_ROUNDING::CUR_DIRECTION)
14927 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14928 dl, Op.getValueType(),
14929 Src1, Src2, Src3, Rnd),
14930 Mask, Src1, Subtarget, DAG);
14932 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14933 dl, Op.getValueType(),
14935 Mask, Src1, Subtarget, DAG);
14938 case CMP_MASK_CC: {
14939 // Comparison intrinsics with masks.
14940 // Example of transformation:
14941 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14942 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14944 // (v8i1 (insert_subvector undef,
14945 // (v2i1 (and (PCMPEQM %a, %b),
14946 // (extract_subvector
14947 // (v8i1 (bitcast %mask)), 0))), 0))))
14948 EVT VT = Op.getOperand(1).getValueType();
14949 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14950 VT.getVectorNumElements());
14951 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14952 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14953 Mask.getValueType().getSizeInBits());
14955 if (IntrData->Type == CMP_MASK_CC) {
14956 SDValue CC = Op.getOperand(3);
14957 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14958 // We specify 2 possible opcodes for intrinsics with rounding modes.
14959 // First, we check if the intrinsic may have non-default rounding mode,
14960 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14961 if (IntrData->Opc1 != 0) {
14962 SDValue Rnd = Op.getOperand(5);
14963 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14964 X86::STATIC_ROUNDING::CUR_DIRECTION)
14965 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14966 Op.getOperand(2), CC, Rnd);
14968 //default rounding mode
14970 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14971 Op.getOperand(2), CC);
14974 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14975 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14978 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14979 DAG.getTargetConstant(0, dl,
14982 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14983 DAG.getUNDEF(BitcastVT), CmpMask,
14984 DAG.getIntPtrConstant(0, dl));
14985 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14987 case COMI: { // Comparison intrinsics
14988 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14989 SDValue LHS = Op.getOperand(1);
14990 SDValue RHS = Op.getOperand(2);
14991 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
14992 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14993 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14994 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14995 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
14996 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14999 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15000 Op.getOperand(1), Op.getOperand(2), DAG);
15002 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15003 Op.getSimpleValueType(),
15005 Op.getOperand(2), DAG),
15006 Op.getOperand(4), Op.getOperand(3), Subtarget,
15008 case COMPRESS_EXPAND_IN_REG: {
15009 SDValue Mask = Op.getOperand(3);
15010 SDValue DataToCompress = Op.getOperand(1);
15011 SDValue PassThru = Op.getOperand(2);
15012 if (isAllOnes(Mask)) // return data as is
15013 return Op.getOperand(1);
15014 EVT VT = Op.getValueType();
15015 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15016 VT.getVectorNumElements());
15017 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15018 Mask.getValueType().getSizeInBits());
15020 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15021 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15022 DAG.getIntPtrConstant(0, dl));
15024 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15028 SDValue Mask = Op.getOperand(3);
15029 EVT VT = Op.getValueType();
15030 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15031 VT.getVectorNumElements());
15032 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15033 Mask.getValueType().getSizeInBits());
15035 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15036 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15037 DAG.getIntPtrConstant(0, dl));
15038 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15047 default: return SDValue(); // Don't custom lower most intrinsics.
15049 case Intrinsic::x86_avx2_permd:
15050 case Intrinsic::x86_avx2_permps:
15051 // Operands intentionally swapped. Mask is last operand to intrinsic,
15052 // but second operand for node/instruction.
15053 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15054 Op.getOperand(2), Op.getOperand(1));
15056 case Intrinsic::x86_avx512_mask_valign_q_512:
15057 case Intrinsic::x86_avx512_mask_valign_d_512:
15058 // Vector source operands are swapped.
15059 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15060 Op.getValueType(), Op.getOperand(2),
15063 Op.getOperand(5), Op.getOperand(4),
15066 // ptest and testp intrinsics. The intrinsic these come from are designed to
15067 // return an integer value, not just an instruction so lower it to the ptest
15068 // or testp pattern and a setcc for the result.
15069 case Intrinsic::x86_sse41_ptestz:
15070 case Intrinsic::x86_sse41_ptestc:
15071 case Intrinsic::x86_sse41_ptestnzc:
15072 case Intrinsic::x86_avx_ptestz_256:
15073 case Intrinsic::x86_avx_ptestc_256:
15074 case Intrinsic::x86_avx_ptestnzc_256:
15075 case Intrinsic::x86_avx_vtestz_ps:
15076 case Intrinsic::x86_avx_vtestc_ps:
15077 case Intrinsic::x86_avx_vtestnzc_ps:
15078 case Intrinsic::x86_avx_vtestz_pd:
15079 case Intrinsic::x86_avx_vtestc_pd:
15080 case Intrinsic::x86_avx_vtestnzc_pd:
15081 case Intrinsic::x86_avx_vtestz_ps_256:
15082 case Intrinsic::x86_avx_vtestc_ps_256:
15083 case Intrinsic::x86_avx_vtestnzc_ps_256:
15084 case Intrinsic::x86_avx_vtestz_pd_256:
15085 case Intrinsic::x86_avx_vtestc_pd_256:
15086 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15087 bool IsTestPacked = false;
15090 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15091 case Intrinsic::x86_avx_vtestz_ps:
15092 case Intrinsic::x86_avx_vtestz_pd:
15093 case Intrinsic::x86_avx_vtestz_ps_256:
15094 case Intrinsic::x86_avx_vtestz_pd_256:
15095 IsTestPacked = true; // Fallthrough
15096 case Intrinsic::x86_sse41_ptestz:
15097 case Intrinsic::x86_avx_ptestz_256:
15099 X86CC = X86::COND_E;
15101 case Intrinsic::x86_avx_vtestc_ps:
15102 case Intrinsic::x86_avx_vtestc_pd:
15103 case Intrinsic::x86_avx_vtestc_ps_256:
15104 case Intrinsic::x86_avx_vtestc_pd_256:
15105 IsTestPacked = true; // Fallthrough
15106 case Intrinsic::x86_sse41_ptestc:
15107 case Intrinsic::x86_avx_ptestc_256:
15109 X86CC = X86::COND_B;
15111 case Intrinsic::x86_avx_vtestnzc_ps:
15112 case Intrinsic::x86_avx_vtestnzc_pd:
15113 case Intrinsic::x86_avx_vtestnzc_ps_256:
15114 case Intrinsic::x86_avx_vtestnzc_pd_256:
15115 IsTestPacked = true; // Fallthrough
15116 case Intrinsic::x86_sse41_ptestnzc:
15117 case Intrinsic::x86_avx_ptestnzc_256:
15119 X86CC = X86::COND_A;
15123 SDValue LHS = Op.getOperand(1);
15124 SDValue RHS = Op.getOperand(2);
15125 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15126 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15127 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15128 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15129 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15131 case Intrinsic::x86_avx512_kortestz_w:
15132 case Intrinsic::x86_avx512_kortestc_w: {
15133 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15134 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15135 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15136 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15137 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15138 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15139 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15142 case Intrinsic::x86_sse42_pcmpistria128:
15143 case Intrinsic::x86_sse42_pcmpestria128:
15144 case Intrinsic::x86_sse42_pcmpistric128:
15145 case Intrinsic::x86_sse42_pcmpestric128:
15146 case Intrinsic::x86_sse42_pcmpistrio128:
15147 case Intrinsic::x86_sse42_pcmpestrio128:
15148 case Intrinsic::x86_sse42_pcmpistris128:
15149 case Intrinsic::x86_sse42_pcmpestris128:
15150 case Intrinsic::x86_sse42_pcmpistriz128:
15151 case Intrinsic::x86_sse42_pcmpestriz128: {
15155 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15156 case Intrinsic::x86_sse42_pcmpistria128:
15157 Opcode = X86ISD::PCMPISTRI;
15158 X86CC = X86::COND_A;
15160 case Intrinsic::x86_sse42_pcmpestria128:
15161 Opcode = X86ISD::PCMPESTRI;
15162 X86CC = X86::COND_A;
15164 case Intrinsic::x86_sse42_pcmpistric128:
15165 Opcode = X86ISD::PCMPISTRI;
15166 X86CC = X86::COND_B;
15168 case Intrinsic::x86_sse42_pcmpestric128:
15169 Opcode = X86ISD::PCMPESTRI;
15170 X86CC = X86::COND_B;
15172 case Intrinsic::x86_sse42_pcmpistrio128:
15173 Opcode = X86ISD::PCMPISTRI;
15174 X86CC = X86::COND_O;
15176 case Intrinsic::x86_sse42_pcmpestrio128:
15177 Opcode = X86ISD::PCMPESTRI;
15178 X86CC = X86::COND_O;
15180 case Intrinsic::x86_sse42_pcmpistris128:
15181 Opcode = X86ISD::PCMPISTRI;
15182 X86CC = X86::COND_S;
15184 case Intrinsic::x86_sse42_pcmpestris128:
15185 Opcode = X86ISD::PCMPESTRI;
15186 X86CC = X86::COND_S;
15188 case Intrinsic::x86_sse42_pcmpistriz128:
15189 Opcode = X86ISD::PCMPISTRI;
15190 X86CC = X86::COND_E;
15192 case Intrinsic::x86_sse42_pcmpestriz128:
15193 Opcode = X86ISD::PCMPESTRI;
15194 X86CC = X86::COND_E;
15197 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15198 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15199 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15200 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15201 DAG.getConstant(X86CC, dl, MVT::i8),
15202 SDValue(PCMP.getNode(), 1));
15203 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15206 case Intrinsic::x86_sse42_pcmpistri128:
15207 case Intrinsic::x86_sse42_pcmpestri128: {
15209 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15210 Opcode = X86ISD::PCMPISTRI;
15212 Opcode = X86ISD::PCMPESTRI;
15214 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15215 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15216 return DAG.getNode(Opcode, dl, VTs, NewOps);
15221 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15222 SDValue Src, SDValue Mask, SDValue Base,
15223 SDValue Index, SDValue ScaleOp, SDValue Chain,
15224 const X86Subtarget * Subtarget) {
15226 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15227 assert(C && "Invalid scale type");
15228 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15229 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15230 Index.getSimpleValueType().getVectorNumElements());
15232 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15234 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15236 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15237 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15238 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15239 SDValue Segment = DAG.getRegister(0, MVT::i32);
15240 if (Src.getOpcode() == ISD::UNDEF)
15241 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15242 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15243 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15244 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15245 return DAG.getMergeValues(RetOps, dl);
15248 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15249 SDValue Src, SDValue Mask, SDValue Base,
15250 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15252 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15253 assert(C && "Invalid scale type");
15254 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15255 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15256 SDValue Segment = DAG.getRegister(0, MVT::i32);
15257 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15258 Index.getSimpleValueType().getVectorNumElements());
15260 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15262 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15264 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15265 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15266 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15267 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15268 return SDValue(Res, 1);
15271 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15272 SDValue Mask, SDValue Base, SDValue Index,
15273 SDValue ScaleOp, SDValue Chain) {
15275 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15276 assert(C && "Invalid scale type");
15277 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15278 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15279 SDValue Segment = DAG.getRegister(0, MVT::i32);
15281 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15283 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15285 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15287 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15288 //SDVTList VTs = DAG.getVTList(MVT::Other);
15289 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15290 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15291 return SDValue(Res, 0);
15294 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15295 // read performance monitor counters (x86_rdpmc).
15296 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15297 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15298 SmallVectorImpl<SDValue> &Results) {
15299 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15300 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15303 // The ECX register is used to select the index of the performance counter
15305 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15307 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15309 // Reads the content of a 64-bit performance counter and returns it in the
15310 // registers EDX:EAX.
15311 if (Subtarget->is64Bit()) {
15312 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15313 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15316 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15317 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15320 Chain = HI.getValue(1);
15322 if (Subtarget->is64Bit()) {
15323 // The EAX register is loaded with the low-order 32 bits. The EDX register
15324 // is loaded with the supported high-order bits of the counter.
15325 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15326 DAG.getConstant(32, DL, MVT::i8));
15327 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15328 Results.push_back(Chain);
15332 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15333 SDValue Ops[] = { LO, HI };
15334 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15335 Results.push_back(Pair);
15336 Results.push_back(Chain);
15339 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15340 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15341 // also used to custom lower READCYCLECOUNTER nodes.
15342 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15343 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15344 SmallVectorImpl<SDValue> &Results) {
15345 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15346 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15349 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15350 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15351 // and the EAX register is loaded with the low-order 32 bits.
15352 if (Subtarget->is64Bit()) {
15353 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15354 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15357 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15358 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15361 SDValue Chain = HI.getValue(1);
15363 if (Opcode == X86ISD::RDTSCP_DAG) {
15364 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15366 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15367 // the ECX register. Add 'ecx' explicitly to the chain.
15368 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15370 // Explicitly store the content of ECX at the location passed in input
15371 // to the 'rdtscp' intrinsic.
15372 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15373 MachinePointerInfo(), false, false, 0);
15376 if (Subtarget->is64Bit()) {
15377 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15378 // the EAX register is loaded with the low-order 32 bits.
15379 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15380 DAG.getConstant(32, DL, MVT::i8));
15381 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15382 Results.push_back(Chain);
15386 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15387 SDValue Ops[] = { LO, HI };
15388 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15389 Results.push_back(Pair);
15390 Results.push_back(Chain);
15393 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15394 SelectionDAG &DAG) {
15395 SmallVector<SDValue, 2> Results;
15397 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15399 return DAG.getMergeValues(Results, DL);
15403 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15404 SelectionDAG &DAG) {
15405 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15407 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15412 switch(IntrData->Type) {
15414 llvm_unreachable("Unknown Intrinsic Type");
15418 // Emit the node with the right value type.
15419 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15420 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15422 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15423 // Otherwise return the value from Rand, which is always 0, casted to i32.
15424 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15425 DAG.getConstant(1, dl, Op->getValueType(1)),
15426 DAG.getConstant(X86::COND_B, dl, MVT::i32),
15427 SDValue(Result.getNode(), 1) };
15428 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15429 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15432 // Return { result, isValid, chain }.
15433 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15434 SDValue(Result.getNode(), 2));
15437 //gather(v1, mask, index, base, scale);
15438 SDValue Chain = Op.getOperand(0);
15439 SDValue Src = Op.getOperand(2);
15440 SDValue Base = Op.getOperand(3);
15441 SDValue Index = Op.getOperand(4);
15442 SDValue Mask = Op.getOperand(5);
15443 SDValue Scale = Op.getOperand(6);
15444 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15448 //scatter(base, mask, index, v1, scale);
15449 SDValue Chain = Op.getOperand(0);
15450 SDValue Base = Op.getOperand(2);
15451 SDValue Mask = Op.getOperand(3);
15452 SDValue Index = Op.getOperand(4);
15453 SDValue Src = Op.getOperand(5);
15454 SDValue Scale = Op.getOperand(6);
15455 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15459 SDValue Hint = Op.getOperand(6);
15460 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15461 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15462 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15463 SDValue Chain = Op.getOperand(0);
15464 SDValue Mask = Op.getOperand(2);
15465 SDValue Index = Op.getOperand(3);
15466 SDValue Base = Op.getOperand(4);
15467 SDValue Scale = Op.getOperand(5);
15468 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15470 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15472 SmallVector<SDValue, 2> Results;
15473 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15475 return DAG.getMergeValues(Results, dl);
15477 // Read Performance Monitoring Counters.
15479 SmallVector<SDValue, 2> Results;
15480 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15481 return DAG.getMergeValues(Results, dl);
15483 // XTEST intrinsics.
15485 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15486 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15487 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15488 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15490 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15491 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15492 Ret, SDValue(InTrans.getNode(), 1));
15496 SmallVector<SDValue, 2> Results;
15497 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15498 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15499 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15500 DAG.getConstant(-1, dl, MVT::i8));
15501 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15502 Op.getOperand(4), GenCF.getValue(1));
15503 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15504 Op.getOperand(5), MachinePointerInfo(),
15506 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15507 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15509 Results.push_back(SetCC);
15510 Results.push_back(Store);
15511 return DAG.getMergeValues(Results, dl);
15513 case COMPRESS_TO_MEM: {
15515 SDValue Mask = Op.getOperand(4);
15516 SDValue DataToCompress = Op.getOperand(3);
15517 SDValue Addr = Op.getOperand(2);
15518 SDValue Chain = Op.getOperand(0);
15520 if (isAllOnes(Mask)) // return just a store
15521 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15522 MachinePointerInfo(), false, false, 0);
15524 EVT VT = DataToCompress.getValueType();
15525 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15526 VT.getVectorNumElements());
15527 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15528 Mask.getValueType().getSizeInBits());
15529 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15530 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15531 DAG.getIntPtrConstant(0, dl));
15533 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15534 DataToCompress, DAG.getUNDEF(VT));
15535 return DAG.getStore(Chain, dl, Compressed, Addr,
15536 MachinePointerInfo(), false, false, 0);
15538 case EXPAND_FROM_MEM: {
15540 SDValue Mask = Op.getOperand(4);
15541 SDValue PathThru = Op.getOperand(3);
15542 SDValue Addr = Op.getOperand(2);
15543 SDValue Chain = Op.getOperand(0);
15544 EVT VT = Op.getValueType();
15546 if (isAllOnes(Mask)) // return just a load
15547 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15549 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15550 VT.getVectorNumElements());
15551 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15552 Mask.getValueType().getSizeInBits());
15553 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15554 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15555 DAG.getIntPtrConstant(0, dl));
15557 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15558 false, false, false, 0);
15560 SDValue Results[] = {
15561 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15563 return DAG.getMergeValues(Results, dl);
15568 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15569 SelectionDAG &DAG) const {
15570 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15571 MFI->setReturnAddressIsTaken(true);
15573 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15576 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15578 EVT PtrVT = getPointerTy();
15581 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15582 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15583 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15584 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15585 DAG.getNode(ISD::ADD, dl, PtrVT,
15586 FrameAddr, Offset),
15587 MachinePointerInfo(), false, false, false, 0);
15590 // Just load the return address.
15591 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15592 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15593 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15596 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15597 MachineFunction &MF = DAG.getMachineFunction();
15598 MachineFrameInfo *MFI = MF.getFrameInfo();
15599 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15600 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15601 EVT VT = Op.getValueType();
15603 MFI->setFrameAddressIsTaken(true);
15605 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15606 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15607 // is not possible to crawl up the stack without looking at the unwind codes
15609 int FrameAddrIndex = FuncInfo->getFAIndex();
15610 if (!FrameAddrIndex) {
15611 // Set up a frame object for the return address.
15612 unsigned SlotSize = RegInfo->getSlotSize();
15613 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15614 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15615 FuncInfo->setFAIndex(FrameAddrIndex);
15617 return DAG.getFrameIndex(FrameAddrIndex, VT);
15620 unsigned FrameReg =
15621 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15622 SDLoc dl(Op); // FIXME probably not meaningful
15623 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15624 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15625 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15626 "Invalid Frame Register!");
15627 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15629 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15630 MachinePointerInfo(),
15631 false, false, false, 0);
15635 // FIXME? Maybe this could be a TableGen attribute on some registers and
15636 // this table could be generated automatically from RegInfo.
15637 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15639 unsigned Reg = StringSwitch<unsigned>(RegName)
15640 .Case("esp", X86::ESP)
15641 .Case("rsp", X86::RSP)
15645 report_fatal_error("Invalid register name global variable");
15648 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15649 SelectionDAG &DAG) const {
15650 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15651 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15654 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15655 SDValue Chain = Op.getOperand(0);
15656 SDValue Offset = Op.getOperand(1);
15657 SDValue Handler = Op.getOperand(2);
15660 EVT PtrVT = getPointerTy();
15661 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15662 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15663 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15664 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15665 "Invalid Frame Register!");
15666 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15667 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15669 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15670 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15672 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15673 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15675 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15677 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15678 DAG.getRegister(StoreAddrReg, PtrVT));
15681 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15682 SelectionDAG &DAG) const {
15684 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15685 DAG.getVTList(MVT::i32, MVT::Other),
15686 Op.getOperand(0), Op.getOperand(1));
15689 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15690 SelectionDAG &DAG) const {
15692 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15693 Op.getOperand(0), Op.getOperand(1));
15696 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15697 return Op.getOperand(0);
15700 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15701 SelectionDAG &DAG) const {
15702 SDValue Root = Op.getOperand(0);
15703 SDValue Trmp = Op.getOperand(1); // trampoline
15704 SDValue FPtr = Op.getOperand(2); // nested function
15705 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15708 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15709 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15711 if (Subtarget->is64Bit()) {
15712 SDValue OutChains[6];
15714 // Large code-model.
15715 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15716 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15718 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15719 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15721 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15723 // Load the pointer to the nested function into R11.
15724 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15725 SDValue Addr = Trmp;
15726 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15727 Addr, MachinePointerInfo(TrmpAddr),
15730 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15731 DAG.getConstant(2, dl, MVT::i64));
15732 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15733 MachinePointerInfo(TrmpAddr, 2),
15736 // Load the 'nest' parameter value into R10.
15737 // R10 is specified in X86CallingConv.td
15738 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15739 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15740 DAG.getConstant(10, dl, MVT::i64));
15741 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15742 Addr, MachinePointerInfo(TrmpAddr, 10),
15745 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15746 DAG.getConstant(12, dl, MVT::i64));
15747 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15748 MachinePointerInfo(TrmpAddr, 12),
15751 // Jump to the nested function.
15752 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15753 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15754 DAG.getConstant(20, dl, MVT::i64));
15755 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15756 Addr, MachinePointerInfo(TrmpAddr, 20),
15759 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15760 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15761 DAG.getConstant(22, dl, MVT::i64));
15762 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15763 Addr, MachinePointerInfo(TrmpAddr, 22),
15766 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15768 const Function *Func =
15769 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15770 CallingConv::ID CC = Func->getCallingConv();
15775 llvm_unreachable("Unsupported calling convention");
15776 case CallingConv::C:
15777 case CallingConv::X86_StdCall: {
15778 // Pass 'nest' parameter in ECX.
15779 // Must be kept in sync with X86CallingConv.td
15780 NestReg = X86::ECX;
15782 // Check that ECX wasn't needed by an 'inreg' parameter.
15783 FunctionType *FTy = Func->getFunctionType();
15784 const AttributeSet &Attrs = Func->getAttributes();
15786 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15787 unsigned InRegCount = 0;
15790 for (FunctionType::param_iterator I = FTy->param_begin(),
15791 E = FTy->param_end(); I != E; ++I, ++Idx)
15792 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15793 // FIXME: should only count parameters that are lowered to integers.
15794 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15796 if (InRegCount > 2) {
15797 report_fatal_error("Nest register in use - reduce number of inreg"
15803 case CallingConv::X86_FastCall:
15804 case CallingConv::X86_ThisCall:
15805 case CallingConv::Fast:
15806 // Pass 'nest' parameter in EAX.
15807 // Must be kept in sync with X86CallingConv.td
15808 NestReg = X86::EAX;
15812 SDValue OutChains[4];
15813 SDValue Addr, Disp;
15815 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15816 DAG.getConstant(10, dl, MVT::i32));
15817 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15819 // This is storing the opcode for MOV32ri.
15820 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15821 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15822 OutChains[0] = DAG.getStore(Root, dl,
15823 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15824 Trmp, MachinePointerInfo(TrmpAddr),
15827 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15828 DAG.getConstant(1, dl, MVT::i32));
15829 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15830 MachinePointerInfo(TrmpAddr, 1),
15833 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15834 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15835 DAG.getConstant(5, dl, MVT::i32));
15836 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15837 Addr, MachinePointerInfo(TrmpAddr, 5),
15840 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15841 DAG.getConstant(6, dl, MVT::i32));
15842 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15843 MachinePointerInfo(TrmpAddr, 6),
15846 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15850 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15851 SelectionDAG &DAG) const {
15853 The rounding mode is in bits 11:10 of FPSR, and has the following
15855 00 Round to nearest
15860 FLT_ROUNDS, on the other hand, expects the following:
15867 To perform the conversion, we do:
15868 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15871 MachineFunction &MF = DAG.getMachineFunction();
15872 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15873 unsigned StackAlignment = TFI.getStackAlignment();
15874 MVT VT = Op.getSimpleValueType();
15877 // Save FP Control Word to stack slot
15878 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15879 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15881 MachineMemOperand *MMO =
15882 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15883 MachineMemOperand::MOStore, 2, 2);
15885 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15886 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15887 DAG.getVTList(MVT::Other),
15888 Ops, MVT::i16, MMO);
15890 // Load FP Control Word from stack slot
15891 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15892 MachinePointerInfo(), false, false, false, 0);
15894 // Transform as necessary
15896 DAG.getNode(ISD::SRL, DL, MVT::i16,
15897 DAG.getNode(ISD::AND, DL, MVT::i16,
15898 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15899 DAG.getConstant(11, DL, MVT::i8));
15901 DAG.getNode(ISD::SRL, DL, MVT::i16,
15902 DAG.getNode(ISD::AND, DL, MVT::i16,
15903 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15904 DAG.getConstant(9, DL, MVT::i8));
15907 DAG.getNode(ISD::AND, DL, MVT::i16,
15908 DAG.getNode(ISD::ADD, DL, MVT::i16,
15909 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15910 DAG.getConstant(1, DL, MVT::i16)),
15911 DAG.getConstant(3, DL, MVT::i16));
15913 return DAG.getNode((VT.getSizeInBits() < 16 ?
15914 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15917 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15918 MVT VT = Op.getSimpleValueType();
15920 unsigned NumBits = VT.getSizeInBits();
15923 Op = Op.getOperand(0);
15924 if (VT == MVT::i8) {
15925 // Zero extend to i32 since there is not an i8 bsr.
15927 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15930 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15931 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15932 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15934 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15937 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15938 DAG.getConstant(X86::COND_E, dl, MVT::i8),
15941 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15943 // Finally xor with NumBits-1.
15944 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15945 DAG.getConstant(NumBits - 1, dl, OpVT));
15948 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15952 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15953 MVT VT = Op.getSimpleValueType();
15955 unsigned NumBits = VT.getSizeInBits();
15958 Op = Op.getOperand(0);
15959 if (VT == MVT::i8) {
15960 // Zero extend to i32 since there is not an i8 bsr.
15962 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15965 // Issue a bsr (scan bits in reverse).
15966 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15967 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15969 // And xor with NumBits-1.
15970 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15971 DAG.getConstant(NumBits - 1, dl, OpVT));
15974 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15978 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15979 MVT VT = Op.getSimpleValueType();
15980 unsigned NumBits = VT.getSizeInBits();
15982 Op = Op.getOperand(0);
15984 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15985 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15986 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15988 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15991 DAG.getConstant(NumBits, dl, VT),
15992 DAG.getConstant(X86::COND_E, dl, MVT::i8),
15995 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15998 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15999 // ones, and then concatenate the result back.
16000 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16001 MVT VT = Op.getSimpleValueType();
16003 assert(VT.is256BitVector() && VT.isInteger() &&
16004 "Unsupported value type for operation");
16006 unsigned NumElems = VT.getVectorNumElements();
16009 // Extract the LHS vectors
16010 SDValue LHS = Op.getOperand(0);
16011 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16012 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16014 // Extract the RHS vectors
16015 SDValue RHS = Op.getOperand(1);
16016 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16017 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16019 MVT EltVT = VT.getVectorElementType();
16020 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16022 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16023 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16024 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16027 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16028 assert(Op.getSimpleValueType().is256BitVector() &&
16029 Op.getSimpleValueType().isInteger() &&
16030 "Only handle AVX 256-bit vector integer operation");
16031 return Lower256IntArith(Op, DAG);
16034 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16035 assert(Op.getSimpleValueType().is256BitVector() &&
16036 Op.getSimpleValueType().isInteger() &&
16037 "Only handle AVX 256-bit vector integer operation");
16038 return Lower256IntArith(Op, DAG);
16041 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16042 SelectionDAG &DAG) {
16044 MVT VT = Op.getSimpleValueType();
16046 // Decompose 256-bit ops into smaller 128-bit ops.
16047 if (VT.is256BitVector() && !Subtarget->hasInt256())
16048 return Lower256IntArith(Op, DAG);
16050 SDValue A = Op.getOperand(0);
16051 SDValue B = Op.getOperand(1);
16053 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16054 // pairs, multiply and truncate.
16055 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16056 if (Subtarget->hasInt256()) {
16057 if (VT == MVT::v32i8) {
16058 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16059 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16060 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16061 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16062 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16063 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16064 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16065 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16066 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16067 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16070 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16071 return DAG.getNode(
16072 ISD::TRUNCATE, dl, VT,
16073 DAG.getNode(ISD::MUL, dl, ExVT,
16074 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16075 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16078 assert(VT == MVT::v16i8 &&
16079 "Pre-AVX2 support only supports v16i8 multiplication");
16080 MVT ExVT = MVT::v8i16;
16082 // Extract the lo parts and sign extend to i16
16084 if (Subtarget->hasSSE41()) {
16085 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16086 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16088 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16089 -1, 4, -1, 5, -1, 6, -1, 7};
16090 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16091 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16092 ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16093 BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16094 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16095 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16098 // Extract the hi parts and sign extend to i16
16100 if (Subtarget->hasSSE41()) {
16101 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16102 -1, -1, -1, -1, -1, -1, -1, -1};
16103 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16104 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16105 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16106 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16108 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16109 -1, 12, -1, 13, -1, 14, -1, 15};
16110 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16111 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16112 AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16113 BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16114 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16115 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16118 // Multiply, mask the lower 8bits of the lo/hi results and pack
16119 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16120 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16121 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16122 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16123 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16126 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16127 if (VT == MVT::v4i32) {
16128 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16129 "Should not custom lower when pmuldq is available!");
16131 // Extract the odd parts.
16132 static const int UnpackMask[] = { 1, -1, 3, -1 };
16133 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16134 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16136 // Multiply the even parts.
16137 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16138 // Now multiply odd parts.
16139 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16141 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16142 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16144 // Merge the two vectors back together with a shuffle. This expands into 2
16146 static const int ShufMask[] = { 0, 4, 2, 6 };
16147 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16150 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16151 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16153 // Ahi = psrlqi(a, 32);
16154 // Bhi = psrlqi(b, 32);
16156 // AloBlo = pmuludq(a, b);
16157 // AloBhi = pmuludq(a, Bhi);
16158 // AhiBlo = pmuludq(Ahi, b);
16160 // AloBhi = psllqi(AloBhi, 32);
16161 // AhiBlo = psllqi(AhiBlo, 32);
16162 // return AloBlo + AloBhi + AhiBlo;
16164 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16165 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16167 // Bit cast to 32-bit vectors for MULUDQ
16168 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16169 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16170 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16171 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16172 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16173 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16175 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16176 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16177 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16179 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16180 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16182 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16183 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16186 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16187 assert(Subtarget->isTargetWin64() && "Unexpected target");
16188 EVT VT = Op.getValueType();
16189 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16190 "Unexpected return type for lowering");
16194 switch (Op->getOpcode()) {
16195 default: llvm_unreachable("Unexpected request for libcall!");
16196 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
16197 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
16198 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
16199 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
16200 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
16201 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16205 SDValue InChain = DAG.getEntryNode();
16207 TargetLowering::ArgListTy Args;
16208 TargetLowering::ArgListEntry Entry;
16209 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16210 EVT ArgVT = Op->getOperand(i).getValueType();
16211 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16212 "Unexpected argument type for lowering");
16213 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16214 Entry.Node = StackPtr;
16215 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16217 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16218 Entry.Ty = PointerType::get(ArgTy,0);
16219 Entry.isSExt = false;
16220 Entry.isZExt = false;
16221 Args.push_back(Entry);
16224 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16227 TargetLowering::CallLoweringInfo CLI(DAG);
16228 CLI.setDebugLoc(dl).setChain(InChain)
16229 .setCallee(getLibcallCallingConv(LC),
16230 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16231 Callee, std::move(Args), 0)
16232 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16234 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16235 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16238 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16239 SelectionDAG &DAG) {
16240 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16241 EVT VT = Op0.getValueType();
16244 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16245 (VT == MVT::v8i32 && Subtarget->hasInt256()));
16247 // PMULxD operations multiply each even value (starting at 0) of LHS with
16248 // the related value of RHS and produce a widen result.
16249 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16250 // => <2 x i64> <ae|cg>
16252 // In other word, to have all the results, we need to perform two PMULxD:
16253 // 1. one with the even values.
16254 // 2. one with the odd values.
16255 // To achieve #2, with need to place the odd values at an even position.
16257 // Place the odd value at an even position (basically, shift all values 1
16258 // step to the left):
16259 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16260 // <a|b|c|d> => <b|undef|d|undef>
16261 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16262 // <e|f|g|h> => <f|undef|h|undef>
16263 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16265 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16267 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16268 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16270 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16271 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16272 // => <2 x i64> <ae|cg>
16273 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16274 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16275 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16276 // => <2 x i64> <bf|dh>
16277 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16278 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16280 // Shuffle it back into the right order.
16281 SDValue Highs, Lows;
16282 if (VT == MVT::v8i32) {
16283 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16284 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16285 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16286 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16288 const int HighMask[] = {1, 5, 3, 7};
16289 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16290 const int LowMask[] = {0, 4, 2, 6};
16291 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16294 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16295 // unsigned multiply.
16296 if (IsSigned && !Subtarget->hasSSE41()) {
16298 DAG.getConstant(31, dl,
16299 DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16300 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16301 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16302 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16303 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16305 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16306 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16309 // The first result of MUL_LOHI is actually the low value, followed by the
16311 SDValue Ops[] = {Lows, Highs};
16312 return DAG.getMergeValues(Ops, dl);
16315 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16316 const X86Subtarget *Subtarget) {
16317 MVT VT = Op.getSimpleValueType();
16319 SDValue R = Op.getOperand(0);
16320 SDValue Amt = Op.getOperand(1);
16322 // Optimize shl/srl/sra with constant shift amount.
16323 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16324 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16325 uint64_t ShiftAmt = ShiftConst->getZExtValue();
16327 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16328 (Subtarget->hasInt256() &&
16329 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16330 (Subtarget->hasAVX512() &&
16331 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16332 if (Op.getOpcode() == ISD::SHL)
16333 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16335 if (Op.getOpcode() == ISD::SRL)
16336 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16338 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16339 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16343 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16344 unsigned NumElts = VT.getVectorNumElements();
16345 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16347 if (Op.getOpcode() == ISD::SHL) {
16348 // Make a large shift.
16349 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16351 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16352 // Zero out the rightmost bits.
16353 SmallVector<SDValue, 32> V(
16354 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16355 return DAG.getNode(ISD::AND, dl, VT, SHL,
16356 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16358 if (Op.getOpcode() == ISD::SRL) {
16359 // Make a large shift.
16360 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16362 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16363 // Zero out the leftmost bits.
16364 SmallVector<SDValue, 32> V(
16365 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16366 return DAG.getNode(ISD::AND, dl, VT, SRL,
16367 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16369 if (Op.getOpcode() == ISD::SRA) {
16370 if (ShiftAmt == 7) {
16371 // R s>> 7 === R s< 0
16372 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16373 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16376 // R s>> a === ((R u>> a) ^ m) - m
16377 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16378 SmallVector<SDValue, 32> V(NumElts,
16379 DAG.getConstant(128 >> ShiftAmt, dl,
16381 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16382 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16383 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16386 llvm_unreachable("Unknown shift opcode.");
16391 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16392 if (!Subtarget->is64Bit() &&
16393 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16394 Amt.getOpcode() == ISD::BITCAST &&
16395 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16396 Amt = Amt.getOperand(0);
16397 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16398 VT.getVectorNumElements();
16399 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16400 uint64_t ShiftAmt = 0;
16401 for (unsigned i = 0; i != Ratio; ++i) {
16402 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16406 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16408 // Check remaining shift amounts.
16409 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16410 uint64_t ShAmt = 0;
16411 for (unsigned j = 0; j != Ratio; ++j) {
16412 ConstantSDNode *C =
16413 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16417 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16419 if (ShAmt != ShiftAmt)
16422 switch (Op.getOpcode()) {
16424 llvm_unreachable("Unknown shift opcode!");
16426 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16429 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16432 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16440 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16441 const X86Subtarget* Subtarget) {
16442 MVT VT = Op.getSimpleValueType();
16444 SDValue R = Op.getOperand(0);
16445 SDValue Amt = Op.getOperand(1);
16447 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16448 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16449 (Subtarget->hasInt256() &&
16450 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16451 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16452 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16454 EVT EltVT = VT.getVectorElementType();
16456 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16457 // Check if this build_vector node is doing a splat.
16458 // If so, then set BaseShAmt equal to the splat value.
16459 BaseShAmt = BV->getSplatValue();
16460 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16461 BaseShAmt = SDValue();
16463 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16464 Amt = Amt.getOperand(0);
16466 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16467 if (SVN && SVN->isSplat()) {
16468 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16469 SDValue InVec = Amt.getOperand(0);
16470 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16471 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16472 "Unexpected shuffle index found!");
16473 BaseShAmt = InVec.getOperand(SplatIdx);
16474 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16475 if (ConstantSDNode *C =
16476 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16477 if (C->getZExtValue() == SplatIdx)
16478 BaseShAmt = InVec.getOperand(1);
16483 // Avoid introducing an extract element from a shuffle.
16484 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16485 DAG.getIntPtrConstant(SplatIdx, dl));
16489 if (BaseShAmt.getNode()) {
16490 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16491 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16492 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16493 else if (EltVT.bitsLT(MVT::i32))
16494 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16496 switch (Op.getOpcode()) {
16498 llvm_unreachable("Unknown shift opcode!");
16500 switch (VT.SimpleTy) {
16501 default: return SDValue();
16510 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16513 switch (VT.SimpleTy) {
16514 default: return SDValue();
16521 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16524 switch (VT.SimpleTy) {
16525 default: return SDValue();
16534 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16540 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16541 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
16542 Amt.getOpcode() == ISD::BITCAST &&
16543 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16544 Amt = Amt.getOperand(0);
16545 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16546 VT.getVectorNumElements();
16547 std::vector<SDValue> Vals(Ratio);
16548 for (unsigned i = 0; i != Ratio; ++i)
16549 Vals[i] = Amt.getOperand(i);
16550 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16551 for (unsigned j = 0; j != Ratio; ++j)
16552 if (Vals[j] != Amt.getOperand(i + j))
16555 switch (Op.getOpcode()) {
16557 llvm_unreachable("Unknown shift opcode!");
16559 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16561 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16563 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16570 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16571 SelectionDAG &DAG) {
16572 MVT VT = Op.getSimpleValueType();
16574 SDValue R = Op.getOperand(0);
16575 SDValue Amt = Op.getOperand(1);
16577 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16578 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16580 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16583 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16586 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16589 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16590 if (Subtarget->hasInt256()) {
16591 if (Op.getOpcode() == ISD::SRL &&
16592 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16593 VT == MVT::v4i64 || VT == MVT::v8i32))
16595 if (Op.getOpcode() == ISD::SHL &&
16596 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16597 VT == MVT::v4i64 || VT == MVT::v8i32))
16599 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16603 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16604 // shifts per-lane and then shuffle the partial results back together.
16605 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16606 // Splat the shift amounts so the scalar shifts above will catch it.
16607 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16608 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16609 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16610 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16611 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16614 // If possible, lower this packed shift into a vector multiply instead of
16615 // expanding it into a sequence of scalar shifts.
16616 // Do this only if the vector shift count is a constant build_vector.
16617 if (Op.getOpcode() == ISD::SHL &&
16618 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16619 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16620 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16621 SmallVector<SDValue, 8> Elts;
16622 EVT SVT = VT.getScalarType();
16623 unsigned SVTBits = SVT.getSizeInBits();
16624 const APInt &One = APInt(SVTBits, 1);
16625 unsigned NumElems = VT.getVectorNumElements();
16627 for (unsigned i=0; i !=NumElems; ++i) {
16628 SDValue Op = Amt->getOperand(i);
16629 if (Op->getOpcode() == ISD::UNDEF) {
16630 Elts.push_back(Op);
16634 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16635 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16636 uint64_t ShAmt = C.getZExtValue();
16637 if (ShAmt >= SVTBits) {
16638 Elts.push_back(DAG.getUNDEF(SVT));
16641 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16643 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16644 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16647 // Lower SHL with variable shift amount.
16648 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16649 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16651 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16652 DAG.getConstant(0x3f800000U, dl, VT));
16653 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16654 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16655 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16658 // If possible, lower this shift as a sequence of two shifts by
16659 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16661 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16663 // Could be rewritten as:
16664 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16666 // The advantage is that the two shifts from the example would be
16667 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16668 // the vector shift into four scalar shifts plus four pairs of vector
16670 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16671 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16672 unsigned TargetOpcode = X86ISD::MOVSS;
16673 bool CanBeSimplified;
16674 // The splat value for the first packed shift (the 'X' from the example).
16675 SDValue Amt1 = Amt->getOperand(0);
16676 // The splat value for the second packed shift (the 'Y' from the example).
16677 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16678 Amt->getOperand(2);
16680 // See if it is possible to replace this node with a sequence of
16681 // two shifts followed by a MOVSS/MOVSD
16682 if (VT == MVT::v4i32) {
16683 // Check if it is legal to use a MOVSS.
16684 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16685 Amt2 == Amt->getOperand(3);
16686 if (!CanBeSimplified) {
16687 // Otherwise, check if we can still simplify this node using a MOVSD.
16688 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16689 Amt->getOperand(2) == Amt->getOperand(3);
16690 TargetOpcode = X86ISD::MOVSD;
16691 Amt2 = Amt->getOperand(2);
16694 // Do similar checks for the case where the machine value type
16696 CanBeSimplified = Amt1 == Amt->getOperand(1);
16697 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16698 CanBeSimplified = Amt2 == Amt->getOperand(i);
16700 if (!CanBeSimplified) {
16701 TargetOpcode = X86ISD::MOVSD;
16702 CanBeSimplified = true;
16703 Amt2 = Amt->getOperand(4);
16704 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16705 CanBeSimplified = Amt1 == Amt->getOperand(i);
16706 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16707 CanBeSimplified = Amt2 == Amt->getOperand(j);
16711 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16712 isa<ConstantSDNode>(Amt2)) {
16713 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16714 EVT CastVT = MVT::v4i32;
16716 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16717 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16719 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16720 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16721 if (TargetOpcode == X86ISD::MOVSD)
16722 CastVT = MVT::v2i64;
16723 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16724 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16725 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16727 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16731 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16732 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16733 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16735 SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16736 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16737 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16739 // r = VSELECT(r, shl(r, 4), a);
16740 SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16741 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16744 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16745 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16746 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16748 // r = VSELECT(r, shl(r, 2), a);
16749 M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16750 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16753 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16754 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16755 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16757 // return VSELECT(r, r+r, a);
16758 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16759 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16763 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16764 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16765 // solution better.
16766 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16767 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16769 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16770 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16771 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16772 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16773 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16776 // Decompose 256-bit shifts into smaller 128-bit shifts.
16777 if (VT.is256BitVector()) {
16778 unsigned NumElems = VT.getVectorNumElements();
16779 MVT EltVT = VT.getVectorElementType();
16780 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16782 // Extract the two vectors
16783 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16784 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16786 // Recreate the shift amount vectors
16787 SDValue Amt1, Amt2;
16788 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16789 // Constant shift amount
16790 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16791 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16792 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16794 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16795 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16797 // Variable shift amount
16798 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16799 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16802 // Issue new vector shifts for the smaller types
16803 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16804 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16806 // Concatenate the result back
16807 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16813 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16814 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16815 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16816 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16817 // has only one use.
16818 SDNode *N = Op.getNode();
16819 SDValue LHS = N->getOperand(0);
16820 SDValue RHS = N->getOperand(1);
16821 unsigned BaseOp = 0;
16824 switch (Op.getOpcode()) {
16825 default: llvm_unreachable("Unknown ovf instruction!");
16827 // A subtract of one will be selected as a INC. Note that INC doesn't
16828 // set CF, so we can't do this for UADDO.
16829 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16831 BaseOp = X86ISD::INC;
16832 Cond = X86::COND_O;
16835 BaseOp = X86ISD::ADD;
16836 Cond = X86::COND_O;
16839 BaseOp = X86ISD::ADD;
16840 Cond = X86::COND_B;
16843 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16844 // set CF, so we can't do this for USUBO.
16845 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16847 BaseOp = X86ISD::DEC;
16848 Cond = X86::COND_O;
16851 BaseOp = X86ISD::SUB;
16852 Cond = X86::COND_O;
16855 BaseOp = X86ISD::SUB;
16856 Cond = X86::COND_B;
16859 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16860 Cond = X86::COND_O;
16862 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16863 if (N->getValueType(0) == MVT::i8) {
16864 BaseOp = X86ISD::UMUL8;
16865 Cond = X86::COND_O;
16868 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16870 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16873 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16874 DAG.getConstant(X86::COND_O, DL, MVT::i32),
16875 SDValue(Sum.getNode(), 2));
16877 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16881 // Also sets EFLAGS.
16882 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16883 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16886 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16887 DAG.getConstant(Cond, DL, MVT::i32),
16888 SDValue(Sum.getNode(), 1));
16890 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16893 /// Returns true if the operand type is exactly twice the native width, and
16894 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16895 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16896 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16897 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16898 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16901 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16902 else if (OpWidth == 128)
16903 return Subtarget->hasCmpxchg16b();
16908 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16909 return needsCmpXchgNb(SI->getValueOperand()->getType());
16912 // Note: this turns large loads into lock cmpxchg8b/16b.
16913 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16914 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16915 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16916 return needsCmpXchgNb(PTy->getElementType());
16919 TargetLoweringBase::AtomicRMWExpansionKind
16920 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16921 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16922 const Type *MemType = AI->getType();
16924 // If the operand is too big, we must see if cmpxchg8/16b is available
16925 // and default to library calls otherwise.
16926 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16927 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16928 : AtomicRMWExpansionKind::None;
16931 AtomicRMWInst::BinOp Op = AI->getOperation();
16934 llvm_unreachable("Unknown atomic operation");
16935 case AtomicRMWInst::Xchg:
16936 case AtomicRMWInst::Add:
16937 case AtomicRMWInst::Sub:
16938 // It's better to use xadd, xsub or xchg for these in all cases.
16939 return AtomicRMWExpansionKind::None;
16940 case AtomicRMWInst::Or:
16941 case AtomicRMWInst::And:
16942 case AtomicRMWInst::Xor:
16943 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16944 // prefix to a normal instruction for these operations.
16945 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16946 : AtomicRMWExpansionKind::None;
16947 case AtomicRMWInst::Nand:
16948 case AtomicRMWInst::Max:
16949 case AtomicRMWInst::Min:
16950 case AtomicRMWInst::UMax:
16951 case AtomicRMWInst::UMin:
16952 // These always require a non-trivial set of data operations on x86. We must
16953 // use a cmpxchg loop.
16954 return AtomicRMWExpansionKind::CmpXChg;
16958 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16959 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16960 // no-sse2). There isn't any reason to disable it if the target processor
16962 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16966 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16967 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16968 const Type *MemType = AI->getType();
16969 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16970 // there is no benefit in turning such RMWs into loads, and it is actually
16971 // harmful as it introduces a mfence.
16972 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16975 auto Builder = IRBuilder<>(AI);
16976 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16977 auto SynchScope = AI->getSynchScope();
16978 // We must restrict the ordering to avoid generating loads with Release or
16979 // ReleaseAcquire orderings.
16980 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16981 auto Ptr = AI->getPointerOperand();
16983 // Before the load we need a fence. Here is an example lifted from
16984 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16987 // x.store(1, relaxed);
16988 // r1 = y.fetch_add(0, release);
16990 // y.fetch_add(42, acquire);
16991 // r2 = x.load(relaxed);
16992 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16993 // lowered to just a load without a fence. A mfence flushes the store buffer,
16994 // making the optimization clearly correct.
16995 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16996 // otherwise, we might be able to be more agressive on relaxed idempotent
16997 // rmw. In practice, they do not look useful, so we don't try to be
16998 // especially clever.
16999 if (SynchScope == SingleThread) {
17000 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17001 // the IR level, so we must wrap it in an intrinsic.
17003 } else if (hasMFENCE(*Subtarget)) {
17004 Function *MFence = llvm::Intrinsic::getDeclaration(M,
17005 Intrinsic::x86_sse2_mfence);
17006 Builder.CreateCall(MFence);
17008 // FIXME: it might make sense to use a locked operation here but on a
17009 // different cache-line to prevent cache-line bouncing. In practice it
17010 // is probably a small win, and x86 processors without mfence are rare
17011 // enough that we do not bother.
17015 // Finally we can emit the atomic load.
17016 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17017 AI->getType()->getPrimitiveSizeInBits());
17018 Loaded->setAtomic(Order, SynchScope);
17019 AI->replaceAllUsesWith(Loaded);
17020 AI->eraseFromParent();
17024 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17025 SelectionDAG &DAG) {
17027 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17028 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17029 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17030 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17032 // The only fence that needs an instruction is a sequentially-consistent
17033 // cross-thread fence.
17034 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17035 if (hasMFENCE(*Subtarget))
17036 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17038 SDValue Chain = Op.getOperand(0);
17039 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17041 DAG.getRegister(X86::ESP, MVT::i32), // Base
17042 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
17043 DAG.getRegister(0, MVT::i32), // Index
17044 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
17045 DAG.getRegister(0, MVT::i32), // Segment.
17049 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17050 return SDValue(Res, 0);
17053 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17054 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17057 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17058 SelectionDAG &DAG) {
17059 MVT T = Op.getSimpleValueType();
17063 switch(T.SimpleTy) {
17064 default: llvm_unreachable("Invalid value type!");
17065 case MVT::i8: Reg = X86::AL; size = 1; break;
17066 case MVT::i16: Reg = X86::AX; size = 2; break;
17067 case MVT::i32: Reg = X86::EAX; size = 4; break;
17069 assert(Subtarget->is64Bit() && "Node not type legal!");
17070 Reg = X86::RAX; size = 8;
17073 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17074 Op.getOperand(2), SDValue());
17075 SDValue Ops[] = { cpIn.getValue(0),
17078 DAG.getTargetConstant(size, DL, MVT::i8),
17079 cpIn.getValue(1) };
17080 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17081 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17082 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17086 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17087 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17088 MVT::i32, cpOut.getValue(2));
17089 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17090 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17093 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17094 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17095 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17099 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17100 SelectionDAG &DAG) {
17101 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17102 MVT DstVT = Op.getSimpleValueType();
17104 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17105 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17106 if (DstVT != MVT::f64)
17107 // This conversion needs to be expanded.
17110 SDValue InVec = Op->getOperand(0);
17112 unsigned NumElts = SrcVT.getVectorNumElements();
17113 EVT SVT = SrcVT.getVectorElementType();
17115 // Widen the vector in input in the case of MVT::v2i32.
17116 // Example: from MVT::v2i32 to MVT::v4i32.
17117 SmallVector<SDValue, 16> Elts;
17118 for (unsigned i = 0, e = NumElts; i != e; ++i)
17119 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17120 DAG.getIntPtrConstant(i, dl)));
17122 // Explicitly mark the extra elements as Undef.
17123 Elts.append(NumElts, DAG.getUNDEF(SVT));
17125 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17126 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17127 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17128 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17129 DAG.getIntPtrConstant(0, dl));
17132 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17133 Subtarget->hasMMX() && "Unexpected custom BITCAST");
17134 assert((DstVT == MVT::i64 ||
17135 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17136 "Unexpected custom BITCAST");
17137 // i64 <=> MMX conversions are Legal.
17138 if (SrcVT==MVT::i64 && DstVT.isVector())
17140 if (DstVT==MVT::i64 && SrcVT.isVector())
17142 // MMX <=> MMX conversions are Legal.
17143 if (SrcVT.isVector() && DstVT.isVector())
17145 // All other conversions need to be expanded.
17149 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17150 SelectionDAG &DAG) {
17151 SDNode *Node = Op.getNode();
17154 Op = Op.getOperand(0);
17155 EVT VT = Op.getValueType();
17156 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17157 "CTPOP lowering only implemented for 128/256-bit wide vector types");
17159 unsigned NumElts = VT.getVectorNumElements();
17160 EVT EltVT = VT.getVectorElementType();
17161 unsigned Len = EltVT.getSizeInBits();
17163 // This is the vectorized version of the "best" algorithm from
17164 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17165 // with a minor tweak to use a series of adds + shifts instead of vector
17166 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17168 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17169 // v8i32 => Always profitable
17171 // FIXME: There a couple of possible improvements:
17173 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17174 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17176 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17177 "CTPOP not implemented for this vector element type.");
17179 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17180 // extra legalization.
17181 bool NeedsBitcast = EltVT == MVT::i32;
17182 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17184 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17186 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17188 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17191 // v = v - ((v >> 1) & 0x55555555...)
17192 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17193 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17194 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17196 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17198 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17199 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17201 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17203 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17204 if (VT != And.getValueType())
17205 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17206 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17208 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17209 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17210 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17211 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17212 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17214 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17215 if (NeedsBitcast) {
17216 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17217 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17218 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17221 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17222 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17223 if (VT != AndRHS.getValueType()) {
17224 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17225 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17227 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17229 // v = (v + (v >> 4)) & 0x0F0F0F0F...
17230 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17231 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17232 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17233 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17235 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17236 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17237 if (NeedsBitcast) {
17238 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17239 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17241 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17242 if (VT != And.getValueType())
17243 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17245 // The algorithm mentioned above uses:
17246 // v = (v * 0x01010101...) >> (Len - 8)
17248 // Change it to use vector adds + vector shifts which yield faster results on
17249 // Haswell than using vector integer multiplication.
17251 // For i32 elements:
17252 // v = v + (v >> 8)
17253 // v = v + (v >> 16)
17255 // For i64 elements:
17256 // v = v + (v >> 8)
17257 // v = v + (v >> 16)
17258 // v = v + (v >> 32)
17261 SmallVector<SDValue, 8> Csts;
17262 for (unsigned i = 8; i <= Len/2; i *= 2) {
17263 Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17264 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17265 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17266 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17270 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17271 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17273 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17274 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17275 if (NeedsBitcast) {
17276 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17277 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17279 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17280 if (VT != And.getValueType())
17281 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17286 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17287 SDNode *Node = Op.getNode();
17289 EVT T = Node->getValueType(0);
17290 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17291 DAG.getConstant(0, dl, T), Node->getOperand(2));
17292 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17293 cast<AtomicSDNode>(Node)->getMemoryVT(),
17294 Node->getOperand(0),
17295 Node->getOperand(1), negOp,
17296 cast<AtomicSDNode>(Node)->getMemOperand(),
17297 cast<AtomicSDNode>(Node)->getOrdering(),
17298 cast<AtomicSDNode>(Node)->getSynchScope());
17301 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17302 SDNode *Node = Op.getNode();
17304 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17306 // Convert seq_cst store -> xchg
17307 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17308 // FIXME: On 32-bit, store -> fist or movq would be more efficient
17309 // (The only way to get a 16-byte store is cmpxchg16b)
17310 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17311 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17312 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17313 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17314 cast<AtomicSDNode>(Node)->getMemoryVT(),
17315 Node->getOperand(0),
17316 Node->getOperand(1), Node->getOperand(2),
17317 cast<AtomicSDNode>(Node)->getMemOperand(),
17318 cast<AtomicSDNode>(Node)->getOrdering(),
17319 cast<AtomicSDNode>(Node)->getSynchScope());
17320 return Swap.getValue(1);
17322 // Other atomic stores have a simple pattern.
17326 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17327 EVT VT = Op.getNode()->getSimpleValueType(0);
17329 // Let legalize expand this if it isn't a legal type yet.
17330 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17333 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17336 bool ExtraOp = false;
17337 switch (Op.getOpcode()) {
17338 default: llvm_unreachable("Invalid code");
17339 case ISD::ADDC: Opc = X86ISD::ADD; break;
17340 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17341 case ISD::SUBC: Opc = X86ISD::SUB; break;
17342 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17346 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17348 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17349 Op.getOperand(1), Op.getOperand(2));
17352 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17353 SelectionDAG &DAG) {
17354 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17356 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17357 // which returns the values as { float, float } (in XMM0) or
17358 // { double, double } (which is returned in XMM0, XMM1).
17360 SDValue Arg = Op.getOperand(0);
17361 EVT ArgVT = Arg.getValueType();
17362 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17364 TargetLowering::ArgListTy Args;
17365 TargetLowering::ArgListEntry Entry;
17369 Entry.isSExt = false;
17370 Entry.isZExt = false;
17371 Args.push_back(Entry);
17373 bool isF64 = ArgVT == MVT::f64;
17374 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17375 // the small struct {f32, f32} is returned in (eax, edx). For f64,
17376 // the results are returned via SRet in memory.
17377 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
17378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17379 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17381 Type *RetTy = isF64
17382 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17383 : (Type*)VectorType::get(ArgTy, 4);
17385 TargetLowering::CallLoweringInfo CLI(DAG);
17386 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17387 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17389 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17392 // Returned in xmm0 and xmm1.
17393 return CallResult.first;
17395 // Returned in bits 0:31 and 32:64 xmm0.
17396 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17397 CallResult.first, DAG.getIntPtrConstant(0, dl));
17398 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17399 CallResult.first, DAG.getIntPtrConstant(1, dl));
17400 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17401 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17404 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17405 SelectionDAG &DAG) {
17406 assert(Subtarget->hasAVX512() &&
17407 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17409 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17410 EVT VT = N->getValue().getValueType();
17411 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17414 // X86 scatter kills mask register, so its type should be added to
17415 // the list of return values
17416 if (N->getNumValues() == 1) {
17417 SDValue Index = N->getIndex();
17418 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17419 !Index.getValueType().is512BitVector())
17420 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17422 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17423 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17424 N->getOperand(3), Index };
17426 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17427 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17428 return SDValue(NewScatter.getNode(), 0);
17433 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17434 SelectionDAG &DAG) {
17435 assert(Subtarget->hasAVX512() &&
17436 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17438 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17439 EVT VT = Op.getValueType();
17440 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17443 SDValue Index = N->getIndex();
17444 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17445 !Index.getValueType().is512BitVector()) {
17446 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17447 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17448 N->getOperand(3), Index };
17449 DAG.UpdateNodeOperands(N, Ops);
17454 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17455 SelectionDAG &DAG) const {
17456 // TODO: Eventually, the lowering of these nodes should be informed by or
17457 // deferred to the GC strategy for the function in which they appear. For
17458 // now, however, they must be lowered to something. Since they are logically
17459 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17460 // require special handling for these nodes), lower them as literal NOOPs for
17462 SmallVector<SDValue, 2> Ops;
17464 Ops.push_back(Op.getOperand(0));
17465 if (Op->getGluedNode())
17466 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17469 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17470 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17475 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17476 SelectionDAG &DAG) const {
17477 // TODO: Eventually, the lowering of these nodes should be informed by or
17478 // deferred to the GC strategy for the function in which they appear. For
17479 // now, however, they must be lowered to something. Since they are logically
17480 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17481 // require special handling for these nodes), lower them as literal NOOPs for
17483 SmallVector<SDValue, 2> Ops;
17485 Ops.push_back(Op.getOperand(0));
17486 if (Op->getGluedNode())
17487 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17490 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17491 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17496 /// LowerOperation - Provide custom lowering hooks for some operations.
17498 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17499 switch (Op.getOpcode()) {
17500 default: llvm_unreachable("Should not custom lower this!");
17501 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17502 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17503 return LowerCMP_SWAP(Op, Subtarget, DAG);
17504 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
17505 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
17506 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
17507 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
17508 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17509 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
17510 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17511 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17512 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17513 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17514 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17515 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17516 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17517 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17518 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17519 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17520 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17521 case ISD::SHL_PARTS:
17522 case ISD::SRA_PARTS:
17523 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17524 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17525 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17526 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17527 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17528 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17529 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17530 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17531 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17532 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17533 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17535 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17536 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17537 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17538 case ISD::SETCC: return LowerSETCC(Op, DAG);
17539 case ISD::SELECT: return LowerSELECT(Op, DAG);
17540 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17541 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17542 case ISD::VASTART: return LowerVASTART(Op, DAG);
17543 case ISD::VAARG: return LowerVAARG(Op, DAG);
17544 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17545 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17546 case ISD::INTRINSIC_VOID:
17547 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17548 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17549 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17550 case ISD::FRAME_TO_ARGS_OFFSET:
17551 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17552 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17553 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17554 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17555 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17556 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17557 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17558 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17559 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17560 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17561 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17562 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17563 case ISD::UMUL_LOHI:
17564 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17567 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17573 case ISD::UMULO: return LowerXALUO(Op, DAG);
17574 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17575 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17579 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17580 case ISD::ADD: return LowerADD(Op, DAG);
17581 case ISD::SUB: return LowerSUB(Op, DAG);
17582 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17583 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
17584 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
17585 case ISD::GC_TRANSITION_START:
17586 return LowerGC_TRANSITION_START(Op, DAG);
17587 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
17591 /// ReplaceNodeResults - Replace a node with an illegal result type
17592 /// with a new node built out of custom code.
17593 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17594 SmallVectorImpl<SDValue>&Results,
17595 SelectionDAG &DAG) const {
17597 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17598 switch (N->getOpcode()) {
17600 llvm_unreachable("Do not know how to custom type legalize this operation!");
17601 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17602 case X86ISD::FMINC:
17604 case X86ISD::FMAXC:
17605 case X86ISD::FMAX: {
17606 EVT VT = N->getValueType(0);
17607 if (VT != MVT::v2f32)
17608 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17609 SDValue UNDEF = DAG.getUNDEF(VT);
17610 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17611 N->getOperand(0), UNDEF);
17612 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17613 N->getOperand(1), UNDEF);
17614 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17617 case ISD::SIGN_EXTEND_INREG:
17622 // We don't want to expand or promote these.
17629 case ISD::UDIVREM: {
17630 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17631 Results.push_back(V);
17634 case ISD::FP_TO_SINT:
17635 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
17636 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17637 if (N->getOperand(0).getValueType() == MVT::f16)
17640 case ISD::FP_TO_UINT: {
17641 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17643 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17646 std::pair<SDValue,SDValue> Vals =
17647 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17648 SDValue FIST = Vals.first, StackSlot = Vals.second;
17649 if (FIST.getNode()) {
17650 EVT VT = N->getValueType(0);
17651 // Return a load from the stack slot.
17652 if (StackSlot.getNode())
17653 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17654 MachinePointerInfo(),
17655 false, false, false, 0));
17657 Results.push_back(FIST);
17661 case ISD::UINT_TO_FP: {
17662 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17663 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17664 N->getValueType(0) != MVT::v2f32)
17666 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17668 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17670 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17671 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17672 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17673 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17674 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17675 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17678 case ISD::FP_ROUND: {
17679 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17681 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17682 Results.push_back(V);
17685 case ISD::FP_EXTEND: {
17686 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17687 // No other ValueType for FP_EXTEND should reach this point.
17688 assert(N->getValueType(0) == MVT::v2f32 &&
17689 "Do not know how to legalize this Node");
17692 case ISD::INTRINSIC_W_CHAIN: {
17693 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17695 default : llvm_unreachable("Do not know how to custom type "
17696 "legalize this intrinsic operation!");
17697 case Intrinsic::x86_rdtsc:
17698 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17700 case Intrinsic::x86_rdtscp:
17701 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17703 case Intrinsic::x86_rdpmc:
17704 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17707 case ISD::READCYCLECOUNTER: {
17708 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17711 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17712 EVT T = N->getValueType(0);
17713 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17714 bool Regs64bit = T == MVT::i128;
17715 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17716 SDValue cpInL, cpInH;
17717 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17718 DAG.getConstant(0, dl, HalfT));
17719 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17720 DAG.getConstant(1, dl, HalfT));
17721 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17722 Regs64bit ? X86::RAX : X86::EAX,
17724 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17725 Regs64bit ? X86::RDX : X86::EDX,
17726 cpInH, cpInL.getValue(1));
17727 SDValue swapInL, swapInH;
17728 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17729 DAG.getConstant(0, dl, HalfT));
17730 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17731 DAG.getConstant(1, dl, HalfT));
17732 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17733 Regs64bit ? X86::RBX : X86::EBX,
17734 swapInL, cpInH.getValue(1));
17735 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17736 Regs64bit ? X86::RCX : X86::ECX,
17737 swapInH, swapInL.getValue(1));
17738 SDValue Ops[] = { swapInH.getValue(0),
17740 swapInH.getValue(1) };
17741 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17742 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17743 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17744 X86ISD::LCMPXCHG8_DAG;
17745 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17746 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17747 Regs64bit ? X86::RAX : X86::EAX,
17748 HalfT, Result.getValue(1));
17749 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17750 Regs64bit ? X86::RDX : X86::EDX,
17751 HalfT, cpOutL.getValue(2));
17752 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17754 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17755 MVT::i32, cpOutH.getValue(2));
17757 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17758 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17759 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17761 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17762 Results.push_back(Success);
17763 Results.push_back(EFLAGS.getValue(1));
17766 case ISD::ATOMIC_SWAP:
17767 case ISD::ATOMIC_LOAD_ADD:
17768 case ISD::ATOMIC_LOAD_SUB:
17769 case ISD::ATOMIC_LOAD_AND:
17770 case ISD::ATOMIC_LOAD_OR:
17771 case ISD::ATOMIC_LOAD_XOR:
17772 case ISD::ATOMIC_LOAD_NAND:
17773 case ISD::ATOMIC_LOAD_MIN:
17774 case ISD::ATOMIC_LOAD_MAX:
17775 case ISD::ATOMIC_LOAD_UMIN:
17776 case ISD::ATOMIC_LOAD_UMAX:
17777 case ISD::ATOMIC_LOAD: {
17778 // Delegate to generic TypeLegalization. Situations we can really handle
17779 // should have already been dealt with by AtomicExpandPass.cpp.
17782 case ISD::BITCAST: {
17783 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17784 EVT DstVT = N->getValueType(0);
17785 EVT SrcVT = N->getOperand(0)->getValueType(0);
17787 if (SrcVT != MVT::f64 ||
17788 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17791 unsigned NumElts = DstVT.getVectorNumElements();
17792 EVT SVT = DstVT.getVectorElementType();
17793 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17794 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17795 MVT::v2f64, N->getOperand(0));
17796 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17798 if (ExperimentalVectorWideningLegalization) {
17799 // If we are legalizing vectors by widening, we already have the desired
17800 // legal vector type, just return it.
17801 Results.push_back(ToVecInt);
17805 SmallVector<SDValue, 8> Elts;
17806 for (unsigned i = 0, e = NumElts; i != e; ++i)
17807 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17808 ToVecInt, DAG.getIntPtrConstant(i, dl)));
17810 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17815 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17816 switch ((X86ISD::NodeType)Opcode) {
17817 case X86ISD::FIRST_NUMBER: break;
17818 case X86ISD::BSF: return "X86ISD::BSF";
17819 case X86ISD::BSR: return "X86ISD::BSR";
17820 case X86ISD::SHLD: return "X86ISD::SHLD";
17821 case X86ISD::SHRD: return "X86ISD::SHRD";
17822 case X86ISD::FAND: return "X86ISD::FAND";
17823 case X86ISD::FANDN: return "X86ISD::FANDN";
17824 case X86ISD::FOR: return "X86ISD::FOR";
17825 case X86ISD::FXOR: return "X86ISD::FXOR";
17826 case X86ISD::FSRL: return "X86ISD::FSRL";
17827 case X86ISD::FILD: return "X86ISD::FILD";
17828 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17829 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17830 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17831 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17832 case X86ISD::FLD: return "X86ISD::FLD";
17833 case X86ISD::FST: return "X86ISD::FST";
17834 case X86ISD::CALL: return "X86ISD::CALL";
17835 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17836 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17837 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17838 case X86ISD::BT: return "X86ISD::BT";
17839 case X86ISD::CMP: return "X86ISD::CMP";
17840 case X86ISD::COMI: return "X86ISD::COMI";
17841 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17842 case X86ISD::CMPM: return "X86ISD::CMPM";
17843 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17844 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
17845 case X86ISD::SETCC: return "X86ISD::SETCC";
17846 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17847 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17848 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
17849 case X86ISD::CMOV: return "X86ISD::CMOV";
17850 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17851 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17852 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17853 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17854 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17855 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17856 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17857 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
17858 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
17859 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
17860 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17861 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17862 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17863 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17864 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17865 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
17866 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17867 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17868 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17869 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17870 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17871 case X86ISD::ADDUS: return "X86ISD::ADDUS";
17872 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17873 case X86ISD::HADD: return "X86ISD::HADD";
17874 case X86ISD::HSUB: return "X86ISD::HSUB";
17875 case X86ISD::FHADD: return "X86ISD::FHADD";
17876 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17877 case X86ISD::UMAX: return "X86ISD::UMAX";
17878 case X86ISD::UMIN: return "X86ISD::UMIN";
17879 case X86ISD::SMAX: return "X86ISD::SMAX";
17880 case X86ISD::SMIN: return "X86ISD::SMIN";
17881 case X86ISD::FMAX: return "X86ISD::FMAX";
17882 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
17883 case X86ISD::FMIN: return "X86ISD::FMIN";
17884 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
17885 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17886 case X86ISD::FMINC: return "X86ISD::FMINC";
17887 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17888 case X86ISD::FRCP: return "X86ISD::FRCP";
17889 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17890 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17891 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17892 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17893 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17894 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17895 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17896 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17897 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17898 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17899 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17900 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17901 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17902 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17903 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17904 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17905 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17906 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17907 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17908 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17909 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17910 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17911 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17912 case X86ISD::VSHL: return "X86ISD::VSHL";
17913 case X86ISD::VSRL: return "X86ISD::VSRL";
17914 case X86ISD::VSRA: return "X86ISD::VSRA";
17915 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17916 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17917 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17918 case X86ISD::CMPP: return "X86ISD::CMPP";
17919 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17920 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17921 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17922 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17923 case X86ISD::ADD: return "X86ISD::ADD";
17924 case X86ISD::SUB: return "X86ISD::SUB";
17925 case X86ISD::ADC: return "X86ISD::ADC";
17926 case X86ISD::SBB: return "X86ISD::SBB";
17927 case X86ISD::SMUL: return "X86ISD::SMUL";
17928 case X86ISD::UMUL: return "X86ISD::UMUL";
17929 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17930 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17931 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17932 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17933 case X86ISD::INC: return "X86ISD::INC";
17934 case X86ISD::DEC: return "X86ISD::DEC";
17935 case X86ISD::OR: return "X86ISD::OR";
17936 case X86ISD::XOR: return "X86ISD::XOR";
17937 case X86ISD::AND: return "X86ISD::AND";
17938 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17939 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17940 case X86ISD::PTEST: return "X86ISD::PTEST";
17941 case X86ISD::TESTP: return "X86ISD::TESTP";
17942 case X86ISD::TESTM: return "X86ISD::TESTM";
17943 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17944 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17945 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17946 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17947 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17948 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17949 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17950 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17951 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17952 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17953 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17954 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17955 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17956 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17957 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17958 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17959 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17960 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17961 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17962 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17963 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17964 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17965 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17966 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17967 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
17968 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17969 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17970 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17971 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17972 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17973 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17974 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17975 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17976 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17977 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17978 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17979 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17980 case X86ISD::MFENCE: return "X86ISD::MFENCE";
17981 case X86ISD::SFENCE: return "X86ISD::SFENCE";
17982 case X86ISD::LFENCE: return "X86ISD::LFENCE";
17983 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17984 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17985 case X86ISD::SAHF: return "X86ISD::SAHF";
17986 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17987 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17988 case X86ISD::FMADD: return "X86ISD::FMADD";
17989 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17990 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17991 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17992 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17993 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17994 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
17995 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
17996 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
17997 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
17998 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
17999 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
18000 case X86ISD::RNDSCALE: return "X86ISD::RNDSCALE";
18001 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
18002 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
18003 case X86ISD::XTEST: return "X86ISD::XTEST";
18004 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
18005 case X86ISD::EXPAND: return "X86ISD::EXPAND";
18006 case X86ISD::SELECT: return "X86ISD::SELECT";
18007 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
18008 case X86ISD::RCP28: return "X86ISD::RCP28";
18009 case X86ISD::EXP2: return "X86ISD::EXP2";
18010 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
18011 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
18012 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
18013 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
18014 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
18015 case X86ISD::ADDS: return "X86ISD::ADDS";
18016 case X86ISD::SUBS: return "X86ISD::SUBS";
18021 // isLegalAddressingMode - Return true if the addressing mode represented
18022 // by AM is legal for this target, for a load/store of the specified type.
18023 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18025 // X86 supports extremely general addressing modes.
18026 CodeModel::Model M = getTargetMachine().getCodeModel();
18027 Reloc::Model R = getTargetMachine().getRelocationModel();
18029 // X86 allows a sign-extended 32-bit immediate field as a displacement.
18030 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18035 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18037 // If a reference to this global requires an extra load, we can't fold it.
18038 if (isGlobalStubReference(GVFlags))
18041 // If BaseGV requires a register for the PIC base, we cannot also have a
18042 // BaseReg specified.
18043 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18046 // If lower 4G is not available, then we must use rip-relative addressing.
18047 if ((M != CodeModel::Small || R != Reloc::Static) &&
18048 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18052 switch (AM.Scale) {
18058 // These scales always work.
18063 // These scales are formed with basereg+scalereg. Only accept if there is
18068 default: // Other stuff never works.
18075 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18076 unsigned Bits = Ty->getScalarSizeInBits();
18078 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18079 // particularly cheaper than those without.
18083 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18084 // variable shifts just as cheap as scalar ones.
18085 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18088 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18089 // fully general vector.
18093 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18094 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18096 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18097 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18098 return NumBits1 > NumBits2;
18101 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18102 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18105 if (!isTypeLegal(EVT::getEVT(Ty1)))
18108 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18110 // Assuming the caller doesn't have a zeroext or signext return parameter,
18111 // truncation all the way down to i1 is valid.
18115 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18116 return isInt<32>(Imm);
18119 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18120 // Can also use sub to handle negated immediates.
18121 return isInt<32>(Imm);
18124 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18125 if (!VT1.isInteger() || !VT2.isInteger())
18127 unsigned NumBits1 = VT1.getSizeInBits();
18128 unsigned NumBits2 = VT2.getSizeInBits();
18129 return NumBits1 > NumBits2;
18132 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18133 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18134 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18137 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18138 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18139 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18142 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18143 EVT VT1 = Val.getValueType();
18144 if (isZExtFree(VT1, VT2))
18147 if (Val.getOpcode() != ISD::LOAD)
18150 if (!VT1.isSimple() || !VT1.isInteger() ||
18151 !VT2.isSimple() || !VT2.isInteger())
18154 switch (VT1.getSimpleVT().SimpleTy) {
18159 // X86 has 8, 16, and 32-bit zero-extending loads.
18166 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18169 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18170 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18173 VT = VT.getScalarType();
18175 if (!VT.isSimple())
18178 switch (VT.getSimpleVT().SimpleTy) {
18189 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18190 // i16 instructions are longer (0x66 prefix) and potentially slower.
18191 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18194 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18195 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18196 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18197 /// are assumed to be legal.
18199 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18201 if (!VT.isSimple())
18204 // Not for i1 vectors
18205 if (VT.getScalarType() == MVT::i1)
18208 // Very little shuffling can be done for 64-bit vectors right now.
18209 if (VT.getSizeInBits() == 64)
18212 // We only care that the types being shuffled are legal. The lowering can
18213 // handle any possible shuffle mask that results.
18214 return isTypeLegal(VT.getSimpleVT());
18218 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18220 // Just delegate to the generic legality, clear masks aren't special.
18221 return isShuffleMaskLegal(Mask, VT);
18224 //===----------------------------------------------------------------------===//
18225 // X86 Scheduler Hooks
18226 //===----------------------------------------------------------------------===//
18228 /// Utility function to emit xbegin specifying the start of an RTM region.
18229 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18230 const TargetInstrInfo *TII) {
18231 DebugLoc DL = MI->getDebugLoc();
18233 const BasicBlock *BB = MBB->getBasicBlock();
18234 MachineFunction::iterator I = MBB;
18237 // For the v = xbegin(), we generate
18248 MachineBasicBlock *thisMBB = MBB;
18249 MachineFunction *MF = MBB->getParent();
18250 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18251 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18252 MF->insert(I, mainMBB);
18253 MF->insert(I, sinkMBB);
18255 // Transfer the remainder of BB and its successor edges to sinkMBB.
18256 sinkMBB->splice(sinkMBB->begin(), MBB,
18257 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18258 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18262 // # fallthrough to mainMBB
18263 // # abortion to sinkMBB
18264 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18265 thisMBB->addSuccessor(mainMBB);
18266 thisMBB->addSuccessor(sinkMBB);
18270 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18271 mainMBB->addSuccessor(sinkMBB);
18274 // EAX is live into the sinkMBB
18275 sinkMBB->addLiveIn(X86::EAX);
18276 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18277 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18280 MI->eraseFromParent();
18284 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18285 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18286 // in the .td file.
18287 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18288 const TargetInstrInfo *TII) {
18290 switch (MI->getOpcode()) {
18291 default: llvm_unreachable("illegal opcode!");
18292 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
18293 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18294 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
18295 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18296 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
18297 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18298 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
18299 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18302 DebugLoc dl = MI->getDebugLoc();
18303 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18305 unsigned NumArgs = MI->getNumOperands();
18306 for (unsigned i = 1; i < NumArgs; ++i) {
18307 MachineOperand &Op = MI->getOperand(i);
18308 if (!(Op.isReg() && Op.isImplicit()))
18309 MIB.addOperand(Op);
18311 if (MI->hasOneMemOperand())
18312 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18314 BuildMI(*BB, MI, dl,
18315 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18316 .addReg(X86::XMM0);
18318 MI->eraseFromParent();
18322 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18323 // defs in an instruction pattern
18324 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18325 const TargetInstrInfo *TII) {
18327 switch (MI->getOpcode()) {
18328 default: llvm_unreachable("illegal opcode!");
18329 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
18330 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18331 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
18332 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18333 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
18334 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18335 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
18336 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18339 DebugLoc dl = MI->getDebugLoc();
18340 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18342 unsigned NumArgs = MI->getNumOperands(); // remove the results
18343 for (unsigned i = 1; i < NumArgs; ++i) {
18344 MachineOperand &Op = MI->getOperand(i);
18345 if (!(Op.isReg() && Op.isImplicit()))
18346 MIB.addOperand(Op);
18348 if (MI->hasOneMemOperand())
18349 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18351 BuildMI(*BB, MI, dl,
18352 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18355 MI->eraseFromParent();
18359 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18360 const X86Subtarget *Subtarget) {
18361 DebugLoc dl = MI->getDebugLoc();
18362 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18363 // Address into RAX/EAX, other two args into ECX, EDX.
18364 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18365 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18366 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18367 for (int i = 0; i < X86::AddrNumOperands; ++i)
18368 MIB.addOperand(MI->getOperand(i));
18370 unsigned ValOps = X86::AddrNumOperands;
18371 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18372 .addReg(MI->getOperand(ValOps).getReg());
18373 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18374 .addReg(MI->getOperand(ValOps+1).getReg());
18376 // The instruction doesn't actually take any operands though.
18377 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18379 MI->eraseFromParent(); // The pseudo is gone now.
18383 MachineBasicBlock *
18384 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18385 MachineBasicBlock *MBB) const {
18386 // Emit va_arg instruction on X86-64.
18388 // Operands to this pseudo-instruction:
18389 // 0 ) Output : destination address (reg)
18390 // 1-5) Input : va_list address (addr, i64mem)
18391 // 6 ) ArgSize : Size (in bytes) of vararg type
18392 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18393 // 8 ) Align : Alignment of type
18394 // 9 ) EFLAGS (implicit-def)
18396 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18397 static_assert(X86::AddrNumOperands == 5,
18398 "VAARG_64 assumes 5 address operands");
18400 unsigned DestReg = MI->getOperand(0).getReg();
18401 MachineOperand &Base = MI->getOperand(1);
18402 MachineOperand &Scale = MI->getOperand(2);
18403 MachineOperand &Index = MI->getOperand(3);
18404 MachineOperand &Disp = MI->getOperand(4);
18405 MachineOperand &Segment = MI->getOperand(5);
18406 unsigned ArgSize = MI->getOperand(6).getImm();
18407 unsigned ArgMode = MI->getOperand(7).getImm();
18408 unsigned Align = MI->getOperand(8).getImm();
18410 // Memory Reference
18411 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18412 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18413 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18415 // Machine Information
18416 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18417 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18418 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18419 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18420 DebugLoc DL = MI->getDebugLoc();
18422 // struct va_list {
18425 // i64 overflow_area (address)
18426 // i64 reg_save_area (address)
18428 // sizeof(va_list) = 24
18429 // alignment(va_list) = 8
18431 unsigned TotalNumIntRegs = 6;
18432 unsigned TotalNumXMMRegs = 8;
18433 bool UseGPOffset = (ArgMode == 1);
18434 bool UseFPOffset = (ArgMode == 2);
18435 unsigned MaxOffset = TotalNumIntRegs * 8 +
18436 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18438 /* Align ArgSize to a multiple of 8 */
18439 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18440 bool NeedsAlign = (Align > 8);
18442 MachineBasicBlock *thisMBB = MBB;
18443 MachineBasicBlock *overflowMBB;
18444 MachineBasicBlock *offsetMBB;
18445 MachineBasicBlock *endMBB;
18447 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
18448 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
18449 unsigned OffsetReg = 0;
18451 if (!UseGPOffset && !UseFPOffset) {
18452 // If we only pull from the overflow region, we don't create a branch.
18453 // We don't need to alter control flow.
18454 OffsetDestReg = 0; // unused
18455 OverflowDestReg = DestReg;
18457 offsetMBB = nullptr;
18458 overflowMBB = thisMBB;
18461 // First emit code to check if gp_offset (or fp_offset) is below the bound.
18462 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18463 // If not, pull from overflow_area. (branch to overflowMBB)
18468 // offsetMBB overflowMBB
18473 // Registers for the PHI in endMBB
18474 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18475 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18477 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18478 MachineFunction *MF = MBB->getParent();
18479 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18480 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18481 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18483 MachineFunction::iterator MBBIter = MBB;
18486 // Insert the new basic blocks
18487 MF->insert(MBBIter, offsetMBB);
18488 MF->insert(MBBIter, overflowMBB);
18489 MF->insert(MBBIter, endMBB);
18491 // Transfer the remainder of MBB and its successor edges to endMBB.
18492 endMBB->splice(endMBB->begin(), thisMBB,
18493 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18494 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18496 // Make offsetMBB and overflowMBB successors of thisMBB
18497 thisMBB->addSuccessor(offsetMBB);
18498 thisMBB->addSuccessor(overflowMBB);
18500 // endMBB is a successor of both offsetMBB and overflowMBB
18501 offsetMBB->addSuccessor(endMBB);
18502 overflowMBB->addSuccessor(endMBB);
18504 // Load the offset value into a register
18505 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18506 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18510 .addDisp(Disp, UseFPOffset ? 4 : 0)
18511 .addOperand(Segment)
18512 .setMemRefs(MMOBegin, MMOEnd);
18514 // Check if there is enough room left to pull this argument.
18515 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18517 .addImm(MaxOffset + 8 - ArgSizeA8);
18519 // Branch to "overflowMBB" if offset >= max
18520 // Fall through to "offsetMBB" otherwise
18521 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18522 .addMBB(overflowMBB);
18525 // In offsetMBB, emit code to use the reg_save_area.
18527 assert(OffsetReg != 0);
18529 // Read the reg_save_area address.
18530 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18531 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18536 .addOperand(Segment)
18537 .setMemRefs(MMOBegin, MMOEnd);
18539 // Zero-extend the offset
18540 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18541 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18544 .addImm(X86::sub_32bit);
18546 // Add the offset to the reg_save_area to get the final address.
18547 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18548 .addReg(OffsetReg64)
18549 .addReg(RegSaveReg);
18551 // Compute the offset for the next argument
18552 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18553 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18555 .addImm(UseFPOffset ? 16 : 8);
18557 // Store it back into the va_list.
18558 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18562 .addDisp(Disp, UseFPOffset ? 4 : 0)
18563 .addOperand(Segment)
18564 .addReg(NextOffsetReg)
18565 .setMemRefs(MMOBegin, MMOEnd);
18568 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18573 // Emit code to use overflow area
18576 // Load the overflow_area address into a register.
18577 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18578 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18583 .addOperand(Segment)
18584 .setMemRefs(MMOBegin, MMOEnd);
18586 // If we need to align it, do so. Otherwise, just copy the address
18587 // to OverflowDestReg.
18589 // Align the overflow address
18590 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18591 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18593 // aligned_addr = (addr + (align-1)) & ~(align-1)
18594 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18595 .addReg(OverflowAddrReg)
18598 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18600 .addImm(~(uint64_t)(Align-1));
18602 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18603 .addReg(OverflowAddrReg);
18606 // Compute the next overflow address after this argument.
18607 // (the overflow address should be kept 8-byte aligned)
18608 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18609 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18610 .addReg(OverflowDestReg)
18611 .addImm(ArgSizeA8);
18613 // Store the new overflow address.
18614 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18619 .addOperand(Segment)
18620 .addReg(NextAddrReg)
18621 .setMemRefs(MMOBegin, MMOEnd);
18623 // If we branched, emit the PHI to the front of endMBB.
18625 BuildMI(*endMBB, endMBB->begin(), DL,
18626 TII->get(X86::PHI), DestReg)
18627 .addReg(OffsetDestReg).addMBB(offsetMBB)
18628 .addReg(OverflowDestReg).addMBB(overflowMBB);
18631 // Erase the pseudo instruction
18632 MI->eraseFromParent();
18637 MachineBasicBlock *
18638 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18640 MachineBasicBlock *MBB) const {
18641 // Emit code to save XMM registers to the stack. The ABI says that the
18642 // number of registers to save is given in %al, so it's theoretically
18643 // possible to do an indirect jump trick to avoid saving all of them,
18644 // however this code takes a simpler approach and just executes all
18645 // of the stores if %al is non-zero. It's less code, and it's probably
18646 // easier on the hardware branch predictor, and stores aren't all that
18647 // expensive anyway.
18649 // Create the new basic blocks. One block contains all the XMM stores,
18650 // and one block is the final destination regardless of whether any
18651 // stores were performed.
18652 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18653 MachineFunction *F = MBB->getParent();
18654 MachineFunction::iterator MBBIter = MBB;
18656 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18657 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18658 F->insert(MBBIter, XMMSaveMBB);
18659 F->insert(MBBIter, EndMBB);
18661 // Transfer the remainder of MBB and its successor edges to EndMBB.
18662 EndMBB->splice(EndMBB->begin(), MBB,
18663 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18664 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18666 // The original block will now fall through to the XMM save block.
18667 MBB->addSuccessor(XMMSaveMBB);
18668 // The XMMSaveMBB will fall through to the end block.
18669 XMMSaveMBB->addSuccessor(EndMBB);
18671 // Now add the instructions.
18672 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18673 DebugLoc DL = MI->getDebugLoc();
18675 unsigned CountReg = MI->getOperand(0).getReg();
18676 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18677 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18679 if (!Subtarget->isTargetWin64()) {
18680 // If %al is 0, branch around the XMM save block.
18681 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18682 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18683 MBB->addSuccessor(EndMBB);
18686 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18687 // that was just emitted, but clearly shouldn't be "saved".
18688 assert((MI->getNumOperands() <= 3 ||
18689 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18690 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18691 && "Expected last argument to be EFLAGS");
18692 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18693 // In the XMM save block, save all the XMM argument registers.
18694 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18695 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18696 MachineMemOperand *MMO =
18697 F->getMachineMemOperand(
18698 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18699 MachineMemOperand::MOStore,
18700 /*Size=*/16, /*Align=*/16);
18701 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18702 .addFrameIndex(RegSaveFrameIndex)
18703 .addImm(/*Scale=*/1)
18704 .addReg(/*IndexReg=*/0)
18705 .addImm(/*Disp=*/Offset)
18706 .addReg(/*Segment=*/0)
18707 .addReg(MI->getOperand(i).getReg())
18708 .addMemOperand(MMO);
18711 MI->eraseFromParent(); // The pseudo instruction is gone now.
18716 // The EFLAGS operand of SelectItr might be missing a kill marker
18717 // because there were multiple uses of EFLAGS, and ISel didn't know
18718 // which to mark. Figure out whether SelectItr should have had a
18719 // kill marker, and set it if it should. Returns the correct kill
18721 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18722 MachineBasicBlock* BB,
18723 const TargetRegisterInfo* TRI) {
18724 // Scan forward through BB for a use/def of EFLAGS.
18725 MachineBasicBlock::iterator miI(std::next(SelectItr));
18726 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18727 const MachineInstr& mi = *miI;
18728 if (mi.readsRegister(X86::EFLAGS))
18730 if (mi.definesRegister(X86::EFLAGS))
18731 break; // Should have kill-flag - update below.
18734 // If we hit the end of the block, check whether EFLAGS is live into a
18736 if (miI == BB->end()) {
18737 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18738 sEnd = BB->succ_end();
18739 sItr != sEnd; ++sItr) {
18740 MachineBasicBlock* succ = *sItr;
18741 if (succ->isLiveIn(X86::EFLAGS))
18746 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18747 // out. SelectMI should have a kill flag on EFLAGS.
18748 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18752 MachineBasicBlock *
18753 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18754 MachineBasicBlock *BB) const {
18755 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18756 DebugLoc DL = MI->getDebugLoc();
18758 // To "insert" a SELECT_CC instruction, we actually have to insert the
18759 // diamond control-flow pattern. The incoming instruction knows the
18760 // destination vreg to set, the condition code register to branch on, the
18761 // true/false values to select between, and a branch opcode to use.
18762 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18763 MachineFunction::iterator It = BB;
18769 // cmpTY ccX, r1, r2
18771 // fallthrough --> copy0MBB
18772 MachineBasicBlock *thisMBB = BB;
18773 MachineFunction *F = BB->getParent();
18775 // We also lower double CMOVs:
18776 // (CMOV (CMOV F, T, cc1), T, cc2)
18777 // to two successives branches. For that, we look for another CMOV as the
18778 // following instruction.
18780 // Without this, we would add a PHI between the two jumps, which ends up
18781 // creating a few copies all around. For instance, for
18783 // (sitofp (zext (fcmp une)))
18785 // we would generate:
18787 // ucomiss %xmm1, %xmm0
18788 // movss <1.0f>, %xmm0
18789 // movaps %xmm0, %xmm1
18791 // xorps %xmm1, %xmm1
18794 // movaps %xmm1, %xmm0
18798 // because this custom-inserter would have generated:
18810 // A: X = ...; Y = ...
18812 // C: Z = PHI [X, A], [Y, B]
18814 // E: PHI [X, C], [Z, D]
18816 // If we lower both CMOVs in a single step, we can instead generate:
18828 // A: X = ...; Y = ...
18830 // E: PHI [X, A], [X, C], [Y, D]
18832 // Which, in our sitofp/fcmp example, gives us something like:
18834 // ucomiss %xmm1, %xmm0
18835 // movss <1.0f>, %xmm0
18838 // xorps %xmm0, %xmm0
18842 MachineInstr *NextCMOV = nullptr;
18843 MachineBasicBlock::iterator NextMIIt =
18844 std::next(MachineBasicBlock::iterator(MI));
18845 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18846 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18847 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18848 NextCMOV = &*NextMIIt;
18850 MachineBasicBlock *jcc1MBB = nullptr;
18852 // If we have a double CMOV, we lower it to two successive branches to
18853 // the same block. EFLAGS is used by both, so mark it as live in the second.
18855 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18856 F->insert(It, jcc1MBB);
18857 jcc1MBB->addLiveIn(X86::EFLAGS);
18860 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18861 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18862 F->insert(It, copy0MBB);
18863 F->insert(It, sinkMBB);
18865 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18866 // live into the sink and copy blocks.
18867 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18869 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18870 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18871 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18872 copy0MBB->addLiveIn(X86::EFLAGS);
18873 sinkMBB->addLiveIn(X86::EFLAGS);
18876 // Transfer the remainder of BB and its successor edges to sinkMBB.
18877 sinkMBB->splice(sinkMBB->begin(), BB,
18878 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18879 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18881 // Add the true and fallthrough blocks as its successors.
18883 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18884 BB->addSuccessor(jcc1MBB);
18886 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18887 // jump to the sinkMBB.
18888 jcc1MBB->addSuccessor(copy0MBB);
18889 jcc1MBB->addSuccessor(sinkMBB);
18891 BB->addSuccessor(copy0MBB);
18894 // The true block target of the first (or only) branch is always sinkMBB.
18895 BB->addSuccessor(sinkMBB);
18897 // Create the conditional branch instruction.
18899 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18900 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18903 unsigned Opc2 = X86::GetCondBranchFromCond(
18904 (X86::CondCode)NextCMOV->getOperand(3).getImm());
18905 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18909 // %FalseValue = ...
18910 // # fallthrough to sinkMBB
18911 copy0MBB->addSuccessor(sinkMBB);
18914 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18916 MachineInstrBuilder MIB =
18917 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18918 MI->getOperand(0).getReg())
18919 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18920 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18922 // If we have a double CMOV, the second Jcc provides the same incoming
18923 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18925 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18926 // Copy the PHI result to the register defined by the second CMOV.
18927 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18928 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18929 .addReg(MI->getOperand(0).getReg());
18930 NextCMOV->eraseFromParent();
18933 MI->eraseFromParent(); // The pseudo instruction is gone now.
18937 MachineBasicBlock *
18938 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18939 MachineBasicBlock *BB) const {
18940 MachineFunction *MF = BB->getParent();
18941 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18942 DebugLoc DL = MI->getDebugLoc();
18943 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18945 assert(MF->shouldSplitStack());
18947 const bool Is64Bit = Subtarget->is64Bit();
18948 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18950 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18951 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18954 // ... [Till the alloca]
18955 // If stacklet is not large enough, jump to mallocMBB
18958 // Allocate by subtracting from RSP
18959 // Jump to continueMBB
18962 // Allocate by call to runtime
18966 // [rest of original BB]
18969 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18970 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18971 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18973 MachineRegisterInfo &MRI = MF->getRegInfo();
18974 const TargetRegisterClass *AddrRegClass =
18975 getRegClassFor(getPointerTy());
18977 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18978 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18979 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18980 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18981 sizeVReg = MI->getOperand(1).getReg(),
18982 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18984 MachineFunction::iterator MBBIter = BB;
18987 MF->insert(MBBIter, bumpMBB);
18988 MF->insert(MBBIter, mallocMBB);
18989 MF->insert(MBBIter, continueMBB);
18991 continueMBB->splice(continueMBB->begin(), BB,
18992 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18993 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18995 // Add code to the main basic block to check if the stack limit has been hit,
18996 // and if so, jump to mallocMBB otherwise to bumpMBB.
18997 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18998 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18999 .addReg(tmpSPVReg).addReg(sizeVReg);
19000 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19001 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19002 .addReg(SPLimitVReg);
19003 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19005 // bumpMBB simply decreases the stack pointer, since we know the current
19006 // stacklet has enough space.
19007 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19008 .addReg(SPLimitVReg);
19009 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19010 .addReg(SPLimitVReg);
19011 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19013 // Calls into a routine in libgcc to allocate more space from the heap.
19014 const uint32_t *RegMask =
19015 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19017 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19019 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19020 .addExternalSymbol("__morestack_allocate_stack_space")
19021 .addRegMask(RegMask)
19022 .addReg(X86::RDI, RegState::Implicit)
19023 .addReg(X86::RAX, RegState::ImplicitDefine);
19024 } else if (Is64Bit) {
19025 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19027 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19028 .addExternalSymbol("__morestack_allocate_stack_space")
19029 .addRegMask(RegMask)
19030 .addReg(X86::EDI, RegState::Implicit)
19031 .addReg(X86::EAX, RegState::ImplicitDefine);
19033 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19035 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19036 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19037 .addExternalSymbol("__morestack_allocate_stack_space")
19038 .addRegMask(RegMask)
19039 .addReg(X86::EAX, RegState::ImplicitDefine);
19043 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19046 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19047 .addReg(IsLP64 ? X86::RAX : X86::EAX);
19048 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19050 // Set up the CFG correctly.
19051 BB->addSuccessor(bumpMBB);
19052 BB->addSuccessor(mallocMBB);
19053 mallocMBB->addSuccessor(continueMBB);
19054 bumpMBB->addSuccessor(continueMBB);
19056 // Take care of the PHI nodes.
19057 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19058 MI->getOperand(0).getReg())
19059 .addReg(mallocPtrVReg).addMBB(mallocMBB)
19060 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19062 // Delete the original pseudo instruction.
19063 MI->eraseFromParent();
19066 return continueMBB;
19069 MachineBasicBlock *
19070 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19071 MachineBasicBlock *BB) const {
19072 DebugLoc DL = MI->getDebugLoc();
19074 assert(!Subtarget->isTargetMachO());
19076 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19078 MI->eraseFromParent(); // The pseudo instruction is gone now.
19082 MachineBasicBlock *
19083 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19084 MachineBasicBlock *BB) const {
19085 // This is pretty easy. We're taking the value that we received from
19086 // our load from the relocation, sticking it in either RDI (x86-64)
19087 // or EAX and doing an indirect call. The return value will then
19088 // be in the normal return register.
19089 MachineFunction *F = BB->getParent();
19090 const X86InstrInfo *TII = Subtarget->getInstrInfo();
19091 DebugLoc DL = MI->getDebugLoc();
19093 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19094 assert(MI->getOperand(3).isGlobal() && "This should be a global");
19096 // Get a register mask for the lowered call.
19097 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19098 // proper register mask.
19099 const uint32_t *RegMask =
19100 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19101 if (Subtarget->is64Bit()) {
19102 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19103 TII->get(X86::MOV64rm), X86::RDI)
19105 .addImm(0).addReg(0)
19106 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19107 MI->getOperand(3).getTargetFlags())
19109 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19110 addDirectMem(MIB, X86::RDI);
19111 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19112 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19113 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19114 TII->get(X86::MOV32rm), X86::EAX)
19116 .addImm(0).addReg(0)
19117 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19118 MI->getOperand(3).getTargetFlags())
19120 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19121 addDirectMem(MIB, X86::EAX);
19122 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19124 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19125 TII->get(X86::MOV32rm), X86::EAX)
19126 .addReg(TII->getGlobalBaseReg(F))
19127 .addImm(0).addReg(0)
19128 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19129 MI->getOperand(3).getTargetFlags())
19131 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19132 addDirectMem(MIB, X86::EAX);
19133 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19136 MI->eraseFromParent(); // The pseudo instruction is gone now.
19140 MachineBasicBlock *
19141 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19142 MachineBasicBlock *MBB) const {
19143 DebugLoc DL = MI->getDebugLoc();
19144 MachineFunction *MF = MBB->getParent();
19145 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19146 MachineRegisterInfo &MRI = MF->getRegInfo();
19148 const BasicBlock *BB = MBB->getBasicBlock();
19149 MachineFunction::iterator I = MBB;
19152 // Memory Reference
19153 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19154 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19157 unsigned MemOpndSlot = 0;
19159 unsigned CurOp = 0;
19161 DstReg = MI->getOperand(CurOp++).getReg();
19162 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19163 assert(RC->hasType(MVT::i32) && "Invalid destination!");
19164 unsigned mainDstReg = MRI.createVirtualRegister(RC);
19165 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19167 MemOpndSlot = CurOp;
19169 MVT PVT = getPointerTy();
19170 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19171 "Invalid Pointer Size!");
19173 // For v = setjmp(buf), we generate
19176 // buf[LabelOffset] = restoreMBB
19177 // SjLjSetup restoreMBB
19183 // v = phi(main, restore)
19186 // if base pointer being used, load it from frame
19189 MachineBasicBlock *thisMBB = MBB;
19190 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19191 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19192 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19193 MF->insert(I, mainMBB);
19194 MF->insert(I, sinkMBB);
19195 MF->push_back(restoreMBB);
19197 MachineInstrBuilder MIB;
19199 // Transfer the remainder of BB and its successor edges to sinkMBB.
19200 sinkMBB->splice(sinkMBB->begin(), MBB,
19201 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19202 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19205 unsigned PtrStoreOpc = 0;
19206 unsigned LabelReg = 0;
19207 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19208 Reloc::Model RM = MF->getTarget().getRelocationModel();
19209 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19210 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19212 // Prepare IP either in reg or imm.
19213 if (!UseImmLabel) {
19214 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19215 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19216 LabelReg = MRI.createVirtualRegister(PtrRC);
19217 if (Subtarget->is64Bit()) {
19218 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19222 .addMBB(restoreMBB)
19225 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19226 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19227 .addReg(XII->getGlobalBaseReg(MF))
19230 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19234 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19236 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19237 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19238 if (i == X86::AddrDisp)
19239 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19241 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19244 MIB.addReg(LabelReg);
19246 MIB.addMBB(restoreMBB);
19247 MIB.setMemRefs(MMOBegin, MMOEnd);
19249 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19250 .addMBB(restoreMBB);
19252 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19253 MIB.addRegMask(RegInfo->getNoPreservedMask());
19254 thisMBB->addSuccessor(mainMBB);
19255 thisMBB->addSuccessor(restoreMBB);
19259 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19260 mainMBB->addSuccessor(sinkMBB);
19263 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19264 TII->get(X86::PHI), DstReg)
19265 .addReg(mainDstReg).addMBB(mainMBB)
19266 .addReg(restoreDstReg).addMBB(restoreMBB);
19269 if (RegInfo->hasBasePointer(*MF)) {
19270 const bool Uses64BitFramePtr =
19271 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19272 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19273 X86FI->setRestoreBasePointer(MF);
19274 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19275 unsigned BasePtr = RegInfo->getBaseRegister();
19276 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19277 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19278 FramePtr, true, X86FI->getRestoreBasePointerOffset())
19279 .setMIFlag(MachineInstr::FrameSetup);
19281 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19282 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19283 restoreMBB->addSuccessor(sinkMBB);
19285 MI->eraseFromParent();
19289 MachineBasicBlock *
19290 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19291 MachineBasicBlock *MBB) const {
19292 DebugLoc DL = MI->getDebugLoc();
19293 MachineFunction *MF = MBB->getParent();
19294 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19295 MachineRegisterInfo &MRI = MF->getRegInfo();
19297 // Memory Reference
19298 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19299 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19301 MVT PVT = getPointerTy();
19302 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19303 "Invalid Pointer Size!");
19305 const TargetRegisterClass *RC =
19306 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19307 unsigned Tmp = MRI.createVirtualRegister(RC);
19308 // Since FP is only updated here but NOT referenced, it's treated as GPR.
19309 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19310 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19311 unsigned SP = RegInfo->getStackRegister();
19313 MachineInstrBuilder MIB;
19315 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19316 const int64_t SPOffset = 2 * PVT.getStoreSize();
19318 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19319 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19322 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19323 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19324 MIB.addOperand(MI->getOperand(i));
19325 MIB.setMemRefs(MMOBegin, MMOEnd);
19327 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19328 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19329 if (i == X86::AddrDisp)
19330 MIB.addDisp(MI->getOperand(i), LabelOffset);
19332 MIB.addOperand(MI->getOperand(i));
19334 MIB.setMemRefs(MMOBegin, MMOEnd);
19336 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19337 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19338 if (i == X86::AddrDisp)
19339 MIB.addDisp(MI->getOperand(i), SPOffset);
19341 MIB.addOperand(MI->getOperand(i));
19343 MIB.setMemRefs(MMOBegin, MMOEnd);
19345 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19347 MI->eraseFromParent();
19351 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19352 // accumulator loops. Writing back to the accumulator allows the coalescer
19353 // to remove extra copies in the loop.
19354 MachineBasicBlock *
19355 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19356 MachineBasicBlock *MBB) const {
19357 MachineOperand &AddendOp = MI->getOperand(3);
19359 // Bail out early if the addend isn't a register - we can't switch these.
19360 if (!AddendOp.isReg())
19363 MachineFunction &MF = *MBB->getParent();
19364 MachineRegisterInfo &MRI = MF.getRegInfo();
19366 // Check whether the addend is defined by a PHI:
19367 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19368 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19369 if (!AddendDef.isPHI())
19372 // Look for the following pattern:
19374 // %addend = phi [%entry, 0], [%loop, %result]
19376 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19380 // %addend = phi [%entry, 0], [%loop, %result]
19382 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19384 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19385 assert(AddendDef.getOperand(i).isReg());
19386 MachineOperand PHISrcOp = AddendDef.getOperand(i);
19387 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19388 if (&PHISrcInst == MI) {
19389 // Found a matching instruction.
19390 unsigned NewFMAOpc = 0;
19391 switch (MI->getOpcode()) {
19392 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19393 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19394 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19395 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19396 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19397 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19398 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19399 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19400 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19401 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19402 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19403 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19404 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19405 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19406 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19407 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19408 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19409 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19410 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19411 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19413 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19414 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19415 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19416 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19417 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19418 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19419 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19420 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19421 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19422 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19423 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19424 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19425 default: llvm_unreachable("Unrecognized FMA variant.");
19428 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19429 MachineInstrBuilder MIB =
19430 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19431 .addOperand(MI->getOperand(0))
19432 .addOperand(MI->getOperand(3))
19433 .addOperand(MI->getOperand(2))
19434 .addOperand(MI->getOperand(1));
19435 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19436 MI->eraseFromParent();
19443 MachineBasicBlock *
19444 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19445 MachineBasicBlock *BB) const {
19446 switch (MI->getOpcode()) {
19447 default: llvm_unreachable("Unexpected instr type to insert");
19448 case X86::TAILJMPd64:
19449 case X86::TAILJMPr64:
19450 case X86::TAILJMPm64:
19451 case X86::TAILJMPd64_REX:
19452 case X86::TAILJMPr64_REX:
19453 case X86::TAILJMPm64_REX:
19454 llvm_unreachable("TAILJMP64 would not be touched here.");
19455 case X86::TCRETURNdi64:
19456 case X86::TCRETURNri64:
19457 case X86::TCRETURNmi64:
19459 case X86::WIN_ALLOCA:
19460 return EmitLoweredWinAlloca(MI, BB);
19461 case X86::SEG_ALLOCA_32:
19462 case X86::SEG_ALLOCA_64:
19463 return EmitLoweredSegAlloca(MI, BB);
19464 case X86::TLSCall_32:
19465 case X86::TLSCall_64:
19466 return EmitLoweredTLSCall(MI, BB);
19467 case X86::CMOV_GR8:
19468 case X86::CMOV_FR32:
19469 case X86::CMOV_FR64:
19470 case X86::CMOV_V4F32:
19471 case X86::CMOV_V2F64:
19472 case X86::CMOV_V2I64:
19473 case X86::CMOV_V8F32:
19474 case X86::CMOV_V4F64:
19475 case X86::CMOV_V4I64:
19476 case X86::CMOV_V16F32:
19477 case X86::CMOV_V8F64:
19478 case X86::CMOV_V8I64:
19479 case X86::CMOV_GR16:
19480 case X86::CMOV_GR32:
19481 case X86::CMOV_RFP32:
19482 case X86::CMOV_RFP64:
19483 case X86::CMOV_RFP80:
19484 return EmitLoweredSelect(MI, BB);
19486 case X86::FP32_TO_INT16_IN_MEM:
19487 case X86::FP32_TO_INT32_IN_MEM:
19488 case X86::FP32_TO_INT64_IN_MEM:
19489 case X86::FP64_TO_INT16_IN_MEM:
19490 case X86::FP64_TO_INT32_IN_MEM:
19491 case X86::FP64_TO_INT64_IN_MEM:
19492 case X86::FP80_TO_INT16_IN_MEM:
19493 case X86::FP80_TO_INT32_IN_MEM:
19494 case X86::FP80_TO_INT64_IN_MEM: {
19495 MachineFunction *F = BB->getParent();
19496 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19497 DebugLoc DL = MI->getDebugLoc();
19499 // Change the floating point control register to use "round towards zero"
19500 // mode when truncating to an integer value.
19501 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19502 addFrameReference(BuildMI(*BB, MI, DL,
19503 TII->get(X86::FNSTCW16m)), CWFrameIdx);
19505 // Load the old value of the high byte of the control word...
19507 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19508 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19511 // Set the high part to be round to zero...
19512 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19515 // Reload the modified control word now...
19516 addFrameReference(BuildMI(*BB, MI, DL,
19517 TII->get(X86::FLDCW16m)), CWFrameIdx);
19519 // Restore the memory image of control word to original value
19520 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19523 // Get the X86 opcode to use.
19525 switch (MI->getOpcode()) {
19526 default: llvm_unreachable("illegal opcode!");
19527 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19528 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19529 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19530 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19531 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19532 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19533 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19534 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19535 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19539 MachineOperand &Op = MI->getOperand(0);
19541 AM.BaseType = X86AddressMode::RegBase;
19542 AM.Base.Reg = Op.getReg();
19544 AM.BaseType = X86AddressMode::FrameIndexBase;
19545 AM.Base.FrameIndex = Op.getIndex();
19547 Op = MI->getOperand(1);
19549 AM.Scale = Op.getImm();
19550 Op = MI->getOperand(2);
19552 AM.IndexReg = Op.getImm();
19553 Op = MI->getOperand(3);
19554 if (Op.isGlobal()) {
19555 AM.GV = Op.getGlobal();
19557 AM.Disp = Op.getImm();
19559 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19560 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19562 // Reload the original control word now.
19563 addFrameReference(BuildMI(*BB, MI, DL,
19564 TII->get(X86::FLDCW16m)), CWFrameIdx);
19566 MI->eraseFromParent(); // The pseudo instruction is gone now.
19569 // String/text processing lowering.
19570 case X86::PCMPISTRM128REG:
19571 case X86::VPCMPISTRM128REG:
19572 case X86::PCMPISTRM128MEM:
19573 case X86::VPCMPISTRM128MEM:
19574 case X86::PCMPESTRM128REG:
19575 case X86::VPCMPESTRM128REG:
19576 case X86::PCMPESTRM128MEM:
19577 case X86::VPCMPESTRM128MEM:
19578 assert(Subtarget->hasSSE42() &&
19579 "Target must have SSE4.2 or AVX features enabled");
19580 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19582 // String/text processing lowering.
19583 case X86::PCMPISTRIREG:
19584 case X86::VPCMPISTRIREG:
19585 case X86::PCMPISTRIMEM:
19586 case X86::VPCMPISTRIMEM:
19587 case X86::PCMPESTRIREG:
19588 case X86::VPCMPESTRIREG:
19589 case X86::PCMPESTRIMEM:
19590 case X86::VPCMPESTRIMEM:
19591 assert(Subtarget->hasSSE42() &&
19592 "Target must have SSE4.2 or AVX features enabled");
19593 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19595 // Thread synchronization.
19597 return EmitMonitor(MI, BB, Subtarget);
19601 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19603 case X86::VASTART_SAVE_XMM_REGS:
19604 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19606 case X86::VAARG_64:
19607 return EmitVAARG64WithCustomInserter(MI, BB);
19609 case X86::EH_SjLj_SetJmp32:
19610 case X86::EH_SjLj_SetJmp64:
19611 return emitEHSjLjSetJmp(MI, BB);
19613 case X86::EH_SjLj_LongJmp32:
19614 case X86::EH_SjLj_LongJmp64:
19615 return emitEHSjLjLongJmp(MI, BB);
19617 case TargetOpcode::STATEPOINT:
19618 // As an implementation detail, STATEPOINT shares the STACKMAP format at
19619 // this point in the process. We diverge later.
19620 return emitPatchPoint(MI, BB);
19622 case TargetOpcode::STACKMAP:
19623 case TargetOpcode::PATCHPOINT:
19624 return emitPatchPoint(MI, BB);
19626 case X86::VFMADDPDr213r:
19627 case X86::VFMADDPSr213r:
19628 case X86::VFMADDSDr213r:
19629 case X86::VFMADDSSr213r:
19630 case X86::VFMSUBPDr213r:
19631 case X86::VFMSUBPSr213r:
19632 case X86::VFMSUBSDr213r:
19633 case X86::VFMSUBSSr213r:
19634 case X86::VFNMADDPDr213r:
19635 case X86::VFNMADDPSr213r:
19636 case X86::VFNMADDSDr213r:
19637 case X86::VFNMADDSSr213r:
19638 case X86::VFNMSUBPDr213r:
19639 case X86::VFNMSUBPSr213r:
19640 case X86::VFNMSUBSDr213r:
19641 case X86::VFNMSUBSSr213r:
19642 case X86::VFMADDSUBPDr213r:
19643 case X86::VFMADDSUBPSr213r:
19644 case X86::VFMSUBADDPDr213r:
19645 case X86::VFMSUBADDPSr213r:
19646 case X86::VFMADDPDr213rY:
19647 case X86::VFMADDPSr213rY:
19648 case X86::VFMSUBPDr213rY:
19649 case X86::VFMSUBPSr213rY:
19650 case X86::VFNMADDPDr213rY:
19651 case X86::VFNMADDPSr213rY:
19652 case X86::VFNMSUBPDr213rY:
19653 case X86::VFNMSUBPSr213rY:
19654 case X86::VFMADDSUBPDr213rY:
19655 case X86::VFMADDSUBPSr213rY:
19656 case X86::VFMSUBADDPDr213rY:
19657 case X86::VFMSUBADDPSr213rY:
19658 return emitFMA3Instr(MI, BB);
19662 //===----------------------------------------------------------------------===//
19663 // X86 Optimization Hooks
19664 //===----------------------------------------------------------------------===//
19666 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19669 const SelectionDAG &DAG,
19670 unsigned Depth) const {
19671 unsigned BitWidth = KnownZero.getBitWidth();
19672 unsigned Opc = Op.getOpcode();
19673 assert((Opc >= ISD::BUILTIN_OP_END ||
19674 Opc == ISD::INTRINSIC_WO_CHAIN ||
19675 Opc == ISD::INTRINSIC_W_CHAIN ||
19676 Opc == ISD::INTRINSIC_VOID) &&
19677 "Should use MaskedValueIsZero if you don't know whether Op"
19678 " is a target node!");
19680 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19694 // These nodes' second result is a boolean.
19695 if (Op.getResNo() == 0)
19698 case X86ISD::SETCC:
19699 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19701 case ISD::INTRINSIC_WO_CHAIN: {
19702 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19703 unsigned NumLoBits = 0;
19706 case Intrinsic::x86_sse_movmsk_ps:
19707 case Intrinsic::x86_avx_movmsk_ps_256:
19708 case Intrinsic::x86_sse2_movmsk_pd:
19709 case Intrinsic::x86_avx_movmsk_pd_256:
19710 case Intrinsic::x86_mmx_pmovmskb:
19711 case Intrinsic::x86_sse2_pmovmskb_128:
19712 case Intrinsic::x86_avx2_pmovmskb: {
19713 // High bits of movmskp{s|d}, pmovmskb are known zero.
19715 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19716 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19717 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19718 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19719 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19720 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19721 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19722 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19724 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19733 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19735 const SelectionDAG &,
19736 unsigned Depth) const {
19737 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19738 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19739 return Op.getValueType().getScalarType().getSizeInBits();
19745 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19746 /// node is a GlobalAddress + offset.
19747 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19748 const GlobalValue* &GA,
19749 int64_t &Offset) const {
19750 if (N->getOpcode() == X86ISD::Wrapper) {
19751 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19752 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19753 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19757 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19760 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19761 /// same as extracting the high 128-bit part of 256-bit vector and then
19762 /// inserting the result into the low part of a new 256-bit vector
19763 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19764 EVT VT = SVOp->getValueType(0);
19765 unsigned NumElems = VT.getVectorNumElements();
19767 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19768 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19769 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19770 SVOp->getMaskElt(j) >= 0)
19776 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19777 /// same as extracting the low 128-bit part of 256-bit vector and then
19778 /// inserting the result into the high part of a new 256-bit vector
19779 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19780 EVT VT = SVOp->getValueType(0);
19781 unsigned NumElems = VT.getVectorNumElements();
19783 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19784 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19785 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19786 SVOp->getMaskElt(j) >= 0)
19792 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19793 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19794 TargetLowering::DAGCombinerInfo &DCI,
19795 const X86Subtarget* Subtarget) {
19797 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19798 SDValue V1 = SVOp->getOperand(0);
19799 SDValue V2 = SVOp->getOperand(1);
19800 EVT VT = SVOp->getValueType(0);
19801 unsigned NumElems = VT.getVectorNumElements();
19803 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19804 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19808 // V UNDEF BUILD_VECTOR UNDEF
19810 // CONCAT_VECTOR CONCAT_VECTOR
19813 // RESULT: V + zero extended
19815 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19816 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19817 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19820 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19823 // To match the shuffle mask, the first half of the mask should
19824 // be exactly the first vector, and all the rest a splat with the
19825 // first element of the second one.
19826 for (unsigned i = 0; i != NumElems/2; ++i)
19827 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19828 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19831 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19832 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19833 if (Ld->hasNUsesOfValue(1, 0)) {
19834 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19835 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19837 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19839 Ld->getPointerInfo(),
19840 Ld->getAlignment(),
19841 false/*isVolatile*/, true/*ReadMem*/,
19842 false/*WriteMem*/);
19844 // Make sure the newly-created LOAD is in the same position as Ld in
19845 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19846 // and update uses of Ld's output chain to use the TokenFactor.
19847 if (Ld->hasAnyUseOfValue(1)) {
19848 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19849 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19850 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19851 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19852 SDValue(ResNode.getNode(), 1));
19855 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19859 // Emit a zeroed vector and insert the desired subvector on its
19861 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19862 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19863 return DCI.CombineTo(N, InsV);
19866 //===--------------------------------------------------------------------===//
19867 // Combine some shuffles into subvector extracts and inserts:
19870 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19871 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19872 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19873 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19874 return DCI.CombineTo(N, InsV);
19877 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19878 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19879 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19880 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19881 return DCI.CombineTo(N, InsV);
19887 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19890 /// This is the leaf of the recursive combinine below. When we have found some
19891 /// chain of single-use x86 shuffle instructions and accumulated the combined
19892 /// shuffle mask represented by them, this will try to pattern match that mask
19893 /// into either a single instruction if there is a special purpose instruction
19894 /// for this operation, or into a PSHUFB instruction which is a fully general
19895 /// instruction but should only be used to replace chains over a certain depth.
19896 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19897 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19898 TargetLowering::DAGCombinerInfo &DCI,
19899 const X86Subtarget *Subtarget) {
19900 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19902 // Find the operand that enters the chain. Note that multiple uses are OK
19903 // here, we're not going to remove the operand we find.
19904 SDValue Input = Op.getOperand(0);
19905 while (Input.getOpcode() == ISD::BITCAST)
19906 Input = Input.getOperand(0);
19908 MVT VT = Input.getSimpleValueType();
19909 MVT RootVT = Root.getSimpleValueType();
19912 // Just remove no-op shuffle masks.
19913 if (Mask.size() == 1) {
19914 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19919 // Use the float domain if the operand type is a floating point type.
19920 bool FloatDomain = VT.isFloatingPoint();
19922 // For floating point shuffles, we don't have free copies in the shuffle
19923 // instructions or the ability to load as part of the instruction, so
19924 // canonicalize their shuffles to UNPCK or MOV variants.
19926 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19927 // vectors because it can have a load folded into it that UNPCK cannot. This
19928 // doesn't preclude something switching to the shorter encoding post-RA.
19930 // FIXME: Should teach these routines about AVX vector widths.
19931 if (FloatDomain && VT.getSizeInBits() == 128) {
19932 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19933 bool Lo = Mask.equals({0, 0});
19936 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19937 // is no slower than UNPCKLPD but has the option to fold the input operand
19938 // into even an unaligned memory load.
19939 if (Lo && Subtarget->hasSSE3()) {
19940 Shuffle = X86ISD::MOVDDUP;
19941 ShuffleVT = MVT::v2f64;
19943 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19944 // than the UNPCK variants.
19945 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19946 ShuffleVT = MVT::v4f32;
19948 if (Depth == 1 && Root->getOpcode() == Shuffle)
19949 return false; // Nothing to do!
19950 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19951 DCI.AddToWorklist(Op.getNode());
19952 if (Shuffle == X86ISD::MOVDDUP)
19953 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19955 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19956 DCI.AddToWorklist(Op.getNode());
19957 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19961 if (Subtarget->hasSSE3() &&
19962 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19963 bool Lo = Mask.equals({0, 0, 2, 2});
19964 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19965 MVT ShuffleVT = MVT::v4f32;
19966 if (Depth == 1 && Root->getOpcode() == Shuffle)
19967 return false; // Nothing to do!
19968 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19969 DCI.AddToWorklist(Op.getNode());
19970 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19971 DCI.AddToWorklist(Op.getNode());
19972 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19976 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19977 bool Lo = Mask.equals({0, 0, 1, 1});
19978 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19979 MVT ShuffleVT = MVT::v4f32;
19980 if (Depth == 1 && Root->getOpcode() == Shuffle)
19981 return false; // Nothing to do!
19982 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19983 DCI.AddToWorklist(Op.getNode());
19984 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19985 DCI.AddToWorklist(Op.getNode());
19986 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19992 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19993 // variants as none of these have single-instruction variants that are
19994 // superior to the UNPCK formulation.
19995 if (!FloatDomain && VT.getSizeInBits() == 128 &&
19996 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19997 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19998 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20000 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20001 bool Lo = Mask[0] == 0;
20002 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20003 if (Depth == 1 && Root->getOpcode() == Shuffle)
20004 return false; // Nothing to do!
20006 switch (Mask.size()) {
20008 ShuffleVT = MVT::v8i16;
20011 ShuffleVT = MVT::v16i8;
20014 llvm_unreachable("Impossible mask size!");
20016 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20017 DCI.AddToWorklist(Op.getNode());
20018 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20019 DCI.AddToWorklist(Op.getNode());
20020 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20025 // Don't try to re-form single instruction chains under any circumstances now
20026 // that we've done encoding canonicalization for them.
20030 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20031 // can replace them with a single PSHUFB instruction profitably. Intel's
20032 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20033 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20034 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20035 SmallVector<SDValue, 16> PSHUFBMask;
20036 int NumBytes = VT.getSizeInBits() / 8;
20037 int Ratio = NumBytes / Mask.size();
20038 for (int i = 0; i < NumBytes; ++i) {
20039 if (Mask[i / Ratio] == SM_SentinelUndef) {
20040 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20043 int M = Mask[i / Ratio] != SM_SentinelZero
20044 ? Ratio * Mask[i / Ratio] + i % Ratio
20046 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20048 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20049 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20050 DCI.AddToWorklist(Op.getNode());
20051 SDValue PSHUFBMaskOp =
20052 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20053 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20054 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20055 DCI.AddToWorklist(Op.getNode());
20056 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20061 // Failed to find any combines.
20065 /// \brief Fully generic combining of x86 shuffle instructions.
20067 /// This should be the last combine run over the x86 shuffle instructions. Once
20068 /// they have been fully optimized, this will recursively consider all chains
20069 /// of single-use shuffle instructions, build a generic model of the cumulative
20070 /// shuffle operation, and check for simpler instructions which implement this
20071 /// operation. We use this primarily for two purposes:
20073 /// 1) Collapse generic shuffles to specialized single instructions when
20074 /// equivalent. In most cases, this is just an encoding size win, but
20075 /// sometimes we will collapse multiple generic shuffles into a single
20076 /// special-purpose shuffle.
20077 /// 2) Look for sequences of shuffle instructions with 3 or more total
20078 /// instructions, and replace them with the slightly more expensive SSSE3
20079 /// PSHUFB instruction if available. We do this as the last combining step
20080 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
20081 /// a suitable short sequence of other instructions. The PHUFB will either
20082 /// use a register or have to read from memory and so is slightly (but only
20083 /// slightly) more expensive than the other shuffle instructions.
20085 /// Because this is inherently a quadratic operation (for each shuffle in
20086 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20087 /// This should never be an issue in practice as the shuffle lowering doesn't
20088 /// produce sequences of more than 8 instructions.
20090 /// FIXME: We will currently miss some cases where the redundant shuffling
20091 /// would simplify under the threshold for PSHUFB formation because of
20092 /// combine-ordering. To fix this, we should do the redundant instruction
20093 /// combining in this recursive walk.
20094 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20095 ArrayRef<int> RootMask,
20096 int Depth, bool HasPSHUFB,
20098 TargetLowering::DAGCombinerInfo &DCI,
20099 const X86Subtarget *Subtarget) {
20100 // Bound the depth of our recursive combine because this is ultimately
20101 // quadratic in nature.
20105 // Directly rip through bitcasts to find the underlying operand.
20106 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20107 Op = Op.getOperand(0);
20109 MVT VT = Op.getSimpleValueType();
20110 if (!VT.isVector())
20111 return false; // Bail if we hit a non-vector.
20113 assert(Root.getSimpleValueType().isVector() &&
20114 "Shuffles operate on vector types!");
20115 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20116 "Can only combine shuffles of the same vector register size.");
20118 if (!isTargetShuffle(Op.getOpcode()))
20120 SmallVector<int, 16> OpMask;
20122 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20123 // We only can combine unary shuffles which we can decode the mask for.
20124 if (!HaveMask || !IsUnary)
20127 assert(VT.getVectorNumElements() == OpMask.size() &&
20128 "Different mask size from vector size!");
20129 assert(((RootMask.size() > OpMask.size() &&
20130 RootMask.size() % OpMask.size() == 0) ||
20131 (OpMask.size() > RootMask.size() &&
20132 OpMask.size() % RootMask.size() == 0) ||
20133 OpMask.size() == RootMask.size()) &&
20134 "The smaller number of elements must divide the larger.");
20135 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20136 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20137 assert(((RootRatio == 1 && OpRatio == 1) ||
20138 (RootRatio == 1) != (OpRatio == 1)) &&
20139 "Must not have a ratio for both incoming and op masks!");
20141 SmallVector<int, 16> Mask;
20142 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20144 // Merge this shuffle operation's mask into our accumulated mask. Note that
20145 // this shuffle's mask will be the first applied to the input, followed by the
20146 // root mask to get us all the way to the root value arrangement. The reason
20147 // for this order is that we are recursing up the operation chain.
20148 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20149 int RootIdx = i / RootRatio;
20150 if (RootMask[RootIdx] < 0) {
20151 // This is a zero or undef lane, we're done.
20152 Mask.push_back(RootMask[RootIdx]);
20156 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20157 int OpIdx = RootMaskedIdx / OpRatio;
20158 if (OpMask[OpIdx] < 0) {
20159 // The incoming lanes are zero or undef, it doesn't matter which ones we
20161 Mask.push_back(OpMask[OpIdx]);
20165 // Ok, we have non-zero lanes, map them through.
20166 Mask.push_back(OpMask[OpIdx] * OpRatio +
20167 RootMaskedIdx % OpRatio);
20170 // See if we can recurse into the operand to combine more things.
20171 switch (Op.getOpcode()) {
20172 case X86ISD::PSHUFB:
20174 case X86ISD::PSHUFD:
20175 case X86ISD::PSHUFHW:
20176 case X86ISD::PSHUFLW:
20177 if (Op.getOperand(0).hasOneUse() &&
20178 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20179 HasPSHUFB, DAG, DCI, Subtarget))
20183 case X86ISD::UNPCKL:
20184 case X86ISD::UNPCKH:
20185 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20186 // We can't check for single use, we have to check that this shuffle is the only user.
20187 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20188 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20189 HasPSHUFB, DAG, DCI, Subtarget))
20194 // Minor canonicalization of the accumulated shuffle mask to make it easier
20195 // to match below. All this does is detect masks with squential pairs of
20196 // elements, and shrink them to the half-width mask. It does this in a loop
20197 // so it will reduce the size of the mask to the minimal width mask which
20198 // performs an equivalent shuffle.
20199 SmallVector<int, 16> WidenedMask;
20200 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20201 Mask = std::move(WidenedMask);
20202 WidenedMask.clear();
20205 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20209 /// \brief Get the PSHUF-style mask from PSHUF node.
20211 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20212 /// PSHUF-style masks that can be reused with such instructions.
20213 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20214 MVT VT = N.getSimpleValueType();
20215 SmallVector<int, 4> Mask;
20217 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20221 // If we have more than 128-bits, only the low 128-bits of shuffle mask
20222 // matter. Check that the upper masks are repeats and remove them.
20223 if (VT.getSizeInBits() > 128) {
20224 int LaneElts = 128 / VT.getScalarSizeInBits();
20226 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20227 for (int j = 0; j < LaneElts; ++j)
20228 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20229 "Mask doesn't repeat in high 128-bit lanes!");
20231 Mask.resize(LaneElts);
20234 switch (N.getOpcode()) {
20235 case X86ISD::PSHUFD:
20237 case X86ISD::PSHUFLW:
20240 case X86ISD::PSHUFHW:
20241 Mask.erase(Mask.begin(), Mask.begin() + 4);
20242 for (int &M : Mask)
20246 llvm_unreachable("No valid shuffle instruction found!");
20250 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20252 /// We walk up the chain and look for a combinable shuffle, skipping over
20253 /// shuffles that we could hoist this shuffle's transformation past without
20254 /// altering anything.
20256 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20258 TargetLowering::DAGCombinerInfo &DCI) {
20259 assert(N.getOpcode() == X86ISD::PSHUFD &&
20260 "Called with something other than an x86 128-bit half shuffle!");
20263 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20264 // of the shuffles in the chain so that we can form a fresh chain to replace
20266 SmallVector<SDValue, 8> Chain;
20267 SDValue V = N.getOperand(0);
20268 for (; V.hasOneUse(); V = V.getOperand(0)) {
20269 switch (V.getOpcode()) {
20271 return SDValue(); // Nothing combined!
20274 // Skip bitcasts as we always know the type for the target specific
20278 case X86ISD::PSHUFD:
20279 // Found another dword shuffle.
20282 case X86ISD::PSHUFLW:
20283 // Check that the low words (being shuffled) are the identity in the
20284 // dword shuffle, and the high words are self-contained.
20285 if (Mask[0] != 0 || Mask[1] != 1 ||
20286 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20289 Chain.push_back(V);
20292 case X86ISD::PSHUFHW:
20293 // Check that the high words (being shuffled) are the identity in the
20294 // dword shuffle, and the low words are self-contained.
20295 if (Mask[2] != 2 || Mask[3] != 3 ||
20296 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20299 Chain.push_back(V);
20302 case X86ISD::UNPCKL:
20303 case X86ISD::UNPCKH:
20304 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20305 // shuffle into a preceding word shuffle.
20306 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20307 V.getSimpleValueType().getScalarType() != MVT::i16)
20310 // Search for a half-shuffle which we can combine with.
20311 unsigned CombineOp =
20312 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20313 if (V.getOperand(0) != V.getOperand(1) ||
20314 !V->isOnlyUserOf(V.getOperand(0).getNode()))
20316 Chain.push_back(V);
20317 V = V.getOperand(0);
20319 switch (V.getOpcode()) {
20321 return SDValue(); // Nothing to combine.
20323 case X86ISD::PSHUFLW:
20324 case X86ISD::PSHUFHW:
20325 if (V.getOpcode() == CombineOp)
20328 Chain.push_back(V);
20332 V = V.getOperand(0);
20336 } while (V.hasOneUse());
20339 // Break out of the loop if we break out of the switch.
20343 if (!V.hasOneUse())
20344 // We fell out of the loop without finding a viable combining instruction.
20347 // Merge this node's mask and our incoming mask.
20348 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20349 for (int &M : Mask)
20351 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20352 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20354 // Rebuild the chain around this new shuffle.
20355 while (!Chain.empty()) {
20356 SDValue W = Chain.pop_back_val();
20358 if (V.getValueType() != W.getOperand(0).getValueType())
20359 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20361 switch (W.getOpcode()) {
20363 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20365 case X86ISD::UNPCKL:
20366 case X86ISD::UNPCKH:
20367 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20370 case X86ISD::PSHUFD:
20371 case X86ISD::PSHUFLW:
20372 case X86ISD::PSHUFHW:
20373 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20377 if (V.getValueType() != N.getValueType())
20378 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20380 // Return the new chain to replace N.
20384 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20386 /// We walk up the chain, skipping shuffles of the other half and looking
20387 /// through shuffles which switch halves trying to find a shuffle of the same
20388 /// pair of dwords.
20389 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20391 TargetLowering::DAGCombinerInfo &DCI) {
20393 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20394 "Called with something other than an x86 128-bit half shuffle!");
20396 unsigned CombineOpcode = N.getOpcode();
20398 // Walk up a single-use chain looking for a combinable shuffle.
20399 SDValue V = N.getOperand(0);
20400 for (; V.hasOneUse(); V = V.getOperand(0)) {
20401 switch (V.getOpcode()) {
20403 return false; // Nothing combined!
20406 // Skip bitcasts as we always know the type for the target specific
20410 case X86ISD::PSHUFLW:
20411 case X86ISD::PSHUFHW:
20412 if (V.getOpcode() == CombineOpcode)
20415 // Other-half shuffles are no-ops.
20418 // Break out of the loop if we break out of the switch.
20422 if (!V.hasOneUse())
20423 // We fell out of the loop without finding a viable combining instruction.
20426 // Combine away the bottom node as its shuffle will be accumulated into
20427 // a preceding shuffle.
20428 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20430 // Record the old value.
20433 // Merge this node's mask and our incoming mask (adjusted to account for all
20434 // the pshufd instructions encountered).
20435 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20436 for (int &M : Mask)
20438 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20439 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20441 // Check that the shuffles didn't cancel each other out. If not, we need to
20442 // combine to the new one.
20444 // Replace the combinable shuffle with the combined one, updating all users
20445 // so that we re-evaluate the chain here.
20446 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20451 /// \brief Try to combine x86 target specific shuffles.
20452 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20453 TargetLowering::DAGCombinerInfo &DCI,
20454 const X86Subtarget *Subtarget) {
20456 MVT VT = N.getSimpleValueType();
20457 SmallVector<int, 4> Mask;
20459 switch (N.getOpcode()) {
20460 case X86ISD::PSHUFD:
20461 case X86ISD::PSHUFLW:
20462 case X86ISD::PSHUFHW:
20463 Mask = getPSHUFShuffleMask(N);
20464 assert(Mask.size() == 4);
20470 // Nuke no-op shuffles that show up after combining.
20471 if (isNoopShuffleMask(Mask))
20472 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20474 // Look for simplifications involving one or two shuffle instructions.
20475 SDValue V = N.getOperand(0);
20476 switch (N.getOpcode()) {
20479 case X86ISD::PSHUFLW:
20480 case X86ISD::PSHUFHW:
20481 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20483 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20484 return SDValue(); // We combined away this shuffle, so we're done.
20486 // See if this reduces to a PSHUFD which is no more expensive and can
20487 // combine with more operations. Note that it has to at least flip the
20488 // dwords as otherwise it would have been removed as a no-op.
20489 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20490 int DMask[] = {0, 1, 2, 3};
20491 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20492 DMask[DOffset + 0] = DOffset + 1;
20493 DMask[DOffset + 1] = DOffset + 0;
20494 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20495 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20496 DCI.AddToWorklist(V.getNode());
20497 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20498 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20499 DCI.AddToWorklist(V.getNode());
20500 return DAG.getNode(ISD::BITCAST, DL, VT, V);
20503 // Look for shuffle patterns which can be implemented as a single unpack.
20504 // FIXME: This doesn't handle the location of the PSHUFD generically, and
20505 // only works when we have a PSHUFD followed by two half-shuffles.
20506 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20507 (V.getOpcode() == X86ISD::PSHUFLW ||
20508 V.getOpcode() == X86ISD::PSHUFHW) &&
20509 V.getOpcode() != N.getOpcode() &&
20511 SDValue D = V.getOperand(0);
20512 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20513 D = D.getOperand(0);
20514 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20515 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20516 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20517 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20518 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20520 for (int i = 0; i < 4; ++i) {
20521 WordMask[i + NOffset] = Mask[i] + NOffset;
20522 WordMask[i + VOffset] = VMask[i] + VOffset;
20524 // Map the word mask through the DWord mask.
20526 for (int i = 0; i < 8; ++i)
20527 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20528 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20529 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20530 // We can replace all three shuffles with an unpack.
20531 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20532 DCI.AddToWorklist(V.getNode());
20533 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20542 case X86ISD::PSHUFD:
20543 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20552 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20554 /// We combine this directly on the abstract vector shuffle nodes so it is
20555 /// easier to generically match. We also insert dummy vector shuffle nodes for
20556 /// the operands which explicitly discard the lanes which are unused by this
20557 /// operation to try to flow through the rest of the combiner the fact that
20558 /// they're unused.
20559 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20561 EVT VT = N->getValueType(0);
20563 // We only handle target-independent shuffles.
20564 // FIXME: It would be easy and harmless to use the target shuffle mask
20565 // extraction tool to support more.
20566 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20569 auto *SVN = cast<ShuffleVectorSDNode>(N);
20570 ArrayRef<int> Mask = SVN->getMask();
20571 SDValue V1 = N->getOperand(0);
20572 SDValue V2 = N->getOperand(1);
20574 // We require the first shuffle operand to be the SUB node, and the second to
20575 // be the ADD node.
20576 // FIXME: We should support the commuted patterns.
20577 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20580 // If there are other uses of these operations we can't fold them.
20581 if (!V1->hasOneUse() || !V2->hasOneUse())
20584 // Ensure that both operations have the same operands. Note that we can
20585 // commute the FADD operands.
20586 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20587 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20588 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20591 // We're looking for blends between FADD and FSUB nodes. We insist on these
20592 // nodes being lined up in a specific expected pattern.
20593 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20594 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20595 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20598 // Only specific types are legal at this point, assert so we notice if and
20599 // when these change.
20600 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20601 VT == MVT::v4f64) &&
20602 "Unknown vector type encountered!");
20604 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20607 /// PerformShuffleCombine - Performs several different shuffle combines.
20608 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20609 TargetLowering::DAGCombinerInfo &DCI,
20610 const X86Subtarget *Subtarget) {
20612 SDValue N0 = N->getOperand(0);
20613 SDValue N1 = N->getOperand(1);
20614 EVT VT = N->getValueType(0);
20616 // Don't create instructions with illegal types after legalize types has run.
20617 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20618 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20621 // If we have legalized the vector types, look for blends of FADD and FSUB
20622 // nodes that we can fuse into an ADDSUB node.
20623 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20624 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20627 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20628 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20629 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20630 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20632 // During Type Legalization, when promoting illegal vector types,
20633 // the backend might introduce new shuffle dag nodes and bitcasts.
20635 // This code performs the following transformation:
20636 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20637 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20639 // We do this only if both the bitcast and the BINOP dag nodes have
20640 // one use. Also, perform this transformation only if the new binary
20641 // operation is legal. This is to avoid introducing dag nodes that
20642 // potentially need to be further expanded (or custom lowered) into a
20643 // less optimal sequence of dag nodes.
20644 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20645 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20646 N0.getOpcode() == ISD::BITCAST) {
20647 SDValue BC0 = N0.getOperand(0);
20648 EVT SVT = BC0.getValueType();
20649 unsigned Opcode = BC0.getOpcode();
20650 unsigned NumElts = VT.getVectorNumElements();
20652 if (BC0.hasOneUse() && SVT.isVector() &&
20653 SVT.getVectorNumElements() * 2 == NumElts &&
20654 TLI.isOperationLegal(Opcode, VT)) {
20655 bool CanFold = false;
20667 unsigned SVTNumElts = SVT.getVectorNumElements();
20668 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20669 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20670 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20671 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20672 CanFold = SVOp->getMaskElt(i) < 0;
20675 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20676 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20677 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20678 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20683 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20684 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20685 // consecutive, non-overlapping, and in the right order.
20686 SmallVector<SDValue, 16> Elts;
20687 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20688 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20690 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20694 if (isTargetShuffle(N->getOpcode())) {
20696 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20697 if (Shuffle.getNode())
20700 // Try recursively combining arbitrary sequences of x86 shuffle
20701 // instructions into higher-order shuffles. We do this after combining
20702 // specific PSHUF instruction sequences into their minimal form so that we
20703 // can evaluate how many specialized shuffle instructions are involved in
20704 // a particular chain.
20705 SmallVector<int, 1> NonceMask; // Just a placeholder.
20706 NonceMask.push_back(0);
20707 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20708 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20710 return SDValue(); // This routine will use CombineTo to replace N.
20716 /// PerformTruncateCombine - Converts truncate operation to
20717 /// a sequence of vector shuffle operations.
20718 /// It is possible when we truncate 256-bit vector to 128-bit vector
20719 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20720 TargetLowering::DAGCombinerInfo &DCI,
20721 const X86Subtarget *Subtarget) {
20725 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20726 /// specific shuffle of a load can be folded into a single element load.
20727 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20728 /// shuffles have been custom lowered so we need to handle those here.
20729 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20730 TargetLowering::DAGCombinerInfo &DCI) {
20731 if (DCI.isBeforeLegalizeOps())
20734 SDValue InVec = N->getOperand(0);
20735 SDValue EltNo = N->getOperand(1);
20737 if (!isa<ConstantSDNode>(EltNo))
20740 EVT OriginalVT = InVec.getValueType();
20742 if (InVec.getOpcode() == ISD::BITCAST) {
20743 // Don't duplicate a load with other uses.
20744 if (!InVec.hasOneUse())
20746 EVT BCVT = InVec.getOperand(0).getValueType();
20747 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20749 InVec = InVec.getOperand(0);
20752 EVT CurrentVT = InVec.getValueType();
20754 if (!isTargetShuffle(InVec.getOpcode()))
20757 // Don't duplicate a load with other uses.
20758 if (!InVec.hasOneUse())
20761 SmallVector<int, 16> ShuffleMask;
20763 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20764 ShuffleMask, UnaryShuffle))
20767 // Select the input vector, guarding against out of range extract vector.
20768 unsigned NumElems = CurrentVT.getVectorNumElements();
20769 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20770 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20771 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20772 : InVec.getOperand(1);
20774 // If inputs to shuffle are the same for both ops, then allow 2 uses
20775 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20776 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20778 if (LdNode.getOpcode() == ISD::BITCAST) {
20779 // Don't duplicate a load with other uses.
20780 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20783 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20784 LdNode = LdNode.getOperand(0);
20787 if (!ISD::isNormalLoad(LdNode.getNode()))
20790 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20792 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20795 EVT EltVT = N->getValueType(0);
20796 // If there's a bitcast before the shuffle, check if the load type and
20797 // alignment is valid.
20798 unsigned Align = LN0->getAlignment();
20799 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20800 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20801 EltVT.getTypeForEVT(*DAG.getContext()));
20803 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20806 // All checks match so transform back to vector_shuffle so that DAG combiner
20807 // can finish the job
20810 // Create shuffle node taking into account the case that its a unary shuffle
20811 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20812 : InVec.getOperand(1);
20813 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20814 InVec.getOperand(0), Shuffle,
20816 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20817 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20821 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20822 /// special and don't usually play with other vector types, it's better to
20823 /// handle them early to be sure we emit efficient code by avoiding
20824 /// store-load conversions.
20825 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20826 if (N->getValueType(0) != MVT::x86mmx ||
20827 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20828 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20831 SDValue V = N->getOperand(0);
20832 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20833 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20834 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20835 N->getValueType(0), V.getOperand(0));
20840 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20841 /// generation and convert it from being a bunch of shuffles and extracts
20842 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20843 /// storing the value and loading scalars back, while for x64 we should
20844 /// use 64-bit extracts and shifts.
20845 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20846 TargetLowering::DAGCombinerInfo &DCI) {
20847 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20848 if (NewOp.getNode())
20851 SDValue InputVector = N->getOperand(0);
20853 // Detect mmx to i32 conversion through a v2i32 elt extract.
20854 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20855 N->getValueType(0) == MVT::i32 &&
20856 InputVector.getValueType() == MVT::v2i32) {
20858 // The bitcast source is a direct mmx result.
20859 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20860 if (MMXSrc.getValueType() == MVT::x86mmx)
20861 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20862 N->getValueType(0),
20863 InputVector.getNode()->getOperand(0));
20865 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20866 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20867 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20868 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20869 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20870 MMXSrcOp.getValueType() == MVT::v1i64 &&
20871 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20872 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20873 N->getValueType(0),
20874 MMXSrcOp.getOperand(0));
20877 // Only operate on vectors of 4 elements, where the alternative shuffling
20878 // gets to be more expensive.
20879 if (InputVector.getValueType() != MVT::v4i32)
20882 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20883 // single use which is a sign-extend or zero-extend, and all elements are
20885 SmallVector<SDNode *, 4> Uses;
20886 unsigned ExtractedElements = 0;
20887 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20888 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20889 if (UI.getUse().getResNo() != InputVector.getResNo())
20892 SDNode *Extract = *UI;
20893 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20896 if (Extract->getValueType(0) != MVT::i32)
20898 if (!Extract->hasOneUse())
20900 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20901 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20903 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20906 // Record which element was extracted.
20907 ExtractedElements |=
20908 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20910 Uses.push_back(Extract);
20913 // If not all the elements were used, this may not be worthwhile.
20914 if (ExtractedElements != 15)
20917 // Ok, we've now decided to do the transformation.
20918 // If 64-bit shifts are legal, use the extract-shift sequence,
20919 // otherwise bounce the vector off the cache.
20920 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20922 SDLoc dl(InputVector);
20924 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20925 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20926 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20927 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20928 DAG.getConstant(0, dl, VecIdxTy));
20929 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20930 DAG.getConstant(1, dl, VecIdxTy));
20932 SDValue ShAmt = DAG.getConstant(32, dl,
20933 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20934 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20935 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20936 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20937 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20938 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20939 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20941 // Store the value to a temporary stack slot.
20942 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20943 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20944 MachinePointerInfo(), false, false, 0);
20946 EVT ElementType = InputVector.getValueType().getVectorElementType();
20947 unsigned EltSize = ElementType.getSizeInBits() / 8;
20949 // Replace each use (extract) with a load of the appropriate element.
20950 for (unsigned i = 0; i < 4; ++i) {
20951 uint64_t Offset = EltSize * i;
20952 SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20954 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20955 StackPtr, OffsetVal);
20957 // Load the scalar.
20958 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20959 ScalarAddr, MachinePointerInfo(),
20960 false, false, false, 0);
20965 // Replace the extracts
20966 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20967 UE = Uses.end(); UI != UE; ++UI) {
20968 SDNode *Extract = *UI;
20970 SDValue Idx = Extract->getOperand(1);
20971 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20972 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20975 // The replacement was made in place; don't return anything.
20979 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20980 static std::pair<unsigned, bool>
20981 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20982 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20983 if (!VT.isVector())
20984 return std::make_pair(0, false);
20986 bool NeedSplit = false;
20987 switch (VT.getSimpleVT().SimpleTy) {
20988 default: return std::make_pair(0, false);
20991 if (!Subtarget->hasVLX())
20992 return std::make_pair(0, false);
20996 if (!Subtarget->hasBWI())
20997 return std::make_pair(0, false);
21001 if (!Subtarget->hasAVX512())
21002 return std::make_pair(0, false);
21007 if (!Subtarget->hasAVX2())
21009 if (!Subtarget->hasAVX())
21010 return std::make_pair(0, false);
21015 if (!Subtarget->hasSSE2())
21016 return std::make_pair(0, false);
21019 // SSE2 has only a small subset of the operations.
21020 bool hasUnsigned = Subtarget->hasSSE41() ||
21021 (Subtarget->hasSSE2() && VT == MVT::v16i8);
21022 bool hasSigned = Subtarget->hasSSE41() ||
21023 (Subtarget->hasSSE2() && VT == MVT::v8i16);
21025 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21028 // Check for x CC y ? x : y.
21029 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21030 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21035 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21038 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21041 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21044 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21046 // Check for x CC y ? y : x -- a min/max with reversed arms.
21047 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21048 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21053 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21056 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21059 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21062 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21066 return std::make_pair(Opc, NeedSplit);
21070 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21071 const X86Subtarget *Subtarget) {
21073 SDValue Cond = N->getOperand(0);
21074 SDValue LHS = N->getOperand(1);
21075 SDValue RHS = N->getOperand(2);
21077 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21078 SDValue CondSrc = Cond->getOperand(0);
21079 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21080 Cond = CondSrc->getOperand(0);
21083 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21086 // A vselect where all conditions and data are constants can be optimized into
21087 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21088 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21089 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21092 unsigned MaskValue = 0;
21093 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21096 MVT VT = N->getSimpleValueType(0);
21097 unsigned NumElems = VT.getVectorNumElements();
21098 SmallVector<int, 8> ShuffleMask(NumElems, -1);
21099 for (unsigned i = 0; i < NumElems; ++i) {
21100 // Be sure we emit undef where we can.
21101 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21102 ShuffleMask[i] = -1;
21104 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21107 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21108 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21110 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21113 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21115 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21116 TargetLowering::DAGCombinerInfo &DCI,
21117 const X86Subtarget *Subtarget) {
21119 SDValue Cond = N->getOperand(0);
21120 // Get the LHS/RHS of the select.
21121 SDValue LHS = N->getOperand(1);
21122 SDValue RHS = N->getOperand(2);
21123 EVT VT = LHS.getValueType();
21124 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21126 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21127 // instructions match the semantics of the common C idiom x<y?x:y but not
21128 // x<=y?x:y, because of how they handle negative zero (which can be
21129 // ignored in unsafe-math mode).
21130 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21131 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21132 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21133 (Subtarget->hasSSE2() ||
21134 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21135 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21137 unsigned Opcode = 0;
21138 // Check for x CC y ? x : y.
21139 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21140 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21144 // Converting this to a min would handle NaNs incorrectly, and swapping
21145 // the operands would cause it to handle comparisons between positive
21146 // and negative zero incorrectly.
21147 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21148 if (!DAG.getTarget().Options.UnsafeFPMath &&
21149 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21151 std::swap(LHS, RHS);
21153 Opcode = X86ISD::FMIN;
21156 // Converting this to a min would handle comparisons between positive
21157 // and negative zero incorrectly.
21158 if (!DAG.getTarget().Options.UnsafeFPMath &&
21159 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21161 Opcode = X86ISD::FMIN;
21164 // Converting this to a min would handle both negative zeros and NaNs
21165 // incorrectly, but we can swap the operands to fix both.
21166 std::swap(LHS, RHS);
21170 Opcode = X86ISD::FMIN;
21174 // Converting this to a max would handle comparisons between positive
21175 // and negative zero incorrectly.
21176 if (!DAG.getTarget().Options.UnsafeFPMath &&
21177 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21179 Opcode = X86ISD::FMAX;
21182 // Converting this to a max would handle NaNs incorrectly, and swapping
21183 // the operands would cause it to handle comparisons between positive
21184 // and negative zero incorrectly.
21185 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21186 if (!DAG.getTarget().Options.UnsafeFPMath &&
21187 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21189 std::swap(LHS, RHS);
21191 Opcode = X86ISD::FMAX;
21194 // Converting this to a max would handle both negative zeros and NaNs
21195 // incorrectly, but we can swap the operands to fix both.
21196 std::swap(LHS, RHS);
21200 Opcode = X86ISD::FMAX;
21203 // Check for x CC y ? y : x -- a min/max with reversed arms.
21204 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21205 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21209 // Converting this to a min would handle comparisons between positive
21210 // and negative zero incorrectly, and swapping the operands would
21211 // cause it to handle NaNs incorrectly.
21212 if (!DAG.getTarget().Options.UnsafeFPMath &&
21213 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21214 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21216 std::swap(LHS, RHS);
21218 Opcode = X86ISD::FMIN;
21221 // Converting this to a min would handle NaNs incorrectly.
21222 if (!DAG.getTarget().Options.UnsafeFPMath &&
21223 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21225 Opcode = X86ISD::FMIN;
21228 // Converting this to a min would handle both negative zeros and NaNs
21229 // incorrectly, but we can swap the operands to fix both.
21230 std::swap(LHS, RHS);
21234 Opcode = X86ISD::FMIN;
21238 // Converting this to a max would handle NaNs incorrectly.
21239 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21241 Opcode = X86ISD::FMAX;
21244 // Converting this to a max would handle comparisons between positive
21245 // and negative zero incorrectly, and swapping the operands would
21246 // cause it to handle NaNs incorrectly.
21247 if (!DAG.getTarget().Options.UnsafeFPMath &&
21248 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21249 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21251 std::swap(LHS, RHS);
21253 Opcode = X86ISD::FMAX;
21256 // Converting this to a max would handle both negative zeros and NaNs
21257 // incorrectly, but we can swap the operands to fix both.
21258 std::swap(LHS, RHS);
21262 Opcode = X86ISD::FMAX;
21268 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21271 EVT CondVT = Cond.getValueType();
21272 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21273 CondVT.getVectorElementType() == MVT::i1) {
21274 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21275 // lowering on KNL. In this case we convert it to
21276 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21277 // The same situation for all 128 and 256-bit vectors of i8 and i16.
21278 // Since SKX these selects have a proper lowering.
21279 EVT OpVT = LHS.getValueType();
21280 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21281 (OpVT.getVectorElementType() == MVT::i8 ||
21282 OpVT.getVectorElementType() == MVT::i16) &&
21283 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21284 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21285 DCI.AddToWorklist(Cond.getNode());
21286 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21289 // If this is a select between two integer constants, try to do some
21291 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21292 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21293 // Don't do this for crazy integer types.
21294 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21295 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21296 // so that TrueC (the true value) is larger than FalseC.
21297 bool NeedsCondInvert = false;
21299 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21300 // Efficiently invertible.
21301 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
21302 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
21303 isa<ConstantSDNode>(Cond.getOperand(1))))) {
21304 NeedsCondInvert = true;
21305 std::swap(TrueC, FalseC);
21308 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
21309 if (FalseC->getAPIntValue() == 0 &&
21310 TrueC->getAPIntValue().isPowerOf2()) {
21311 if (NeedsCondInvert) // Invert the condition if needed.
21312 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21313 DAG.getConstant(1, DL, Cond.getValueType()));
21315 // Zero extend the condition if needed.
21316 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21318 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21319 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21320 DAG.getConstant(ShAmt, DL, MVT::i8));
21323 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21324 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21325 if (NeedsCondInvert) // Invert the condition if needed.
21326 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21327 DAG.getConstant(1, DL, Cond.getValueType()));
21329 // Zero extend the condition if needed.
21330 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21331 FalseC->getValueType(0), Cond);
21332 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21333 SDValue(FalseC, 0));
21336 // Optimize cases that will turn into an LEA instruction. This requires
21337 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21338 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21339 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21340 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21342 bool isFastMultiplier = false;
21344 switch ((unsigned char)Diff) {
21346 case 1: // result = add base, cond
21347 case 2: // result = lea base( , cond*2)
21348 case 3: // result = lea base(cond, cond*2)
21349 case 4: // result = lea base( , cond*4)
21350 case 5: // result = lea base(cond, cond*4)
21351 case 8: // result = lea base( , cond*8)
21352 case 9: // result = lea base(cond, cond*8)
21353 isFastMultiplier = true;
21358 if (isFastMultiplier) {
21359 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21360 if (NeedsCondInvert) // Invert the condition if needed.
21361 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21362 DAG.getConstant(1, DL, Cond.getValueType()));
21364 // Zero extend the condition if needed.
21365 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21367 // Scale the condition by the difference.
21369 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21370 DAG.getConstant(Diff, DL,
21371 Cond.getValueType()));
21373 // Add the base if non-zero.
21374 if (FalseC->getAPIntValue() != 0)
21375 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21376 SDValue(FalseC, 0));
21383 // Canonicalize max and min:
21384 // (x > y) ? x : y -> (x >= y) ? x : y
21385 // (x < y) ? x : y -> (x <= y) ? x : y
21386 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21387 // the need for an extra compare
21388 // against zero. e.g.
21389 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21391 // testl %edi, %edi
21393 // cmovgl %edi, %eax
21397 // cmovsl %eax, %edi
21398 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21399 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21400 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21401 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21406 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21407 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21408 Cond.getOperand(0), Cond.getOperand(1), NewCC);
21409 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21414 // Early exit check
21415 if (!TLI.isTypeLegal(VT))
21418 // Match VSELECTs into subs with unsigned saturation.
21419 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21420 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21421 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21422 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21423 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21425 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21426 // left side invert the predicate to simplify logic below.
21428 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21430 CC = ISD::getSetCCInverse(CC, true);
21431 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21435 if (Other.getNode() && Other->getNumOperands() == 2 &&
21436 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21437 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21438 SDValue CondRHS = Cond->getOperand(1);
21440 // Look for a general sub with unsigned saturation first.
21441 // x >= y ? x-y : 0 --> subus x, y
21442 // x > y ? x-y : 0 --> subus x, y
21443 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21444 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21445 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21447 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21448 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21449 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21450 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21451 // If the RHS is a constant we have to reverse the const
21452 // canonicalization.
21453 // x > C-1 ? x+-C : 0 --> subus x, C
21454 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21455 CondRHSConst->getAPIntValue() ==
21456 (-OpRHSConst->getAPIntValue() - 1))
21457 return DAG.getNode(
21458 X86ISD::SUBUS, DL, VT, OpLHS,
21459 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21461 // Another special case: If C was a sign bit, the sub has been
21462 // canonicalized into a xor.
21463 // FIXME: Would it be better to use computeKnownBits to determine
21464 // whether it's safe to decanonicalize the xor?
21465 // x s< 0 ? x^C : 0 --> subus x, C
21466 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21467 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21468 OpRHSConst->getAPIntValue().isSignBit())
21469 // Note that we have to rebuild the RHS constant here to ensure we
21470 // don't rely on particular values of undef lanes.
21471 return DAG.getNode(
21472 X86ISD::SUBUS, DL, VT, OpLHS,
21473 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21478 // Try to match a min/max vector operation.
21479 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21480 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21481 unsigned Opc = ret.first;
21482 bool NeedSplit = ret.second;
21484 if (Opc && NeedSplit) {
21485 unsigned NumElems = VT.getVectorNumElements();
21486 // Extract the LHS vectors
21487 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21488 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21490 // Extract the RHS vectors
21491 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21492 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21494 // Create min/max for each subvector
21495 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21496 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21498 // Merge the result
21499 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21501 return DAG.getNode(Opc, DL, VT, LHS, RHS);
21504 // Simplify vector selection if condition value type matches vselect
21506 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21507 assert(Cond.getValueType().isVector() &&
21508 "vector select expects a vector selector!");
21510 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21511 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21513 // Try invert the condition if true value is not all 1s and false value
21515 if (!TValIsAllOnes && !FValIsAllZeros &&
21516 // Check if the selector will be produced by CMPP*/PCMP*
21517 Cond.getOpcode() == ISD::SETCC &&
21518 // Check if SETCC has already been promoted
21519 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21520 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21521 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21523 if (TValIsAllZeros || FValIsAllOnes) {
21524 SDValue CC = Cond.getOperand(2);
21525 ISD::CondCode NewCC =
21526 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21527 Cond.getOperand(0).getValueType().isInteger());
21528 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21529 std::swap(LHS, RHS);
21530 TValIsAllOnes = FValIsAllOnes;
21531 FValIsAllZeros = TValIsAllZeros;
21535 if (TValIsAllOnes || FValIsAllZeros) {
21538 if (TValIsAllOnes && FValIsAllZeros)
21540 else if (TValIsAllOnes)
21541 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21542 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21543 else if (FValIsAllZeros)
21544 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21545 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21547 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21551 // We should generate an X86ISD::BLENDI from a vselect if its argument
21552 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21553 // constants. This specific pattern gets generated when we split a
21554 // selector for a 512 bit vector in a machine without AVX512 (but with
21555 // 256-bit vectors), during legalization:
21557 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21559 // Iff we find this pattern and the build_vectors are built from
21560 // constants, we translate the vselect into a shuffle_vector that we
21561 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21562 if ((N->getOpcode() == ISD::VSELECT ||
21563 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21564 !DCI.isBeforeLegalize()) {
21565 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21566 if (Shuffle.getNode())
21570 // If this is a *dynamic* select (non-constant condition) and we can match
21571 // this node with one of the variable blend instructions, restructure the
21572 // condition so that the blends can use the high bit of each element and use
21573 // SimplifyDemandedBits to simplify the condition operand.
21574 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21575 !DCI.isBeforeLegalize() &&
21576 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21577 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21579 // Don't optimize vector selects that map to mask-registers.
21583 // We can only handle the cases where VSELECT is directly legal on the
21584 // subtarget. We custom lower VSELECT nodes with constant conditions and
21585 // this makes it hard to see whether a dynamic VSELECT will correctly
21586 // lower, so we both check the operation's status and explicitly handle the
21587 // cases where a *dynamic* blend will fail even though a constant-condition
21588 // blend could be custom lowered.
21589 // FIXME: We should find a better way to handle this class of problems.
21590 // Potentially, we should combine constant-condition vselect nodes
21591 // pre-legalization into shuffles and not mark as many types as custom
21593 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21595 // FIXME: We don't support i16-element blends currently. We could and
21596 // should support them by making *all* the bits in the condition be set
21597 // rather than just the high bit and using an i8-element blend.
21598 if (VT.getScalarType() == MVT::i16)
21600 // Dynamic blending was only available from SSE4.1 onward.
21601 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21603 // Byte blends are only available in AVX2
21604 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21605 !Subtarget->hasAVX2())
21608 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21609 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21611 APInt KnownZero, KnownOne;
21612 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21613 DCI.isBeforeLegalizeOps());
21614 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21615 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21617 // If we changed the computation somewhere in the DAG, this change
21618 // will affect all users of Cond.
21619 // Make sure it is fine and update all the nodes so that we do not
21620 // use the generic VSELECT anymore. Otherwise, we may perform
21621 // wrong optimizations as we messed up with the actual expectation
21622 // for the vector boolean values.
21623 if (Cond != TLO.Old) {
21624 // Check all uses of that condition operand to check whether it will be
21625 // consumed by non-BLEND instructions, which may depend on all bits are
21627 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21629 if (I->getOpcode() != ISD::VSELECT)
21630 // TODO: Add other opcodes eventually lowered into BLEND.
21633 // Update all the users of the condition, before committing the change,
21634 // so that the VSELECT optimizations that expect the correct vector
21635 // boolean value will not be triggered.
21636 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21638 DAG.ReplaceAllUsesOfValueWith(
21640 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21641 Cond, I->getOperand(1), I->getOperand(2)));
21642 DCI.CommitTargetLoweringOpt(TLO);
21645 // At this point, only Cond is changed. Change the condition
21646 // just for N to keep the opportunity to optimize all other
21647 // users their own way.
21648 DAG.ReplaceAllUsesOfValueWith(
21650 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21651 TLO.New, N->getOperand(1), N->getOperand(2)));
21659 // Check whether a boolean test is testing a boolean value generated by
21660 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21663 // Simplify the following patterns:
21664 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21665 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21666 // to (Op EFLAGS Cond)
21668 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21669 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21670 // to (Op EFLAGS !Cond)
21672 // where Op could be BRCOND or CMOV.
21674 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21675 // Quit if not CMP and SUB with its value result used.
21676 if (Cmp.getOpcode() != X86ISD::CMP &&
21677 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21680 // Quit if not used as a boolean value.
21681 if (CC != X86::COND_E && CC != X86::COND_NE)
21684 // Check CMP operands. One of them should be 0 or 1 and the other should be
21685 // an SetCC or extended from it.
21686 SDValue Op1 = Cmp.getOperand(0);
21687 SDValue Op2 = Cmp.getOperand(1);
21690 const ConstantSDNode* C = nullptr;
21691 bool needOppositeCond = (CC == X86::COND_E);
21692 bool checkAgainstTrue = false; // Is it a comparison against 1?
21694 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21696 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21698 else // Quit if all operands are not constants.
21701 if (C->getZExtValue() == 1) {
21702 needOppositeCond = !needOppositeCond;
21703 checkAgainstTrue = true;
21704 } else if (C->getZExtValue() != 0)
21705 // Quit if the constant is neither 0 or 1.
21708 bool truncatedToBoolWithAnd = false;
21709 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21710 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21711 SetCC.getOpcode() == ISD::TRUNCATE ||
21712 SetCC.getOpcode() == ISD::AND) {
21713 if (SetCC.getOpcode() == ISD::AND) {
21715 ConstantSDNode *CS;
21716 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21717 CS->getZExtValue() == 1)
21719 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21720 CS->getZExtValue() == 1)
21724 SetCC = SetCC.getOperand(OpIdx);
21725 truncatedToBoolWithAnd = true;
21727 SetCC = SetCC.getOperand(0);
21730 switch (SetCC.getOpcode()) {
21731 case X86ISD::SETCC_CARRY:
21732 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21733 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21734 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21735 // truncated to i1 using 'and'.
21736 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21738 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21739 "Invalid use of SETCC_CARRY!");
21741 case X86ISD::SETCC:
21742 // Set the condition code or opposite one if necessary.
21743 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21744 if (needOppositeCond)
21745 CC = X86::GetOppositeBranchCondition(CC);
21746 return SetCC.getOperand(1);
21747 case X86ISD::CMOV: {
21748 // Check whether false/true value has canonical one, i.e. 0 or 1.
21749 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21750 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21751 // Quit if true value is not a constant.
21754 // Quit if false value is not a constant.
21756 SDValue Op = SetCC.getOperand(0);
21757 // Skip 'zext' or 'trunc' node.
21758 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21759 Op.getOpcode() == ISD::TRUNCATE)
21760 Op = Op.getOperand(0);
21761 // A special case for rdrand/rdseed, where 0 is set if false cond is
21763 if ((Op.getOpcode() != X86ISD::RDRAND &&
21764 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21767 // Quit if false value is not the constant 0 or 1.
21768 bool FValIsFalse = true;
21769 if (FVal && FVal->getZExtValue() != 0) {
21770 if (FVal->getZExtValue() != 1)
21772 // If FVal is 1, opposite cond is needed.
21773 needOppositeCond = !needOppositeCond;
21774 FValIsFalse = false;
21776 // Quit if TVal is not the constant opposite of FVal.
21777 if (FValIsFalse && TVal->getZExtValue() != 1)
21779 if (!FValIsFalse && TVal->getZExtValue() != 0)
21781 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21782 if (needOppositeCond)
21783 CC = X86::GetOppositeBranchCondition(CC);
21784 return SetCC.getOperand(3);
21791 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21793 /// (X86or (X86setcc) (X86setcc))
21794 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21795 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21796 X86::CondCode &CC1, SDValue &Flags,
21798 if (Cond->getOpcode() == X86ISD::CMP) {
21799 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21800 if (!CondOp1C || !CondOp1C->isNullValue())
21803 Cond = Cond->getOperand(0);
21808 SDValue SetCC0, SetCC1;
21809 switch (Cond->getOpcode()) {
21810 default: return false;
21817 SetCC0 = Cond->getOperand(0);
21818 SetCC1 = Cond->getOperand(1);
21822 // Make sure we have SETCC nodes, using the same flags value.
21823 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21824 SetCC1.getOpcode() != X86ISD::SETCC ||
21825 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21828 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21829 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21830 Flags = SetCC0->getOperand(1);
21834 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21835 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21836 TargetLowering::DAGCombinerInfo &DCI,
21837 const X86Subtarget *Subtarget) {
21840 // If the flag operand isn't dead, don't touch this CMOV.
21841 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21844 SDValue FalseOp = N->getOperand(0);
21845 SDValue TrueOp = N->getOperand(1);
21846 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21847 SDValue Cond = N->getOperand(3);
21849 if (CC == X86::COND_E || CC == X86::COND_NE) {
21850 switch (Cond.getOpcode()) {
21854 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21855 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21856 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21862 Flags = checkBoolTestSetCCCombine(Cond, CC);
21863 if (Flags.getNode() &&
21864 // Extra check as FCMOV only supports a subset of X86 cond.
21865 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21866 SDValue Ops[] = { FalseOp, TrueOp,
21867 DAG.getConstant(CC, DL, MVT::i8), Flags };
21868 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21871 // If this is a select between two integer constants, try to do some
21872 // optimizations. Note that the operands are ordered the opposite of SELECT
21874 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21875 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21876 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21877 // larger than FalseC (the false value).
21878 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21879 CC = X86::GetOppositeBranchCondition(CC);
21880 std::swap(TrueC, FalseC);
21881 std::swap(TrueOp, FalseOp);
21884 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21885 // This is efficient for any integer data type (including i8/i16) and
21887 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21888 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21889 DAG.getConstant(CC, DL, MVT::i8), Cond);
21891 // Zero extend the condition if needed.
21892 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21894 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21895 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21896 DAG.getConstant(ShAmt, DL, MVT::i8));
21897 if (N->getNumValues() == 2) // Dead flag value?
21898 return DCI.CombineTo(N, Cond, SDValue());
21902 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21903 // for any integer data type, including i8/i16.
21904 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21905 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21906 DAG.getConstant(CC, DL, MVT::i8), Cond);
21908 // Zero extend the condition if needed.
21909 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21910 FalseC->getValueType(0), Cond);
21911 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21912 SDValue(FalseC, 0));
21914 if (N->getNumValues() == 2) // Dead flag value?
21915 return DCI.CombineTo(N, Cond, SDValue());
21919 // Optimize cases that will turn into an LEA instruction. This requires
21920 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21921 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21922 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21923 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21925 bool isFastMultiplier = false;
21927 switch ((unsigned char)Diff) {
21929 case 1: // result = add base, cond
21930 case 2: // result = lea base( , cond*2)
21931 case 3: // result = lea base(cond, cond*2)
21932 case 4: // result = lea base( , cond*4)
21933 case 5: // result = lea base(cond, cond*4)
21934 case 8: // result = lea base( , cond*8)
21935 case 9: // result = lea base(cond, cond*8)
21936 isFastMultiplier = true;
21941 if (isFastMultiplier) {
21942 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21943 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21944 DAG.getConstant(CC, DL, MVT::i8), Cond);
21945 // Zero extend the condition if needed.
21946 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21948 // Scale the condition by the difference.
21950 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21951 DAG.getConstant(Diff, DL, Cond.getValueType()));
21953 // Add the base if non-zero.
21954 if (FalseC->getAPIntValue() != 0)
21955 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21956 SDValue(FalseC, 0));
21957 if (N->getNumValues() == 2) // Dead flag value?
21958 return DCI.CombineTo(N, Cond, SDValue());
21965 // Handle these cases:
21966 // (select (x != c), e, c) -> select (x != c), e, x),
21967 // (select (x == c), c, e) -> select (x == c), x, e)
21968 // where the c is an integer constant, and the "select" is the combination
21969 // of CMOV and CMP.
21971 // The rationale for this change is that the conditional-move from a constant
21972 // needs two instructions, however, conditional-move from a register needs
21973 // only one instruction.
21975 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21976 // some instruction-combining opportunities. This opt needs to be
21977 // postponed as late as possible.
21979 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21980 // the DCI.xxxx conditions are provided to postpone the optimization as
21981 // late as possible.
21983 ConstantSDNode *CmpAgainst = nullptr;
21984 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21985 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21986 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21988 if (CC == X86::COND_NE &&
21989 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21990 CC = X86::GetOppositeBranchCondition(CC);
21991 std::swap(TrueOp, FalseOp);
21994 if (CC == X86::COND_E &&
21995 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21996 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21997 DAG.getConstant(CC, DL, MVT::i8), Cond };
21998 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22003 // Fold and/or of setcc's to double CMOV:
22004 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22005 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22007 // This combine lets us generate:
22008 // cmovcc1 (jcc1 if we don't have CMOV)
22014 // cmovne (jne if we don't have CMOV)
22015 // When we can't use the CMOV instruction, it might increase branch
22017 // When we can use CMOV, or when there is no mispredict, this improves
22018 // throughput and reduces register pressure.
22020 if (CC == X86::COND_NE) {
22022 X86::CondCode CC0, CC1;
22024 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22026 std::swap(FalseOp, TrueOp);
22027 CC0 = X86::GetOppositeBranchCondition(CC0);
22028 CC1 = X86::GetOppositeBranchCondition(CC1);
22031 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22033 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22034 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22035 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22036 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22044 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22045 const X86Subtarget *Subtarget) {
22046 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22048 default: return SDValue();
22049 // SSE/AVX/AVX2 blend intrinsics.
22050 case Intrinsic::x86_avx2_pblendvb:
22051 // Don't try to simplify this intrinsic if we don't have AVX2.
22052 if (!Subtarget->hasAVX2())
22055 case Intrinsic::x86_avx_blendv_pd_256:
22056 case Intrinsic::x86_avx_blendv_ps_256:
22057 // Don't try to simplify this intrinsic if we don't have AVX.
22058 if (!Subtarget->hasAVX())
22061 case Intrinsic::x86_sse41_blendvps:
22062 case Intrinsic::x86_sse41_blendvpd:
22063 case Intrinsic::x86_sse41_pblendvb: {
22064 SDValue Op0 = N->getOperand(1);
22065 SDValue Op1 = N->getOperand(2);
22066 SDValue Mask = N->getOperand(3);
22068 // Don't try to simplify this intrinsic if we don't have SSE4.1.
22069 if (!Subtarget->hasSSE41())
22072 // fold (blend A, A, Mask) -> A
22075 // fold (blend A, B, allZeros) -> A
22076 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22078 // fold (blend A, B, allOnes) -> B
22079 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22082 // Simplify the case where the mask is a constant i32 value.
22083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22084 if (C->isNullValue())
22086 if (C->isAllOnesValue())
22093 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22094 case Intrinsic::x86_sse2_psrai_w:
22095 case Intrinsic::x86_sse2_psrai_d:
22096 case Intrinsic::x86_avx2_psrai_w:
22097 case Intrinsic::x86_avx2_psrai_d:
22098 case Intrinsic::x86_sse2_psra_w:
22099 case Intrinsic::x86_sse2_psra_d:
22100 case Intrinsic::x86_avx2_psra_w:
22101 case Intrinsic::x86_avx2_psra_d: {
22102 SDValue Op0 = N->getOperand(1);
22103 SDValue Op1 = N->getOperand(2);
22104 EVT VT = Op0.getValueType();
22105 assert(VT.isVector() && "Expected a vector type!");
22107 if (isa<BuildVectorSDNode>(Op1))
22108 Op1 = Op1.getOperand(0);
22110 if (!isa<ConstantSDNode>(Op1))
22113 EVT SVT = VT.getVectorElementType();
22114 unsigned SVTBits = SVT.getSizeInBits();
22116 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22117 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22118 uint64_t ShAmt = C.getZExtValue();
22120 // Don't try to convert this shift into a ISD::SRA if the shift
22121 // count is bigger than or equal to the element size.
22122 if (ShAmt >= SVTBits)
22125 // Trivial case: if the shift count is zero, then fold this
22126 // into the first operand.
22130 // Replace this packed shift intrinsic with a target independent
22133 SDValue Splat = DAG.getConstant(C, DL, VT);
22134 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22139 /// PerformMulCombine - Optimize a single multiply with constant into two
22140 /// in order to implement it with two cheaper instructions, e.g.
22141 /// LEA + SHL, LEA + LEA.
22142 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22143 TargetLowering::DAGCombinerInfo &DCI) {
22144 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22147 EVT VT = N->getValueType(0);
22148 if (VT != MVT::i64 && VT != MVT::i32)
22151 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22154 uint64_t MulAmt = C->getZExtValue();
22155 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22158 uint64_t MulAmt1 = 0;
22159 uint64_t MulAmt2 = 0;
22160 if ((MulAmt % 9) == 0) {
22162 MulAmt2 = MulAmt / 9;
22163 } else if ((MulAmt % 5) == 0) {
22165 MulAmt2 = MulAmt / 5;
22166 } else if ((MulAmt % 3) == 0) {
22168 MulAmt2 = MulAmt / 3;
22171 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22174 if (isPowerOf2_64(MulAmt2) &&
22175 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22176 // If second multiplifer is pow2, issue it first. We want the multiply by
22177 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22179 std::swap(MulAmt1, MulAmt2);
22182 if (isPowerOf2_64(MulAmt1))
22183 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22184 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22186 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22187 DAG.getConstant(MulAmt1, DL, VT));
22189 if (isPowerOf2_64(MulAmt2))
22190 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22191 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22193 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22194 DAG.getConstant(MulAmt2, DL, VT));
22196 // Do not add new nodes to DAG combiner worklist.
22197 DCI.CombineTo(N, NewMul, false);
22202 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22203 SDValue N0 = N->getOperand(0);
22204 SDValue N1 = N->getOperand(1);
22205 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22206 EVT VT = N0.getValueType();
22208 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22209 // since the result of setcc_c is all zero's or all ones.
22210 if (VT.isInteger() && !VT.isVector() &&
22211 N1C && N0.getOpcode() == ISD::AND &&
22212 N0.getOperand(1).getOpcode() == ISD::Constant) {
22213 SDValue N00 = N0.getOperand(0);
22214 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22215 ((N00.getOpcode() == ISD::ANY_EXTEND ||
22216 N00.getOpcode() == ISD::ZERO_EXTEND) &&
22217 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22218 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22219 APInt ShAmt = N1C->getAPIntValue();
22220 Mask = Mask.shl(ShAmt);
22223 return DAG.getNode(ISD::AND, DL, VT,
22224 N00, DAG.getConstant(Mask, DL, VT));
22229 // Hardware support for vector shifts is sparse which makes us scalarize the
22230 // vector operations in many cases. Also, on sandybridge ADD is faster than
22232 // (shl V, 1) -> add V,V
22233 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22234 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22235 assert(N0.getValueType().isVector() && "Invalid vector shift type");
22236 // We shift all of the values by one. In many cases we do not have
22237 // hardware support for this operation. This is better expressed as an ADD
22239 if (N1SplatC->getZExtValue() == 1)
22240 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22246 /// \brief Returns a vector of 0s if the node in input is a vector logical
22247 /// shift by a constant amount which is known to be bigger than or equal
22248 /// to the vector element size in bits.
22249 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22250 const X86Subtarget *Subtarget) {
22251 EVT VT = N->getValueType(0);
22253 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22254 (!Subtarget->hasInt256() ||
22255 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22258 SDValue Amt = N->getOperand(1);
22260 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22261 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22262 APInt ShiftAmt = AmtSplat->getAPIntValue();
22263 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22265 // SSE2/AVX2 logical shifts always return a vector of 0s
22266 // if the shift amount is bigger than or equal to
22267 // the element size. The constant shift amount will be
22268 // encoded as a 8-bit immediate.
22269 if (ShiftAmt.trunc(8).uge(MaxAmount))
22270 return getZeroVector(VT, Subtarget, DAG, DL);
22276 /// PerformShiftCombine - Combine shifts.
22277 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22278 TargetLowering::DAGCombinerInfo &DCI,
22279 const X86Subtarget *Subtarget) {
22280 if (N->getOpcode() == ISD::SHL) {
22281 SDValue V = PerformSHLCombine(N, DAG);
22282 if (V.getNode()) return V;
22285 if (N->getOpcode() != ISD::SRA) {
22286 // Try to fold this logical shift into a zero vector.
22287 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22288 if (V.getNode()) return V;
22294 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
22295 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22296 // and friends. Likewise for OR -> CMPNEQSS.
22297 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22298 TargetLowering::DAGCombinerInfo &DCI,
22299 const X86Subtarget *Subtarget) {
22302 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22303 // we're requiring SSE2 for both.
22304 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22305 SDValue N0 = N->getOperand(0);
22306 SDValue N1 = N->getOperand(1);
22307 SDValue CMP0 = N0->getOperand(1);
22308 SDValue CMP1 = N1->getOperand(1);
22311 // The SETCCs should both refer to the same CMP.
22312 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22315 SDValue CMP00 = CMP0->getOperand(0);
22316 SDValue CMP01 = CMP0->getOperand(1);
22317 EVT VT = CMP00.getValueType();
22319 if (VT == MVT::f32 || VT == MVT::f64) {
22320 bool ExpectingFlags = false;
22321 // Check for any users that want flags:
22322 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22323 !ExpectingFlags && UI != UE; ++UI)
22324 switch (UI->getOpcode()) {
22329 ExpectingFlags = true;
22331 case ISD::CopyToReg:
22332 case ISD::SIGN_EXTEND:
22333 case ISD::ZERO_EXTEND:
22334 case ISD::ANY_EXTEND:
22338 if (!ExpectingFlags) {
22339 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22340 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22342 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22343 X86::CondCode tmp = cc0;
22348 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
22349 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22350 // FIXME: need symbolic constants for these magic numbers.
22351 // See X86ATTInstPrinter.cpp:printSSECC().
22352 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22353 if (Subtarget->hasAVX512()) {
22354 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22356 DAG.getConstant(x86cc, DL, MVT::i8));
22357 if (N->getValueType(0) != MVT::i1)
22358 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22362 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22363 CMP00.getValueType(), CMP00, CMP01,
22364 DAG.getConstant(x86cc, DL,
22367 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22368 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22370 if (is64BitFP && !Subtarget->is64Bit()) {
22371 // On a 32-bit target, we cannot bitcast the 64-bit float to a
22372 // 64-bit integer, since that's not a legal type. Since
22373 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22374 // bits, but can do this little dance to extract the lowest 32 bits
22375 // and work with those going forward.
22376 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22378 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22380 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22381 Vector32, DAG.getIntPtrConstant(0, DL));
22385 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22387 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22388 DAG.getConstant(1, DL, IntVT));
22389 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22391 return OneBitOfTruth;
22399 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22400 /// so it can be folded inside ANDNP.
22401 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22402 EVT VT = N->getValueType(0);
22404 // Match direct AllOnes for 128 and 256-bit vectors
22405 if (ISD::isBuildVectorAllOnes(N))
22408 // Look through a bit convert.
22409 if (N->getOpcode() == ISD::BITCAST)
22410 N = N->getOperand(0).getNode();
22412 // Sometimes the operand may come from a insert_subvector building a 256-bit
22414 if (VT.is256BitVector() &&
22415 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22416 SDValue V1 = N->getOperand(0);
22417 SDValue V2 = N->getOperand(1);
22419 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22420 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22421 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22422 ISD::isBuildVectorAllOnes(V2.getNode()))
22429 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22430 // register. In most cases we actually compare or select YMM-sized registers
22431 // and mixing the two types creates horrible code. This method optimizes
22432 // some of the transition sequences.
22433 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22434 TargetLowering::DAGCombinerInfo &DCI,
22435 const X86Subtarget *Subtarget) {
22436 EVT VT = N->getValueType(0);
22437 if (!VT.is256BitVector())
22440 assert((N->getOpcode() == ISD::ANY_EXTEND ||
22441 N->getOpcode() == ISD::ZERO_EXTEND ||
22442 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22444 SDValue Narrow = N->getOperand(0);
22445 EVT NarrowVT = Narrow->getValueType(0);
22446 if (!NarrowVT.is128BitVector())
22449 if (Narrow->getOpcode() != ISD::XOR &&
22450 Narrow->getOpcode() != ISD::AND &&
22451 Narrow->getOpcode() != ISD::OR)
22454 SDValue N0 = Narrow->getOperand(0);
22455 SDValue N1 = Narrow->getOperand(1);
22458 // The Left side has to be a trunc.
22459 if (N0.getOpcode() != ISD::TRUNCATE)
22462 // The type of the truncated inputs.
22463 EVT WideVT = N0->getOperand(0)->getValueType(0);
22467 // The right side has to be a 'trunc' or a constant vector.
22468 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22469 ConstantSDNode *RHSConstSplat = nullptr;
22470 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22471 RHSConstSplat = RHSBV->getConstantSplatNode();
22472 if (!RHSTrunc && !RHSConstSplat)
22475 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22477 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22480 // Set N0 and N1 to hold the inputs to the new wide operation.
22481 N0 = N0->getOperand(0);
22482 if (RHSConstSplat) {
22483 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22484 SDValue(RHSConstSplat, 0));
22485 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22486 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22487 } else if (RHSTrunc) {
22488 N1 = N1->getOperand(0);
22491 // Generate the wide operation.
22492 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22493 unsigned Opcode = N->getOpcode();
22495 case ISD::ANY_EXTEND:
22497 case ISD::ZERO_EXTEND: {
22498 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22499 APInt Mask = APInt::getAllOnesValue(InBits);
22500 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22501 return DAG.getNode(ISD::AND, DL, VT,
22502 Op, DAG.getConstant(Mask, DL, VT));
22504 case ISD::SIGN_EXTEND:
22505 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22506 Op, DAG.getValueType(NarrowVT));
22508 llvm_unreachable("Unexpected opcode");
22512 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22513 TargetLowering::DAGCombinerInfo &DCI,
22514 const X86Subtarget *Subtarget) {
22515 SDValue N0 = N->getOperand(0);
22516 SDValue N1 = N->getOperand(1);
22519 // A vector zext_in_reg may be represented as a shuffle,
22520 // feeding into a bitcast (this represents anyext) feeding into
22521 // an and with a mask.
22522 // We'd like to try to combine that into a shuffle with zero
22523 // plus a bitcast, removing the and.
22524 if (N0.getOpcode() != ISD::BITCAST ||
22525 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22528 // The other side of the AND should be a splat of 2^C, where C
22529 // is the number of bits in the source type.
22530 if (N1.getOpcode() == ISD::BITCAST)
22531 N1 = N1.getOperand(0);
22532 if (N1.getOpcode() != ISD::BUILD_VECTOR)
22534 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22536 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22537 EVT SrcType = Shuffle->getValueType(0);
22539 // We expect a single-source shuffle
22540 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22543 unsigned SrcSize = SrcType.getScalarSizeInBits();
22545 APInt SplatValue, SplatUndef;
22546 unsigned SplatBitSize;
22548 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22549 SplatBitSize, HasAnyUndefs))
22552 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22553 // Make sure the splat matches the mask we expect
22554 if (SplatBitSize > ResSize ||
22555 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22558 // Make sure the input and output size make sense
22559 if (SrcSize >= ResSize || ResSize % SrcSize)
22562 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22563 // The number of u's between each two values depends on the ratio between
22564 // the source and dest type.
22565 unsigned ZextRatio = ResSize / SrcSize;
22566 bool IsZext = true;
22567 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22568 if (i % ZextRatio) {
22569 if (Shuffle->getMaskElt(i) > 0) {
22575 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22576 // Expected element number
22586 // Ok, perform the transformation - replace the shuffle with
22587 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22588 // (instead of undef) where the k elements come from the zero vector.
22589 SmallVector<int, 8> Mask;
22590 unsigned NumElems = SrcType.getVectorNumElements();
22591 for (unsigned i = 0; i < NumElems; ++i)
22593 Mask.push_back(NumElems);
22595 Mask.push_back(i / ZextRatio);
22597 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22598 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22599 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22602 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22603 TargetLowering::DAGCombinerInfo &DCI,
22604 const X86Subtarget *Subtarget) {
22605 if (DCI.isBeforeLegalizeOps())
22608 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22611 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22614 EVT VT = N->getValueType(0);
22615 SDValue N0 = N->getOperand(0);
22616 SDValue N1 = N->getOperand(1);
22619 // Create BEXTR instructions
22620 // BEXTR is ((X >> imm) & (2**size-1))
22621 if (VT == MVT::i32 || VT == MVT::i64) {
22622 // Check for BEXTR.
22623 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22624 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22625 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22626 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22627 if (MaskNode && ShiftNode) {
22628 uint64_t Mask = MaskNode->getZExtValue();
22629 uint64_t Shift = ShiftNode->getZExtValue();
22630 if (isMask_64(Mask)) {
22631 uint64_t MaskSize = countPopulation(Mask);
22632 if (Shift + MaskSize <= VT.getSizeInBits())
22633 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22634 DAG.getConstant(Shift | (MaskSize << 8), DL,
22643 // Want to form ANDNP nodes:
22644 // 1) In the hopes of then easily combining them with OR and AND nodes
22645 // to form PBLEND/PSIGN.
22646 // 2) To match ANDN packed intrinsics
22647 if (VT != MVT::v2i64 && VT != MVT::v4i64)
22650 // Check LHS for vnot
22651 if (N0.getOpcode() == ISD::XOR &&
22652 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22653 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22654 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22656 // Check RHS for vnot
22657 if (N1.getOpcode() == ISD::XOR &&
22658 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22659 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22660 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22665 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22666 TargetLowering::DAGCombinerInfo &DCI,
22667 const X86Subtarget *Subtarget) {
22668 if (DCI.isBeforeLegalizeOps())
22671 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22675 SDValue N0 = N->getOperand(0);
22676 SDValue N1 = N->getOperand(1);
22677 EVT VT = N->getValueType(0);
22679 // look for psign/blend
22680 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22681 if (!Subtarget->hasSSSE3() ||
22682 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22685 // Canonicalize pandn to RHS
22686 if (N0.getOpcode() == X86ISD::ANDNP)
22688 // or (and (m, y), (pandn m, x))
22689 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22690 SDValue Mask = N1.getOperand(0);
22691 SDValue X = N1.getOperand(1);
22693 if (N0.getOperand(0) == Mask)
22694 Y = N0.getOperand(1);
22695 if (N0.getOperand(1) == Mask)
22696 Y = N0.getOperand(0);
22698 // Check to see if the mask appeared in both the AND and ANDNP and
22702 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22703 // Look through mask bitcast.
22704 if (Mask.getOpcode() == ISD::BITCAST)
22705 Mask = Mask.getOperand(0);
22706 if (X.getOpcode() == ISD::BITCAST)
22707 X = X.getOperand(0);
22708 if (Y.getOpcode() == ISD::BITCAST)
22709 Y = Y.getOperand(0);
22711 EVT MaskVT = Mask.getValueType();
22713 // Validate that the Mask operand is a vector sra node.
22714 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22715 // there is no psrai.b
22716 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22717 unsigned SraAmt = ~0;
22718 if (Mask.getOpcode() == ISD::SRA) {
22719 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22720 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22721 SraAmt = AmtConst->getZExtValue();
22722 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22723 SDValue SraC = Mask.getOperand(1);
22724 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22726 if ((SraAmt + 1) != EltBits)
22731 // Now we know we at least have a plendvb with the mask val. See if
22732 // we can form a psignb/w/d.
22733 // psign = x.type == y.type == mask.type && y = sub(0, x);
22734 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22735 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22736 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22737 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22738 "Unsupported VT for PSIGN");
22739 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22740 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22742 // PBLENDVB only available on SSE 4.1
22743 if (!Subtarget->hasSSE41())
22746 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22748 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22749 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22750 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22751 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22752 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22756 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22759 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22760 MachineFunction &MF = DAG.getMachineFunction();
22762 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22764 // SHLD/SHRD instructions have lower register pressure, but on some
22765 // platforms they have higher latency than the equivalent
22766 // series of shifts/or that would otherwise be generated.
22767 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22768 // have higher latencies and we are not optimizing for size.
22769 if (!OptForSize && Subtarget->isSHLDSlow())
22772 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22774 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22776 if (!N0.hasOneUse() || !N1.hasOneUse())
22779 SDValue ShAmt0 = N0.getOperand(1);
22780 if (ShAmt0.getValueType() != MVT::i8)
22782 SDValue ShAmt1 = N1.getOperand(1);
22783 if (ShAmt1.getValueType() != MVT::i8)
22785 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22786 ShAmt0 = ShAmt0.getOperand(0);
22787 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22788 ShAmt1 = ShAmt1.getOperand(0);
22791 unsigned Opc = X86ISD::SHLD;
22792 SDValue Op0 = N0.getOperand(0);
22793 SDValue Op1 = N1.getOperand(0);
22794 if (ShAmt0.getOpcode() == ISD::SUB) {
22795 Opc = X86ISD::SHRD;
22796 std::swap(Op0, Op1);
22797 std::swap(ShAmt0, ShAmt1);
22800 unsigned Bits = VT.getSizeInBits();
22801 if (ShAmt1.getOpcode() == ISD::SUB) {
22802 SDValue Sum = ShAmt1.getOperand(0);
22803 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22804 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22805 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22806 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22807 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22808 return DAG.getNode(Opc, DL, VT,
22810 DAG.getNode(ISD::TRUNCATE, DL,
22813 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22814 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22816 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22817 return DAG.getNode(Opc, DL, VT,
22818 N0.getOperand(0), N1.getOperand(0),
22819 DAG.getNode(ISD::TRUNCATE, DL,
22826 // Generate NEG and CMOV for integer abs.
22827 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22828 EVT VT = N->getValueType(0);
22830 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22831 // 8-bit integer abs to NEG and CMOV.
22832 if (VT.isInteger() && VT.getSizeInBits() == 8)
22835 SDValue N0 = N->getOperand(0);
22836 SDValue N1 = N->getOperand(1);
22839 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22840 // and change it to SUB and CMOV.
22841 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22842 N0.getOpcode() == ISD::ADD &&
22843 N0.getOperand(1) == N1 &&
22844 N1.getOpcode() == ISD::SRA &&
22845 N1.getOperand(0) == N0.getOperand(0))
22846 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22847 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22848 // Generate SUB & CMOV.
22849 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22850 DAG.getConstant(0, DL, VT), N0.getOperand(0));
22852 SDValue Ops[] = { N0.getOperand(0), Neg,
22853 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22854 SDValue(Neg.getNode(), 1) };
22855 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22860 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22861 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22862 TargetLowering::DAGCombinerInfo &DCI,
22863 const X86Subtarget *Subtarget) {
22864 if (DCI.isBeforeLegalizeOps())
22867 if (Subtarget->hasCMov()) {
22868 SDValue RV = performIntegerAbsCombine(N, DAG);
22876 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22877 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22878 TargetLowering::DAGCombinerInfo &DCI,
22879 const X86Subtarget *Subtarget) {
22880 LoadSDNode *Ld = cast<LoadSDNode>(N);
22881 EVT RegVT = Ld->getValueType(0);
22882 EVT MemVT = Ld->getMemoryVT();
22884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22886 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22887 // into two 16-byte operations.
22888 ISD::LoadExtType Ext = Ld->getExtensionType();
22889 unsigned Alignment = Ld->getAlignment();
22890 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22891 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22892 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22893 unsigned NumElems = RegVT.getVectorNumElements();
22897 SDValue Ptr = Ld->getBasePtr();
22898 SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22900 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22902 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22903 Ld->getPointerInfo(), Ld->isVolatile(),
22904 Ld->isNonTemporal(), Ld->isInvariant(),
22906 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22907 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22908 Ld->getPointerInfo(), Ld->isVolatile(),
22909 Ld->isNonTemporal(), Ld->isInvariant(),
22910 std::min(16U, Alignment));
22911 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22913 Load2.getValue(1));
22915 SDValue NewVec = DAG.getUNDEF(RegVT);
22916 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22917 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22918 return DCI.CombineTo(N, NewVec, TF, true);
22924 /// PerformMLOADCombine - Resolve extending loads
22925 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22926 TargetLowering::DAGCombinerInfo &DCI,
22927 const X86Subtarget *Subtarget) {
22928 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22929 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22932 EVT VT = Mld->getValueType(0);
22933 unsigned NumElems = VT.getVectorNumElements();
22934 EVT LdVT = Mld->getMemoryVT();
22937 assert(LdVT != VT && "Cannot extend to the same type");
22938 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22939 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22940 // From, To sizes and ElemCount must be pow of two
22941 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22942 "Unexpected size for extending masked load");
22944 unsigned SizeRatio = ToSz / FromSz;
22945 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22947 // Create a type on which we perform the shuffle
22948 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22949 LdVT.getScalarType(), NumElems*SizeRatio);
22950 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22952 // Convert Src0 value
22953 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22954 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22955 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22956 for (unsigned i = 0; i != NumElems; ++i)
22957 ShuffleVec[i] = i * SizeRatio;
22959 // Can't shuffle using an illegal type.
22960 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22961 && "WideVecVT should be legal");
22962 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22963 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22965 // Prepare the new mask
22967 SDValue Mask = Mld->getMask();
22968 if (Mask.getValueType() == VT) {
22969 // Mask and original value have the same type
22970 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22971 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22972 for (unsigned i = 0; i != NumElems; ++i)
22973 ShuffleVec[i] = i * SizeRatio;
22974 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22975 ShuffleVec[i] = NumElems*SizeRatio;
22976 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22977 DAG.getConstant(0, dl, WideVecVT),
22981 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22982 unsigned WidenNumElts = NumElems*SizeRatio;
22983 unsigned MaskNumElts = VT.getVectorNumElements();
22984 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22987 unsigned NumConcat = WidenNumElts / MaskNumElts;
22988 SmallVector<SDValue, 16> Ops(NumConcat);
22989 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
22991 for (unsigned i = 1; i != NumConcat; ++i)
22994 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22997 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22998 Mld->getBasePtr(), NewMask, WideSrc0,
22999 Mld->getMemoryVT(), Mld->getMemOperand(),
23001 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23002 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23005 /// PerformMSTORECombine - Resolve truncating stores
23006 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23007 const X86Subtarget *Subtarget) {
23008 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23009 if (!Mst->isTruncatingStore())
23012 EVT VT = Mst->getValue().getValueType();
23013 unsigned NumElems = VT.getVectorNumElements();
23014 EVT StVT = Mst->getMemoryVT();
23017 assert(StVT != VT && "Cannot truncate to the same type");
23018 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23019 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23021 // From, To sizes and ElemCount must be pow of two
23022 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23023 "Unexpected size for truncating masked store");
23024 // We are going to use the original vector elt for storing.
23025 // Accumulated smaller vector elements must be a multiple of the store size.
23026 assert (((NumElems * FromSz) % ToSz) == 0 &&
23027 "Unexpected ratio for truncating masked store");
23029 unsigned SizeRatio = FromSz / ToSz;
23030 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23032 // Create a type on which we perform the shuffle
23033 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23034 StVT.getScalarType(), NumElems*SizeRatio);
23036 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23038 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23039 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23040 for (unsigned i = 0; i != NumElems; ++i)
23041 ShuffleVec[i] = i * SizeRatio;
23043 // Can't shuffle using an illegal type.
23044 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23045 && "WideVecVT should be legal");
23047 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23048 DAG.getUNDEF(WideVecVT),
23052 SDValue Mask = Mst->getMask();
23053 if (Mask.getValueType() == VT) {
23054 // Mask and original value have the same type
23055 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23056 for (unsigned i = 0; i != NumElems; ++i)
23057 ShuffleVec[i] = i * SizeRatio;
23058 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23059 ShuffleVec[i] = NumElems*SizeRatio;
23060 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23061 DAG.getConstant(0, dl, WideVecVT),
23065 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23066 unsigned WidenNumElts = NumElems*SizeRatio;
23067 unsigned MaskNumElts = VT.getVectorNumElements();
23068 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23071 unsigned NumConcat = WidenNumElts / MaskNumElts;
23072 SmallVector<SDValue, 16> Ops(NumConcat);
23073 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23075 for (unsigned i = 1; i != NumConcat; ++i)
23078 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23081 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23082 NewMask, StVT, Mst->getMemOperand(), false);
23084 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23085 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23086 const X86Subtarget *Subtarget) {
23087 StoreSDNode *St = cast<StoreSDNode>(N);
23088 EVT VT = St->getValue().getValueType();
23089 EVT StVT = St->getMemoryVT();
23091 SDValue StoredVal = St->getOperand(1);
23092 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23094 // If we are saving a concatenation of two XMM registers and 32-byte stores
23095 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23096 unsigned Alignment = St->getAlignment();
23097 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23098 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23099 StVT == VT && !IsAligned) {
23100 unsigned NumElems = VT.getVectorNumElements();
23104 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23105 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23107 SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23108 SDValue Ptr0 = St->getBasePtr();
23109 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23111 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23112 St->getPointerInfo(), St->isVolatile(),
23113 St->isNonTemporal(), Alignment);
23114 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23115 St->getPointerInfo(), St->isVolatile(),
23116 St->isNonTemporal(),
23117 std::min(16U, Alignment));
23118 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23121 // Optimize trunc store (of multiple scalars) to shuffle and store.
23122 // First, pack all of the elements in one place. Next, store to memory
23123 // in fewer chunks.
23124 if (St->isTruncatingStore() && VT.isVector()) {
23125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23126 unsigned NumElems = VT.getVectorNumElements();
23127 assert(StVT != VT && "Cannot truncate to the same type");
23128 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23129 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23131 // From, To sizes and ElemCount must be pow of two
23132 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23133 // We are going to use the original vector elt for storing.
23134 // Accumulated smaller vector elements must be a multiple of the store size.
23135 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23137 unsigned SizeRatio = FromSz / ToSz;
23139 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23141 // Create a type on which we perform the shuffle
23142 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23143 StVT.getScalarType(), NumElems*SizeRatio);
23145 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23147 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23148 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23149 for (unsigned i = 0; i != NumElems; ++i)
23150 ShuffleVec[i] = i * SizeRatio;
23152 // Can't shuffle using an illegal type.
23153 if (!TLI.isTypeLegal(WideVecVT))
23156 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23157 DAG.getUNDEF(WideVecVT),
23159 // At this point all of the data is stored at the bottom of the
23160 // register. We now need to save it to mem.
23162 // Find the largest store unit
23163 MVT StoreType = MVT::i8;
23164 for (MVT Tp : MVT::integer_valuetypes()) {
23165 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23169 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23170 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23171 (64 <= NumElems * ToSz))
23172 StoreType = MVT::f64;
23174 // Bitcast the original vector into a vector of store-size units
23175 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23176 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23177 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23178 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23179 SmallVector<SDValue, 8> Chains;
23180 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23181 TLI.getPointerTy());
23182 SDValue Ptr = St->getBasePtr();
23184 // Perform one or more big stores into memory.
23185 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23186 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23187 StoreType, ShuffWide,
23188 DAG.getIntPtrConstant(i, dl));
23189 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23190 St->getPointerInfo(), St->isVolatile(),
23191 St->isNonTemporal(), St->getAlignment());
23192 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23193 Chains.push_back(Ch);
23196 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23199 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
23200 // the FP state in cases where an emms may be missing.
23201 // A preferable solution to the general problem is to figure out the right
23202 // places to insert EMMS. This qualifies as a quick hack.
23204 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23205 if (VT.getSizeInBits() != 64)
23208 const Function *F = DAG.getMachineFunction().getFunction();
23209 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23211 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23212 if ((VT.isVector() ||
23213 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23214 isa<LoadSDNode>(St->getValue()) &&
23215 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23216 St->getChain().hasOneUse() && !St->isVolatile()) {
23217 SDNode* LdVal = St->getValue().getNode();
23218 LoadSDNode *Ld = nullptr;
23219 int TokenFactorIndex = -1;
23220 SmallVector<SDValue, 8> Ops;
23221 SDNode* ChainVal = St->getChain().getNode();
23222 // Must be a store of a load. We currently handle two cases: the load
23223 // is a direct child, and it's under an intervening TokenFactor. It is
23224 // possible to dig deeper under nested TokenFactors.
23225 if (ChainVal == LdVal)
23226 Ld = cast<LoadSDNode>(St->getChain());
23227 else if (St->getValue().hasOneUse() &&
23228 ChainVal->getOpcode() == ISD::TokenFactor) {
23229 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23230 if (ChainVal->getOperand(i).getNode() == LdVal) {
23231 TokenFactorIndex = i;
23232 Ld = cast<LoadSDNode>(St->getValue());
23234 Ops.push_back(ChainVal->getOperand(i));
23238 if (!Ld || !ISD::isNormalLoad(Ld))
23241 // If this is not the MMX case, i.e. we are just turning i64 load/store
23242 // into f64 load/store, avoid the transformation if there are multiple
23243 // uses of the loaded value.
23244 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23249 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23250 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23252 if (Subtarget->is64Bit() || F64IsLegal) {
23253 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23254 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23255 Ld->getPointerInfo(), Ld->isVolatile(),
23256 Ld->isNonTemporal(), Ld->isInvariant(),
23257 Ld->getAlignment());
23258 SDValue NewChain = NewLd.getValue(1);
23259 if (TokenFactorIndex != -1) {
23260 Ops.push_back(NewChain);
23261 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23263 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23264 St->getPointerInfo(),
23265 St->isVolatile(), St->isNonTemporal(),
23266 St->getAlignment());
23269 // Otherwise, lower to two pairs of 32-bit loads / stores.
23270 SDValue LoAddr = Ld->getBasePtr();
23271 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23272 DAG.getConstant(4, LdDL, MVT::i32));
23274 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23275 Ld->getPointerInfo(),
23276 Ld->isVolatile(), Ld->isNonTemporal(),
23277 Ld->isInvariant(), Ld->getAlignment());
23278 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23279 Ld->getPointerInfo().getWithOffset(4),
23280 Ld->isVolatile(), Ld->isNonTemporal(),
23282 MinAlign(Ld->getAlignment(), 4));
23284 SDValue NewChain = LoLd.getValue(1);
23285 if (TokenFactorIndex != -1) {
23286 Ops.push_back(LoLd);
23287 Ops.push_back(HiLd);
23288 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23291 LoAddr = St->getBasePtr();
23292 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23293 DAG.getConstant(4, StDL, MVT::i32));
23295 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23296 St->getPointerInfo(),
23297 St->isVolatile(), St->isNonTemporal(),
23298 St->getAlignment());
23299 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23300 St->getPointerInfo().getWithOffset(4),
23302 St->isNonTemporal(),
23303 MinAlign(St->getAlignment(), 4));
23304 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23307 // This is similar to the above case, but here we handle a scalar 64-bit
23308 // integer store that is extracted from a vector on a 32-bit target.
23309 // If we have SSE2, then we can treat it like a floating-point double
23310 // to get past legalization. The execution dependencies fixup pass will
23311 // choose the optimal machine instruction for the store if this really is
23312 // an integer or v2f32 rather than an f64.
23313 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23314 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23315 SDValue OldExtract = St->getOperand(1);
23316 SDValue ExtOp0 = OldExtract.getOperand(0);
23317 unsigned VecSize = ExtOp0.getValueSizeInBits();
23318 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23319 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23320 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23321 BitCast, OldExtract.getOperand(1));
23322 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23323 St->getPointerInfo(), St->isVolatile(),
23324 St->isNonTemporal(), St->getAlignment());
23330 /// Return 'true' if this vector operation is "horizontal"
23331 /// and return the operands for the horizontal operation in LHS and RHS. A
23332 /// horizontal operation performs the binary operation on successive elements
23333 /// of its first operand, then on successive elements of its second operand,
23334 /// returning the resulting values in a vector. For example, if
23335 /// A = < float a0, float a1, float a2, float a3 >
23337 /// B = < float b0, float b1, float b2, float b3 >
23338 /// then the result of doing a horizontal operation on A and B is
23339 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23340 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23341 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23342 /// set to A, RHS to B, and the routine returns 'true'.
23343 /// Note that the binary operation should have the property that if one of the
23344 /// operands is UNDEF then the result is UNDEF.
23345 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23346 // Look for the following pattern: if
23347 // A = < float a0, float a1, float a2, float a3 >
23348 // B = < float b0, float b1, float b2, float b3 >
23350 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23351 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23352 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23353 // which is A horizontal-op B.
23355 // At least one of the operands should be a vector shuffle.
23356 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23357 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23360 MVT VT = LHS.getSimpleValueType();
23362 assert((VT.is128BitVector() || VT.is256BitVector()) &&
23363 "Unsupported vector type for horizontal add/sub");
23365 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23366 // operate independently on 128-bit lanes.
23367 unsigned NumElts = VT.getVectorNumElements();
23368 unsigned NumLanes = VT.getSizeInBits()/128;
23369 unsigned NumLaneElts = NumElts / NumLanes;
23370 assert((NumLaneElts % 2 == 0) &&
23371 "Vector type should have an even number of elements in each lane");
23372 unsigned HalfLaneElts = NumLaneElts/2;
23374 // View LHS in the form
23375 // LHS = VECTOR_SHUFFLE A, B, LMask
23376 // If LHS is not a shuffle then pretend it is the shuffle
23377 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23378 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23381 SmallVector<int, 16> LMask(NumElts);
23382 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23383 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23384 A = LHS.getOperand(0);
23385 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23386 B = LHS.getOperand(1);
23387 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23388 std::copy(Mask.begin(), Mask.end(), LMask.begin());
23390 if (LHS.getOpcode() != ISD::UNDEF)
23392 for (unsigned i = 0; i != NumElts; ++i)
23396 // Likewise, view RHS in the form
23397 // RHS = VECTOR_SHUFFLE C, D, RMask
23399 SmallVector<int, 16> RMask(NumElts);
23400 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23401 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23402 C = RHS.getOperand(0);
23403 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23404 D = RHS.getOperand(1);
23405 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23406 std::copy(Mask.begin(), Mask.end(), RMask.begin());
23408 if (RHS.getOpcode() != ISD::UNDEF)
23410 for (unsigned i = 0; i != NumElts; ++i)
23414 // Check that the shuffles are both shuffling the same vectors.
23415 if (!(A == C && B == D) && !(A == D && B == C))
23418 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23419 if (!A.getNode() && !B.getNode())
23422 // If A and B occur in reverse order in RHS, then "swap" them (which means
23423 // rewriting the mask).
23425 ShuffleVectorSDNode::commuteMask(RMask);
23427 // At this point LHS and RHS are equivalent to
23428 // LHS = VECTOR_SHUFFLE A, B, LMask
23429 // RHS = VECTOR_SHUFFLE A, B, RMask
23430 // Check that the masks correspond to performing a horizontal operation.
23431 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23432 for (unsigned i = 0; i != NumLaneElts; ++i) {
23433 int LIdx = LMask[i+l], RIdx = RMask[i+l];
23435 // Ignore any UNDEF components.
23436 if (LIdx < 0 || RIdx < 0 ||
23437 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23438 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23441 // Check that successive elements are being operated on. If not, this is
23442 // not a horizontal operation.
23443 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23444 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23445 if (!(LIdx == Index && RIdx == Index + 1) &&
23446 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23451 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23452 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23456 /// Do target-specific dag combines on floating point adds.
23457 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23458 const X86Subtarget *Subtarget) {
23459 EVT VT = N->getValueType(0);
23460 SDValue LHS = N->getOperand(0);
23461 SDValue RHS = N->getOperand(1);
23463 // Try to synthesize horizontal adds from adds of shuffles.
23464 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23465 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23466 isHorizontalBinOp(LHS, RHS, true))
23467 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23471 /// Do target-specific dag combines on floating point subs.
23472 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23473 const X86Subtarget *Subtarget) {
23474 EVT VT = N->getValueType(0);
23475 SDValue LHS = N->getOperand(0);
23476 SDValue RHS = N->getOperand(1);
23478 // Try to synthesize horizontal subs from subs of shuffles.
23479 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23480 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23481 isHorizontalBinOp(LHS, RHS, false))
23482 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23486 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23487 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23488 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23490 // F[X]OR(0.0, x) -> x
23491 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23492 if (C->getValueAPF().isPosZero())
23493 return N->getOperand(1);
23495 // F[X]OR(x, 0.0) -> x
23496 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23497 if (C->getValueAPF().isPosZero())
23498 return N->getOperand(0);
23502 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23503 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23504 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23506 // Only perform optimizations if UnsafeMath is used.
23507 if (!DAG.getTarget().Options.UnsafeFPMath)
23510 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23511 // into FMINC and FMAXC, which are Commutative operations.
23512 unsigned NewOp = 0;
23513 switch (N->getOpcode()) {
23514 default: llvm_unreachable("unknown opcode");
23515 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
23516 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
23519 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23520 N->getOperand(0), N->getOperand(1));
23523 /// Do target-specific dag combines on X86ISD::FAND nodes.
23524 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23525 // FAND(0.0, x) -> 0.0
23526 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23527 if (C->getValueAPF().isPosZero())
23528 return N->getOperand(0);
23530 // FAND(x, 0.0) -> 0.0
23531 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23532 if (C->getValueAPF().isPosZero())
23533 return N->getOperand(1);
23538 /// Do target-specific dag combines on X86ISD::FANDN nodes
23539 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23540 // FANDN(0.0, x) -> x
23541 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23542 if (C->getValueAPF().isPosZero())
23543 return N->getOperand(1);
23545 // FANDN(x, 0.0) -> 0.0
23546 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23547 if (C->getValueAPF().isPosZero())
23548 return N->getOperand(1);
23553 static SDValue PerformBTCombine(SDNode *N,
23555 TargetLowering::DAGCombinerInfo &DCI) {
23556 // BT ignores high bits in the bit index operand.
23557 SDValue Op1 = N->getOperand(1);
23558 if (Op1.hasOneUse()) {
23559 unsigned BitWidth = Op1.getValueSizeInBits();
23560 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23561 APInt KnownZero, KnownOne;
23562 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23563 !DCI.isBeforeLegalizeOps());
23564 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23565 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23566 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23567 DCI.CommitTargetLoweringOpt(TLO);
23572 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23573 SDValue Op = N->getOperand(0);
23574 if (Op.getOpcode() == ISD::BITCAST)
23575 Op = Op.getOperand(0);
23576 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23577 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23578 VT.getVectorElementType().getSizeInBits() ==
23579 OpVT.getVectorElementType().getSizeInBits()) {
23580 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23585 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23586 const X86Subtarget *Subtarget) {
23587 EVT VT = N->getValueType(0);
23588 if (!VT.isVector())
23591 SDValue N0 = N->getOperand(0);
23592 SDValue N1 = N->getOperand(1);
23593 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23596 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23597 // both SSE and AVX2 since there is no sign-extended shift right
23598 // operation on a vector with 64-bit elements.
23599 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23600 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23601 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23602 N0.getOpcode() == ISD::SIGN_EXTEND)) {
23603 SDValue N00 = N0.getOperand(0);
23605 // EXTLOAD has a better solution on AVX2,
23606 // it may be replaced with X86ISD::VSEXT node.
23607 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23608 if (!ISD::isNormalLoad(N00.getNode()))
23611 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23612 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23614 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23620 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23621 TargetLowering::DAGCombinerInfo &DCI,
23622 const X86Subtarget *Subtarget) {
23623 SDValue N0 = N->getOperand(0);
23624 EVT VT = N->getValueType(0);
23626 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23627 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23628 // This exposes the sext to the sdivrem lowering, so that it directly extends
23629 // from AH (which we otherwise need to do contortions to access).
23630 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23631 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23633 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23634 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23635 N0.getOperand(0), N0.getOperand(1));
23636 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23637 return R.getValue(1);
23640 if (!DCI.isBeforeLegalizeOps())
23643 if (!Subtarget->hasFp256())
23646 if (VT.isVector() && VT.getSizeInBits() == 256) {
23647 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23655 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23656 const X86Subtarget* Subtarget) {
23658 EVT VT = N->getValueType(0);
23660 // Let legalize expand this if it isn't a legal type yet.
23661 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23664 EVT ScalarVT = VT.getScalarType();
23665 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23666 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23669 SDValue A = N->getOperand(0);
23670 SDValue B = N->getOperand(1);
23671 SDValue C = N->getOperand(2);
23673 bool NegA = (A.getOpcode() == ISD::FNEG);
23674 bool NegB = (B.getOpcode() == ISD::FNEG);
23675 bool NegC = (C.getOpcode() == ISD::FNEG);
23677 // Negative multiplication when NegA xor NegB
23678 bool NegMul = (NegA != NegB);
23680 A = A.getOperand(0);
23682 B = B.getOperand(0);
23684 C = C.getOperand(0);
23688 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23690 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23692 return DAG.getNode(Opcode, dl, VT, A, B, C);
23695 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23696 TargetLowering::DAGCombinerInfo &DCI,
23697 const X86Subtarget *Subtarget) {
23698 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23699 // (and (i32 x86isd::setcc_carry), 1)
23700 // This eliminates the zext. This transformation is necessary because
23701 // ISD::SETCC is always legalized to i8.
23703 SDValue N0 = N->getOperand(0);
23704 EVT VT = N->getValueType(0);
23706 if (N0.getOpcode() == ISD::AND &&
23708 N0.getOperand(0).hasOneUse()) {
23709 SDValue N00 = N0.getOperand(0);
23710 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23711 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23712 if (!C || C->getZExtValue() != 1)
23714 return DAG.getNode(ISD::AND, dl, VT,
23715 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23716 N00.getOperand(0), N00.getOperand(1)),
23717 DAG.getConstant(1, dl, VT));
23721 if (N0.getOpcode() == ISD::TRUNCATE &&
23723 N0.getOperand(0).hasOneUse()) {
23724 SDValue N00 = N0.getOperand(0);
23725 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23726 return DAG.getNode(ISD::AND, dl, VT,
23727 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23728 N00.getOperand(0), N00.getOperand(1)),
23729 DAG.getConstant(1, dl, VT));
23732 if (VT.is256BitVector()) {
23733 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23738 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23739 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23740 // This exposes the zext to the udivrem lowering, so that it directly extends
23741 // from AH (which we otherwise need to do contortions to access).
23742 if (N0.getOpcode() == ISD::UDIVREM &&
23743 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23744 (VT == MVT::i32 || VT == MVT::i64)) {
23745 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23746 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23747 N0.getOperand(0), N0.getOperand(1));
23748 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23749 return R.getValue(1);
23755 // Optimize x == -y --> x+y == 0
23756 // x != -y --> x+y != 0
23757 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23758 const X86Subtarget* Subtarget) {
23759 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23760 SDValue LHS = N->getOperand(0);
23761 SDValue RHS = N->getOperand(1);
23762 EVT VT = N->getValueType(0);
23765 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23766 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23767 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23768 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23769 LHS.getOperand(1));
23770 return DAG.getSetCC(DL, N->getValueType(0), addV,
23771 DAG.getConstant(0, DL, addV.getValueType()), CC);
23773 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23774 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23775 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23776 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23777 RHS.getOperand(1));
23778 return DAG.getSetCC(DL, N->getValueType(0), addV,
23779 DAG.getConstant(0, DL, addV.getValueType()), CC);
23782 if (VT.getScalarType() == MVT::i1 &&
23783 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23785 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23786 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23787 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23789 if (!IsSEXT0 || !IsVZero1) {
23790 // Swap the operands and update the condition code.
23791 std::swap(LHS, RHS);
23792 CC = ISD::getSetCCSwappedOperands(CC);
23794 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23795 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23796 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23799 if (IsSEXT0 && IsVZero1) {
23800 assert(VT == LHS.getOperand(0).getValueType() &&
23801 "Uexpected operand type");
23802 if (CC == ISD::SETGT)
23803 return DAG.getConstant(0, DL, VT);
23804 if (CC == ISD::SETLE)
23805 return DAG.getConstant(1, DL, VT);
23806 if (CC == ISD::SETEQ || CC == ISD::SETGE)
23807 return DAG.getNOT(DL, LHS.getOperand(0), VT);
23809 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23810 "Unexpected condition code!");
23811 return LHS.getOperand(0);
23818 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23819 SelectionDAG &DAG) {
23821 MVT VT = Load->getSimpleValueType(0);
23822 MVT EVT = VT.getVectorElementType();
23823 SDValue Addr = Load->getOperand(1);
23824 SDValue NewAddr = DAG.getNode(
23825 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23826 DAG.getConstant(Index * EVT.getStoreSize(), dl,
23827 Addr.getSimpleValueType()));
23830 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23831 DAG.getMachineFunction().getMachineMemOperand(
23832 Load->getMemOperand(), 0, EVT.getStoreSize()));
23836 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23837 const X86Subtarget *Subtarget) {
23839 MVT VT = N->getOperand(1)->getSimpleValueType(0);
23840 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23841 "X86insertps is only defined for v4x32");
23843 SDValue Ld = N->getOperand(1);
23844 if (MayFoldLoad(Ld)) {
23845 // Extract the countS bits from the immediate so we can get the proper
23846 // address when narrowing the vector load to a specific element.
23847 // When the second source op is a memory address, insertps doesn't use
23848 // countS and just gets an f32 from that address.
23849 unsigned DestIndex =
23850 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23852 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23854 // Create this as a scalar to vector to match the instruction pattern.
23855 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23856 // countS bits are ignored when loading from memory on insertps, which
23857 // means we don't need to explicitly set them to 0.
23858 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23859 LoadScalarToVector, N->getOperand(2));
23864 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23865 SDValue V0 = N->getOperand(0);
23866 SDValue V1 = N->getOperand(1);
23868 EVT VT = N->getValueType(0);
23870 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23871 // operands and changing the mask to 1. This saves us a bunch of
23872 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23873 // x86InstrInfo knows how to commute this back after instruction selection
23874 // if it would help register allocation.
23876 // TODO: If optimizing for size or a processor that doesn't suffer from
23877 // partial register update stalls, this should be transformed into a MOVSD
23878 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23880 if (VT == MVT::v2f64)
23881 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23882 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23883 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23884 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23890 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23891 // as "sbb reg,reg", since it can be extended without zext and produces
23892 // an all-ones bit which is more useful than 0/1 in some cases.
23893 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23896 return DAG.getNode(ISD::AND, DL, VT,
23897 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23898 DAG.getConstant(X86::COND_B, DL, MVT::i8),
23900 DAG.getConstant(1, DL, VT));
23901 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23902 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23903 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23904 DAG.getConstant(X86::COND_B, DL, MVT::i8),
23908 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23909 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23910 TargetLowering::DAGCombinerInfo &DCI,
23911 const X86Subtarget *Subtarget) {
23913 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23914 SDValue EFLAGS = N->getOperand(1);
23916 if (CC == X86::COND_A) {
23917 // Try to convert COND_A into COND_B in an attempt to facilitate
23918 // materializing "setb reg".
23920 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23921 // cannot take an immediate as its first operand.
23923 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23924 EFLAGS.getValueType().isInteger() &&
23925 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23926 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23927 EFLAGS.getNode()->getVTList(),
23928 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23929 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23930 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23934 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23935 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23937 if (CC == X86::COND_B)
23938 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23942 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23943 if (Flags.getNode()) {
23944 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23945 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23951 // Optimize branch condition evaluation.
23953 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23954 TargetLowering::DAGCombinerInfo &DCI,
23955 const X86Subtarget *Subtarget) {
23957 SDValue Chain = N->getOperand(0);
23958 SDValue Dest = N->getOperand(1);
23959 SDValue EFLAGS = N->getOperand(3);
23960 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23964 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23965 if (Flags.getNode()) {
23966 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23967 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23974 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23975 SelectionDAG &DAG) {
23976 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23977 // optimize away operation when it's from a constant.
23979 // The general transformation is:
23980 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23981 // AND(VECTOR_CMP(x,y), constant2)
23982 // constant2 = UNARYOP(constant)
23984 // Early exit if this isn't a vector operation, the operand of the
23985 // unary operation isn't a bitwise AND, or if the sizes of the operations
23986 // aren't the same.
23987 EVT VT = N->getValueType(0);
23988 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23989 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23990 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23993 // Now check that the other operand of the AND is a constant. We could
23994 // make the transformation for non-constant splats as well, but it's unclear
23995 // that would be a benefit as it would not eliminate any operations, just
23996 // perform one more step in scalar code before moving to the vector unit.
23997 if (BuildVectorSDNode *BV =
23998 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23999 // Bail out if the vector isn't a constant.
24000 if (!BV->isConstant())
24003 // Everything checks out. Build up the new and improved node.
24005 EVT IntVT = BV->getValueType(0);
24006 // Create a new constant of the appropriate type for the transformed
24008 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24009 // The AND node needs bitcasts to/from an integer vector type around it.
24010 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24011 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24012 N->getOperand(0)->getOperand(0), MaskConst);
24013 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24020 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24021 const X86Subtarget *Subtarget) {
24022 // First try to optimize away the conversion entirely when it's
24023 // conditionally from a constant. Vectors only.
24024 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24025 if (Res != SDValue())
24028 // Now move on to more general possibilities.
24029 SDValue Op0 = N->getOperand(0);
24030 EVT InVT = Op0->getValueType(0);
24032 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24033 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24035 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24036 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24037 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24040 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24041 // a 32-bit target where SSE doesn't support i64->FP operations.
24042 if (Op0.getOpcode() == ISD::LOAD) {
24043 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24044 EVT VT = Ld->getValueType(0);
24046 // This transformation is not supported if the result type is f16
24047 if (N->getValueType(0) == MVT::f16)
24050 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24051 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24052 !Subtarget->is64Bit() && VT == MVT::i64) {
24053 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24054 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24055 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24062 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24063 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24064 X86TargetLowering::DAGCombinerInfo &DCI) {
24065 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24066 // the result is either zero or one (depending on the input carry bit).
24067 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24068 if (X86::isZeroNode(N->getOperand(0)) &&
24069 X86::isZeroNode(N->getOperand(1)) &&
24070 // We don't have a good way to replace an EFLAGS use, so only do this when
24072 SDValue(N, 1).use_empty()) {
24074 EVT VT = N->getValueType(0);
24075 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24076 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24077 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24078 DAG.getConstant(X86::COND_B, DL,
24081 DAG.getConstant(1, DL, VT));
24082 return DCI.CombineTo(N, Res1, CarryOut);
24088 // fold (add Y, (sete X, 0)) -> adc 0, Y
24089 // (add Y, (setne X, 0)) -> sbb -1, Y
24090 // (sub (sete X, 0), Y) -> sbb 0, Y
24091 // (sub (setne X, 0), Y) -> adc -1, Y
24092 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24095 // Look through ZExts.
24096 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24097 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24100 SDValue SetCC = Ext.getOperand(0);
24101 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24104 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24105 if (CC != X86::COND_E && CC != X86::COND_NE)
24108 SDValue Cmp = SetCC.getOperand(1);
24109 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24110 !X86::isZeroNode(Cmp.getOperand(1)) ||
24111 !Cmp.getOperand(0).getValueType().isInteger())
24114 SDValue CmpOp0 = Cmp.getOperand(0);
24115 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24116 DAG.getConstant(1, DL, CmpOp0.getValueType()));
24118 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24119 if (CC == X86::COND_NE)
24120 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24121 DL, OtherVal.getValueType(), OtherVal,
24122 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24124 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24125 DL, OtherVal.getValueType(), OtherVal,
24126 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24129 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24130 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24131 const X86Subtarget *Subtarget) {
24132 EVT VT = N->getValueType(0);
24133 SDValue Op0 = N->getOperand(0);
24134 SDValue Op1 = N->getOperand(1);
24136 // Try to synthesize horizontal adds from adds of shuffles.
24137 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24138 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24139 isHorizontalBinOp(Op0, Op1, true))
24140 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24142 return OptimizeConditionalInDecrement(N, DAG);
24145 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24146 const X86Subtarget *Subtarget) {
24147 SDValue Op0 = N->getOperand(0);
24148 SDValue Op1 = N->getOperand(1);
24150 // X86 can't encode an immediate LHS of a sub. See if we can push the
24151 // negation into a preceding instruction.
24152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24153 // If the RHS of the sub is a XOR with one use and a constant, invert the
24154 // immediate. Then add one to the LHS of the sub so we can turn
24155 // X-Y -> X+~Y+1, saving one register.
24156 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24157 isa<ConstantSDNode>(Op1.getOperand(1))) {
24158 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24159 EVT VT = Op0.getValueType();
24160 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24162 DAG.getConstant(~XorC, SDLoc(Op1), VT));
24163 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24164 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24168 // Try to synthesize horizontal adds from adds of shuffles.
24169 EVT VT = N->getValueType(0);
24170 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24171 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24172 isHorizontalBinOp(Op0, Op1, true))
24173 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24175 return OptimizeConditionalInDecrement(N, DAG);
24178 /// performVZEXTCombine - Performs build vector combines
24179 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24180 TargetLowering::DAGCombinerInfo &DCI,
24181 const X86Subtarget *Subtarget) {
24183 MVT VT = N->getSimpleValueType(0);
24184 SDValue Op = N->getOperand(0);
24185 MVT OpVT = Op.getSimpleValueType();
24186 MVT OpEltVT = OpVT.getVectorElementType();
24187 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24189 // (vzext (bitcast (vzext (x)) -> (vzext x)
24191 while (V.getOpcode() == ISD::BITCAST)
24192 V = V.getOperand(0);
24194 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24195 MVT InnerVT = V.getSimpleValueType();
24196 MVT InnerEltVT = InnerVT.getVectorElementType();
24198 // If the element sizes match exactly, we can just do one larger vzext. This
24199 // is always an exact type match as vzext operates on integer types.
24200 if (OpEltVT == InnerEltVT) {
24201 assert(OpVT == InnerVT && "Types must match for vzext!");
24202 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24205 // The only other way we can combine them is if only a single element of the
24206 // inner vzext is used in the input to the outer vzext.
24207 if (InnerEltVT.getSizeInBits() < InputBits)
24210 // In this case, the inner vzext is completely dead because we're going to
24211 // only look at bits inside of the low element. Just do the outer vzext on
24212 // a bitcast of the input to the inner.
24213 return DAG.getNode(X86ISD::VZEXT, DL, VT,
24214 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24217 // Check if we can bypass extracting and re-inserting an element of an input
24218 // vector. Essentialy:
24219 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24220 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24221 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24222 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24223 SDValue ExtractedV = V.getOperand(0);
24224 SDValue OrigV = ExtractedV.getOperand(0);
24225 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24226 if (ExtractIdx->getZExtValue() == 0) {
24227 MVT OrigVT = OrigV.getSimpleValueType();
24228 // Extract a subvector if necessary...
24229 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24230 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24231 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24232 OrigVT.getVectorNumElements() / Ratio);
24233 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24234 DAG.getIntPtrConstant(0, DL));
24236 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24237 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24244 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24245 DAGCombinerInfo &DCI) const {
24246 SelectionDAG &DAG = DCI.DAG;
24247 switch (N->getOpcode()) {
24249 case ISD::EXTRACT_VECTOR_ELT:
24250 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24253 case X86ISD::SHRUNKBLEND:
24254 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24255 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
24256 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24257 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
24258 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
24259 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
24260 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
24263 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
24264 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
24265 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
24266 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
24267 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
24268 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24269 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
24270 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
24271 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24272 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
24273 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
24275 case X86ISD::FOR: return PerformFORCombine(N, DAG);
24277 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
24278 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
24279 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
24280 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
24281 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
24282 case ISD::ANY_EXTEND:
24283 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
24284 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
24285 case ISD::SIGN_EXTEND_INREG:
24286 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24287 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
24288 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
24289 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24290 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24291 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
24292 case X86ISD::SHUFP: // Handle all target specific shuffles
24293 case X86ISD::PALIGNR:
24294 case X86ISD::UNPCKH:
24295 case X86ISD::UNPCKL:
24296 case X86ISD::MOVHLPS:
24297 case X86ISD::MOVLHPS:
24298 case X86ISD::PSHUFB:
24299 case X86ISD::PSHUFD:
24300 case X86ISD::PSHUFHW:
24301 case X86ISD::PSHUFLW:
24302 case X86ISD::MOVSS:
24303 case X86ISD::MOVSD:
24304 case X86ISD::VPERMILPI:
24305 case X86ISD::VPERM2X128:
24306 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24307 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
24308 case ISD::INTRINSIC_WO_CHAIN:
24309 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24310 case X86ISD::INSERTPS: {
24311 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24312 return PerformINSERTPSCombine(N, DAG, Subtarget);
24315 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
24321 /// isTypeDesirableForOp - Return true if the target has native support for
24322 /// the specified value type and it is 'desirable' to use the type for the
24323 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24324 /// instruction encodings are longer and some i16 instructions are slow.
24325 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24326 if (!isTypeLegal(VT))
24328 if (VT != MVT::i16)
24335 case ISD::SIGN_EXTEND:
24336 case ISD::ZERO_EXTEND:
24337 case ISD::ANY_EXTEND:
24350 /// IsDesirableToPromoteOp - This method query the target whether it is
24351 /// beneficial for dag combiner to promote the specified node. If true, it
24352 /// should return the desired promotion type by reference.
24353 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24354 EVT VT = Op.getValueType();
24355 if (VT != MVT::i16)
24358 bool Promote = false;
24359 bool Commute = false;
24360 switch (Op.getOpcode()) {
24363 LoadSDNode *LD = cast<LoadSDNode>(Op);
24364 // If the non-extending load has a single use and it's not live out, then it
24365 // might be folded.
24366 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24367 Op.hasOneUse()*/) {
24368 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24369 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24370 // The only case where we'd want to promote LOAD (rather then it being
24371 // promoted as an operand is when it's only use is liveout.
24372 if (UI->getOpcode() != ISD::CopyToReg)
24379 case ISD::SIGN_EXTEND:
24380 case ISD::ZERO_EXTEND:
24381 case ISD::ANY_EXTEND:
24386 SDValue N0 = Op.getOperand(0);
24387 // Look out for (store (shl (load), x)).
24388 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24401 SDValue N0 = Op.getOperand(0);
24402 SDValue N1 = Op.getOperand(1);
24403 if (!Commute && MayFoldLoad(N1))
24405 // Avoid disabling potential load folding opportunities.
24406 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24408 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24418 //===----------------------------------------------------------------------===//
24419 // X86 Inline Assembly Support
24420 //===----------------------------------------------------------------------===//
24422 // Helper to match a string separated by whitespace.
24423 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24424 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24426 for (StringRef Piece : Pieces) {
24427 if (!S.startswith(Piece)) // Check if the piece matches.
24430 S = S.substr(Piece.size());
24431 StringRef::size_type Pos = S.find_first_not_of(" \t");
24432 if (Pos == 0) // We matched a prefix.
24441 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24443 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24444 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24445 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24446 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24448 if (AsmPieces.size() == 3)
24450 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24457 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24458 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24460 std::string AsmStr = IA->getAsmString();
24462 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24463 if (!Ty || Ty->getBitWidth() % 16 != 0)
24466 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24467 SmallVector<StringRef, 4> AsmPieces;
24468 SplitString(AsmStr, AsmPieces, ";\n");
24470 switch (AsmPieces.size()) {
24471 default: return false;
24473 // FIXME: this should verify that we are targeting a 486 or better. If not,
24474 // we will turn this bswap into something that will be lowered to logical
24475 // ops instead of emitting the bswap asm. For now, we don't support 486 or
24476 // lower so don't worry about this.
24478 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24479 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24480 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24481 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24482 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24483 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24484 // No need to check constraints, nothing other than the equivalent of
24485 // "=r,0" would be valid here.
24486 return IntrinsicLowering::LowerToByteSwap(CI);
24489 // rorw $$8, ${0:w} --> llvm.bswap.i16
24490 if (CI->getType()->isIntegerTy(16) &&
24491 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24492 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24493 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24495 const std::string &ConstraintsStr = IA->getConstraintString();
24496 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24497 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24498 if (clobbersFlagRegisters(AsmPieces))
24499 return IntrinsicLowering::LowerToByteSwap(CI);
24503 if (CI->getType()->isIntegerTy(32) &&
24504 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24505 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24506 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24507 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24509 const std::string &ConstraintsStr = IA->getConstraintString();
24510 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24511 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24512 if (clobbersFlagRegisters(AsmPieces))
24513 return IntrinsicLowering::LowerToByteSwap(CI);
24516 if (CI->getType()->isIntegerTy(64)) {
24517 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24518 if (Constraints.size() >= 2 &&
24519 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24520 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24521 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
24522 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24523 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24524 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24525 return IntrinsicLowering::LowerToByteSwap(CI);
24533 /// getConstraintType - Given a constraint letter, return the type of
24534 /// constraint it is for this target.
24535 X86TargetLowering::ConstraintType
24536 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24537 if (Constraint.size() == 1) {
24538 switch (Constraint[0]) {
24549 return C_RegisterClass;
24573 return TargetLowering::getConstraintType(Constraint);
24576 /// Examine constraint type and operand type and determine a weight value.
24577 /// This object must already have been set up with the operand type
24578 /// and the current alternative constraint selected.
24579 TargetLowering::ConstraintWeight
24580 X86TargetLowering::getSingleConstraintMatchWeight(
24581 AsmOperandInfo &info, const char *constraint) const {
24582 ConstraintWeight weight = CW_Invalid;
24583 Value *CallOperandVal = info.CallOperandVal;
24584 // If we don't have a value, we can't do a match,
24585 // but allow it at the lowest weight.
24586 if (!CallOperandVal)
24588 Type *type = CallOperandVal->getType();
24589 // Look at the constraint type.
24590 switch (*constraint) {
24592 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24603 if (CallOperandVal->getType()->isIntegerTy())
24604 weight = CW_SpecificReg;
24609 if (type->isFloatingPointTy())
24610 weight = CW_SpecificReg;
24613 if (type->isX86_MMXTy() && Subtarget->hasMMX())
24614 weight = CW_SpecificReg;
24618 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24619 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24620 weight = CW_Register;
24623 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24624 if (C->getZExtValue() <= 31)
24625 weight = CW_Constant;
24629 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24630 if (C->getZExtValue() <= 63)
24631 weight = CW_Constant;
24635 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24636 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24637 weight = CW_Constant;
24641 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24642 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24643 weight = CW_Constant;
24647 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24648 if (C->getZExtValue() <= 3)
24649 weight = CW_Constant;
24653 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24654 if (C->getZExtValue() <= 0xff)
24655 weight = CW_Constant;
24660 if (isa<ConstantFP>(CallOperandVal)) {
24661 weight = CW_Constant;
24665 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24666 if ((C->getSExtValue() >= -0x80000000LL) &&
24667 (C->getSExtValue() <= 0x7fffffffLL))
24668 weight = CW_Constant;
24672 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24673 if (C->getZExtValue() <= 0xffffffff)
24674 weight = CW_Constant;
24681 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24682 /// with another that has more specific requirements based on the type of the
24683 /// corresponding operand.
24684 const char *X86TargetLowering::
24685 LowerXConstraint(EVT ConstraintVT) const {
24686 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24687 // 'f' like normal targets.
24688 if (ConstraintVT.isFloatingPoint()) {
24689 if (Subtarget->hasSSE2())
24691 if (Subtarget->hasSSE1())
24695 return TargetLowering::LowerXConstraint(ConstraintVT);
24698 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24699 /// vector. If it is invalid, don't add anything to Ops.
24700 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24701 std::string &Constraint,
24702 std::vector<SDValue>&Ops,
24703 SelectionDAG &DAG) const {
24706 // Only support length 1 constraints for now.
24707 if (Constraint.length() > 1) return;
24709 char ConstraintLetter = Constraint[0];
24710 switch (ConstraintLetter) {
24713 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24714 if (C->getZExtValue() <= 31) {
24715 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24716 Op.getValueType());
24722 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24723 if (C->getZExtValue() <= 63) {
24724 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24725 Op.getValueType());
24731 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24732 if (isInt<8>(C->getSExtValue())) {
24733 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24734 Op.getValueType());
24740 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24741 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24742 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24743 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24744 Op.getValueType());
24750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24751 if (C->getZExtValue() <= 3) {
24752 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24753 Op.getValueType());
24759 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24760 if (C->getZExtValue() <= 255) {
24761 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24762 Op.getValueType());
24768 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24769 if (C->getZExtValue() <= 127) {
24770 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24771 Op.getValueType());
24777 // 32-bit signed value
24778 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24779 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24780 C->getSExtValue())) {
24781 // Widen to 64 bits here to get it sign extended.
24782 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24785 // FIXME gcc accepts some relocatable values here too, but only in certain
24786 // memory models; it's complicated.
24791 // 32-bit unsigned value
24792 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24793 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24794 C->getZExtValue())) {
24795 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24796 Op.getValueType());
24800 // FIXME gcc accepts some relocatable values here too, but only in certain
24801 // memory models; it's complicated.
24805 // Literal immediates are always ok.
24806 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24807 // Widen to 64 bits here to get it sign extended.
24808 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24812 // In any sort of PIC mode addresses need to be computed at runtime by
24813 // adding in a register or some sort of table lookup. These can't
24814 // be used as immediates.
24815 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24818 // If we are in non-pic codegen mode, we allow the address of a global (with
24819 // an optional displacement) to be used with 'i'.
24820 GlobalAddressSDNode *GA = nullptr;
24821 int64_t Offset = 0;
24823 // Match either (GA), (GA+C), (GA+C1+C2), etc.
24825 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24826 Offset += GA->getOffset();
24828 } else if (Op.getOpcode() == ISD::ADD) {
24829 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24830 Offset += C->getZExtValue();
24831 Op = Op.getOperand(0);
24834 } else if (Op.getOpcode() == ISD::SUB) {
24835 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24836 Offset += -C->getZExtValue();
24837 Op = Op.getOperand(0);
24842 // Otherwise, this isn't something we can handle, reject it.
24846 const GlobalValue *GV = GA->getGlobal();
24847 // If we require an extra load to get this address, as in PIC mode, we
24848 // can't accept it.
24849 if (isGlobalStubReference(
24850 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24853 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24854 GA->getValueType(0), Offset);
24859 if (Result.getNode()) {
24860 Ops.push_back(Result);
24863 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24866 std::pair<unsigned, const TargetRegisterClass *>
24867 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24868 const std::string &Constraint,
24870 // First, see if this is a constraint that directly corresponds to an LLVM
24872 if (Constraint.size() == 1) {
24873 // GCC Constraint Letters
24874 switch (Constraint[0]) {
24876 // TODO: Slight differences here in allocation order and leaving
24877 // RIP in the class. Do they matter any more here than they do
24878 // in the normal allocation?
24879 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24880 if (Subtarget->is64Bit()) {
24881 if (VT == MVT::i32 || VT == MVT::f32)
24882 return std::make_pair(0U, &X86::GR32RegClass);
24883 if (VT == MVT::i16)
24884 return std::make_pair(0U, &X86::GR16RegClass);
24885 if (VT == MVT::i8 || VT == MVT::i1)
24886 return std::make_pair(0U, &X86::GR8RegClass);
24887 if (VT == MVT::i64 || VT == MVT::f64)
24888 return std::make_pair(0U, &X86::GR64RegClass);
24891 // 32-bit fallthrough
24892 case 'Q': // Q_REGS
24893 if (VT == MVT::i32 || VT == MVT::f32)
24894 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24895 if (VT == MVT::i16)
24896 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24897 if (VT == MVT::i8 || VT == MVT::i1)
24898 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24899 if (VT == MVT::i64)
24900 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24902 case 'r': // GENERAL_REGS
24903 case 'l': // INDEX_REGS
24904 if (VT == MVT::i8 || VT == MVT::i1)
24905 return std::make_pair(0U, &X86::GR8RegClass);
24906 if (VT == MVT::i16)
24907 return std::make_pair(0U, &X86::GR16RegClass);
24908 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24909 return std::make_pair(0U, &X86::GR32RegClass);
24910 return std::make_pair(0U, &X86::GR64RegClass);
24911 case 'R': // LEGACY_REGS
24912 if (VT == MVT::i8 || VT == MVT::i1)
24913 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24914 if (VT == MVT::i16)
24915 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24916 if (VT == MVT::i32 || !Subtarget->is64Bit())
24917 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24918 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24919 case 'f': // FP Stack registers.
24920 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24921 // value to the correct fpstack register class.
24922 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24923 return std::make_pair(0U, &X86::RFP32RegClass);
24924 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24925 return std::make_pair(0U, &X86::RFP64RegClass);
24926 return std::make_pair(0U, &X86::RFP80RegClass);
24927 case 'y': // MMX_REGS if MMX allowed.
24928 if (!Subtarget->hasMMX()) break;
24929 return std::make_pair(0U, &X86::VR64RegClass);
24930 case 'Y': // SSE_REGS if SSE2 allowed
24931 if (!Subtarget->hasSSE2()) break;
24933 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24934 if (!Subtarget->hasSSE1()) break;
24936 switch (VT.SimpleTy) {
24938 // Scalar SSE types.
24941 return std::make_pair(0U, &X86::FR32RegClass);
24944 return std::make_pair(0U, &X86::FR64RegClass);
24952 return std::make_pair(0U, &X86::VR128RegClass);
24960 return std::make_pair(0U, &X86::VR256RegClass);
24965 return std::make_pair(0U, &X86::VR512RegClass);
24971 // Use the default implementation in TargetLowering to convert the register
24972 // constraint into a member of a register class.
24973 std::pair<unsigned, const TargetRegisterClass*> Res;
24974 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24976 // Not found as a standard register?
24978 // Map st(0) -> st(7) -> ST0
24979 if (Constraint.size() == 7 && Constraint[0] == '{' &&
24980 tolower(Constraint[1]) == 's' &&
24981 tolower(Constraint[2]) == 't' &&
24982 Constraint[3] == '(' &&
24983 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24984 Constraint[5] == ')' &&
24985 Constraint[6] == '}') {
24987 Res.first = X86::FP0+Constraint[4]-'0';
24988 Res.second = &X86::RFP80RegClass;
24992 // GCC allows "st(0)" to be called just plain "st".
24993 if (StringRef("{st}").equals_lower(Constraint)) {
24994 Res.first = X86::FP0;
24995 Res.second = &X86::RFP80RegClass;
25000 if (StringRef("{flags}").equals_lower(Constraint)) {
25001 Res.first = X86::EFLAGS;
25002 Res.second = &X86::CCRRegClass;
25006 // 'A' means EAX + EDX.
25007 if (Constraint == "A") {
25008 Res.first = X86::EAX;
25009 Res.second = &X86::GR32_ADRegClass;
25015 // Otherwise, check to see if this is a register class of the wrong value
25016 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25017 // turn into {ax},{dx}.
25018 if (Res.second->hasType(VT))
25019 return Res; // Correct type already, nothing to do.
25021 // All of the single-register GCC register classes map their values onto
25022 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
25023 // really want an 8-bit or 32-bit register, map to the appropriate register
25024 // class and return the appropriate register.
25025 if (Res.second == &X86::GR16RegClass) {
25026 if (VT == MVT::i8 || VT == MVT::i1) {
25027 unsigned DestReg = 0;
25028 switch (Res.first) {
25030 case X86::AX: DestReg = X86::AL; break;
25031 case X86::DX: DestReg = X86::DL; break;
25032 case X86::CX: DestReg = X86::CL; break;
25033 case X86::BX: DestReg = X86::BL; break;
25036 Res.first = DestReg;
25037 Res.second = &X86::GR8RegClass;
25039 } else if (VT == MVT::i32 || VT == MVT::f32) {
25040 unsigned DestReg = 0;
25041 switch (Res.first) {
25043 case X86::AX: DestReg = X86::EAX; break;
25044 case X86::DX: DestReg = X86::EDX; break;
25045 case X86::CX: DestReg = X86::ECX; break;
25046 case X86::BX: DestReg = X86::EBX; break;
25047 case X86::SI: DestReg = X86::ESI; break;
25048 case X86::DI: DestReg = X86::EDI; break;
25049 case X86::BP: DestReg = X86::EBP; break;
25050 case X86::SP: DestReg = X86::ESP; break;
25053 Res.first = DestReg;
25054 Res.second = &X86::GR32RegClass;
25056 } else if (VT == MVT::i64 || VT == MVT::f64) {
25057 unsigned DestReg = 0;
25058 switch (Res.first) {
25060 case X86::AX: DestReg = X86::RAX; break;
25061 case X86::DX: DestReg = X86::RDX; break;
25062 case X86::CX: DestReg = X86::RCX; break;
25063 case X86::BX: DestReg = X86::RBX; break;
25064 case X86::SI: DestReg = X86::RSI; break;
25065 case X86::DI: DestReg = X86::RDI; break;
25066 case X86::BP: DestReg = X86::RBP; break;
25067 case X86::SP: DestReg = X86::RSP; break;
25070 Res.first = DestReg;
25071 Res.second = &X86::GR64RegClass;
25074 } else if (Res.second == &X86::FR32RegClass ||
25075 Res.second == &X86::FR64RegClass ||
25076 Res.second == &X86::VR128RegClass ||
25077 Res.second == &X86::VR256RegClass ||
25078 Res.second == &X86::FR32XRegClass ||
25079 Res.second == &X86::FR64XRegClass ||
25080 Res.second == &X86::VR128XRegClass ||
25081 Res.second == &X86::VR256XRegClass ||
25082 Res.second == &X86::VR512RegClass) {
25083 // Handle references to XMM physical registers that got mapped into the
25084 // wrong class. This can happen with constraints like {xmm0} where the
25085 // target independent register mapper will just pick the first match it can
25086 // find, ignoring the required type.
25088 if (VT == MVT::f32 || VT == MVT::i32)
25089 Res.second = &X86::FR32RegClass;
25090 else if (VT == MVT::f64 || VT == MVT::i64)
25091 Res.second = &X86::FR64RegClass;
25092 else if (X86::VR128RegClass.hasType(VT))
25093 Res.second = &X86::VR128RegClass;
25094 else if (X86::VR256RegClass.hasType(VT))
25095 Res.second = &X86::VR256RegClass;
25096 else if (X86::VR512RegClass.hasType(VT))
25097 Res.second = &X86::VR512RegClass;
25103 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25105 // Scaling factors are not free at all.
25106 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25107 // will take 2 allocations in the out of order engine instead of 1
25108 // for plain addressing mode, i.e. inst (reg1).
25110 // vaddps (%rsi,%drx), %ymm0, %ymm1
25111 // Requires two allocations (one for the load, one for the computation)
25113 // vaddps (%rsi), %ymm0, %ymm1
25114 // Requires just 1 allocation, i.e., freeing allocations for other operations
25115 // and having less micro operations to execute.
25117 // For some X86 architectures, this is even worse because for instance for
25118 // stores, the complex addressing mode forces the instruction to use the
25119 // "load" ports instead of the dedicated "store" port.
25120 // E.g., on Haswell:
25121 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25122 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25123 if (isLegalAddressingMode(AM, Ty))
25124 // Scale represents reg2 * scale, thus account for 1
25125 // as soon as we use a second register.
25126 return AM.Scale != 0;
25130 bool X86TargetLowering::isTargetFTOL() const {
25131 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();