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::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1008 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1009 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1011 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1012 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1014 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1015 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1017 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1018 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1020 // In the customized shift lowering, the legal cases in AVX2 will be
1022 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1023 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1025 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1026 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1028 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1031 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1032 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1033 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1035 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1036 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1039 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1040 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1041 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1043 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1044 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1045 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1046 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1047 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1050 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1051 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1054 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1056 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1059 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1060 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1063 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1064 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1066 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1067 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1069 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1070 // even though v8i16 is a legal type.
1071 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1072 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1073 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1075 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1076 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1077 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1079 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1080 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1082 for (MVT VT : MVT::fp_vector_valuetypes())
1083 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1085 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1086 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1088 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1089 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1091 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1092 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1094 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1095 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1096 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1097 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1099 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1100 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1101 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1103 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1104 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1105 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1106 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1107 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1108 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1109 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1110 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1111 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1112 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1113 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1114 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1116 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1117 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1118 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1119 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1120 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1121 setOperationAction(ISD::FMA, MVT::f32, Legal);
1122 setOperationAction(ISD::FMA, MVT::f64, Legal);
1125 if (Subtarget->hasInt256()) {
1126 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1127 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1128 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1129 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1131 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1132 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1133 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1134 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1136 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1137 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1138 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1139 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1141 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1142 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1143 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1144 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1146 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1147 // when we have a 256bit-wide blend with immediate.
1148 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1150 // Only provide customized ctpop vector bit twiddling for vector types we
1151 // know to perform better than using the popcnt instructions on each
1152 // vector element. If popcnt isn't supported, always provide the custom
1154 if (!Subtarget->hasPOPCNT())
1155 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1157 // Custom CTPOP always performs better on natively supported v8i32
1158 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1160 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1161 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1162 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1163 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1164 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1165 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1166 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1168 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1169 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1170 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1171 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1172 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1173 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1175 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1176 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1177 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1178 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1180 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1181 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1182 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1183 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1185 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1186 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1187 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1188 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1191 // In the customized shift lowering, the legal cases in AVX2 will be
1193 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1194 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1196 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1199 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1201 // Custom lower several nodes for 256-bit types.
1202 for (MVT VT : MVT::vector_valuetypes()) {
1203 if (VT.getScalarSizeInBits() >= 32) {
1204 setOperationAction(ISD::MLOAD, VT, Legal);
1205 setOperationAction(ISD::MSTORE, VT, Legal);
1207 // Extract subvector is special because the value type
1208 // (result) is 128-bit but the source is 256-bit wide.
1209 if (VT.is128BitVector()) {
1210 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1212 // Do not attempt to custom lower other non-256-bit vectors
1213 if (!VT.is256BitVector())
1216 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1217 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1218 setOperationAction(ISD::VSELECT, VT, Custom);
1219 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1220 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1221 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1222 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1223 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1226 if (Subtarget->hasInt256())
1227 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1230 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1231 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1232 MVT VT = (MVT::SimpleValueType)i;
1234 // Do not attempt to promote non-256-bit vectors
1235 if (!VT.is256BitVector())
1238 setOperationAction(ISD::AND, VT, Promote);
1239 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1240 setOperationAction(ISD::OR, VT, Promote);
1241 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1242 setOperationAction(ISD::XOR, VT, Promote);
1243 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1244 setOperationAction(ISD::LOAD, VT, Promote);
1245 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1246 setOperationAction(ISD::SELECT, VT, Promote);
1247 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1251 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1252 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1253 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1254 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1255 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1257 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1258 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1259 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1261 for (MVT VT : MVT::fp_vector_valuetypes())
1262 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1264 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1265 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1266 setOperationAction(ISD::XOR, MVT::i1, Legal);
1267 setOperationAction(ISD::OR, MVT::i1, Legal);
1268 setOperationAction(ISD::AND, MVT::i1, Legal);
1269 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1270 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1271 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1272 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1273 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1275 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1276 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1277 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1278 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1279 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1280 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1282 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1283 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1284 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1285 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1286 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1287 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1288 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1289 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1291 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1292 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1293 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1294 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1295 if (Subtarget->is64Bit()) {
1296 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1297 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1298 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1299 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1301 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1302 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1303 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1304 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1305 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1306 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1307 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1308 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1309 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1310 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1311 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1312 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1313 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1314 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1315 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1316 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1318 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1319 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1320 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1321 if (Subtarget->hasDQI()) {
1322 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1323 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1325 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1326 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1327 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1328 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1329 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1330 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1331 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1332 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1333 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1334 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1335 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1336 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1337 if (Subtarget->hasDQI()) {
1338 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1339 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1341 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1342 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1343 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1344 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1347 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1349 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1350 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1352 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1353 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1354 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1355 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1356 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1358 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1359 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1361 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1363 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1364 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1365 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1366 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1367 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1368 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1369 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1370 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1371 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1372 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1373 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1375 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1376 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1378 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1379 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1381 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1383 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1384 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1386 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1387 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1389 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1390 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1392 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1393 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1394 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1395 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1396 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1397 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1399 if (Subtarget->hasCDI()) {
1400 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1401 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1403 if (Subtarget->hasDQI()) {
1404 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1405 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1406 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1408 // Custom lower several nodes.
1409 for (MVT VT : MVT::vector_valuetypes()) {
1410 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1412 setOperationAction(ISD::AND, VT, Legal);
1413 setOperationAction(ISD::OR, VT, Legal);
1414 setOperationAction(ISD::XOR, VT, Legal);
1416 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1417 setOperationAction(ISD::MGATHER, VT, Custom);
1418 setOperationAction(ISD::MSCATTER, VT, Custom);
1420 // Extract subvector is special because the value type
1421 // (result) is 256/128-bit but the source is 512-bit wide.
1422 if (VT.is128BitVector() || VT.is256BitVector()) {
1423 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1425 if (VT.getVectorElementType() == MVT::i1)
1426 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1428 // Do not attempt to custom lower other non-512-bit vectors
1429 if (!VT.is512BitVector())
1432 if (EltSize >= 32) {
1433 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1434 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1435 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1436 setOperationAction(ISD::VSELECT, VT, Legal);
1437 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1438 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1439 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1440 setOperationAction(ISD::MLOAD, VT, Legal);
1441 setOperationAction(ISD::MSTORE, VT, Legal);
1444 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1445 MVT VT = (MVT::SimpleValueType)i;
1447 // Do not attempt to promote non-512-bit vectors.
1448 if (!VT.is512BitVector())
1451 setOperationAction(ISD::SELECT, VT, Promote);
1452 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1456 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1457 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1458 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1460 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1461 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1463 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1464 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1465 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1466 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1467 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1468 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1469 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1470 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1471 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1472 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1473 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1474 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1475 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1476 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1477 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1478 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1479 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1480 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1481 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1482 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1483 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1484 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1485 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1487 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1488 const MVT VT = (MVT::SimpleValueType)i;
1490 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1492 // Do not attempt to promote non-512-bit vectors.
1493 if (!VT.is512BitVector())
1497 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1498 setOperationAction(ISD::VSELECT, VT, Legal);
1503 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1504 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1505 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1507 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1508 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1509 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1510 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1511 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1512 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1513 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1514 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1515 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1516 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1518 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1519 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1520 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1521 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1522 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1523 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1524 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1525 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1528 // We want to custom lower some of our intrinsics.
1529 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1530 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1531 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1532 if (!Subtarget->is64Bit())
1533 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1535 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1536 // handle type legalization for these operations here.
1538 // FIXME: We really should do custom legalization for addition and
1539 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1540 // than generic legalization for 64-bit multiplication-with-overflow, though.
1541 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1542 // Add/Sub/Mul with overflow operations are custom lowered.
1544 setOperationAction(ISD::SADDO, VT, Custom);
1545 setOperationAction(ISD::UADDO, VT, Custom);
1546 setOperationAction(ISD::SSUBO, VT, Custom);
1547 setOperationAction(ISD::USUBO, VT, Custom);
1548 setOperationAction(ISD::SMULO, VT, Custom);
1549 setOperationAction(ISD::UMULO, VT, Custom);
1553 if (!Subtarget->is64Bit()) {
1554 // These libcalls are not available in 32-bit.
1555 setLibcallName(RTLIB::SHL_I128, nullptr);
1556 setLibcallName(RTLIB::SRL_I128, nullptr);
1557 setLibcallName(RTLIB::SRA_I128, nullptr);
1560 // Combine sin / cos into one node or libcall if possible.
1561 if (Subtarget->hasSinCos()) {
1562 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1563 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1564 if (Subtarget->isTargetDarwin()) {
1565 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1566 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1567 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1568 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1572 if (Subtarget->isTargetWin64()) {
1573 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1574 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1575 setOperationAction(ISD::SREM, MVT::i128, Custom);
1576 setOperationAction(ISD::UREM, MVT::i128, Custom);
1577 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1578 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1581 // We have target-specific dag combine patterns for the following nodes:
1582 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1583 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1584 setTargetDAGCombine(ISD::BITCAST);
1585 setTargetDAGCombine(ISD::VSELECT);
1586 setTargetDAGCombine(ISD::SELECT);
1587 setTargetDAGCombine(ISD::SHL);
1588 setTargetDAGCombine(ISD::SRA);
1589 setTargetDAGCombine(ISD::SRL);
1590 setTargetDAGCombine(ISD::OR);
1591 setTargetDAGCombine(ISD::AND);
1592 setTargetDAGCombine(ISD::ADD);
1593 setTargetDAGCombine(ISD::FADD);
1594 setTargetDAGCombine(ISD::FSUB);
1595 setTargetDAGCombine(ISD::FMA);
1596 setTargetDAGCombine(ISD::SUB);
1597 setTargetDAGCombine(ISD::LOAD);
1598 setTargetDAGCombine(ISD::MLOAD);
1599 setTargetDAGCombine(ISD::STORE);
1600 setTargetDAGCombine(ISD::MSTORE);
1601 setTargetDAGCombine(ISD::ZERO_EXTEND);
1602 setTargetDAGCombine(ISD::ANY_EXTEND);
1603 setTargetDAGCombine(ISD::SIGN_EXTEND);
1604 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1605 setTargetDAGCombine(ISD::SINT_TO_FP);
1606 setTargetDAGCombine(ISD::SETCC);
1607 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1608 setTargetDAGCombine(ISD::BUILD_VECTOR);
1609 setTargetDAGCombine(ISD::MUL);
1610 setTargetDAGCombine(ISD::XOR);
1612 computeRegisterProperties(Subtarget->getRegisterInfo());
1614 // On Darwin, -Os means optimize for size without hurting performance,
1615 // do not reduce the limit.
1616 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1617 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1618 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1619 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1620 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1621 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1622 setPrefLoopAlignment(4); // 2^4 bytes.
1624 // Predictable cmov don't hurt on atom because it's in-order.
1625 PredictableSelectIsExpensive = !Subtarget->isAtom();
1626 EnableExtLdPromotion = true;
1627 setPrefFunctionAlignment(4); // 2^4 bytes.
1629 verifyIntrinsicTables();
1632 // This has so far only been implemented for 64-bit MachO.
1633 bool X86TargetLowering::useLoadStackGuardNode() const {
1634 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1637 TargetLoweringBase::LegalizeTypeAction
1638 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1639 if (ExperimentalVectorWideningLegalization &&
1640 VT.getVectorNumElements() != 1 &&
1641 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1642 return TypeWidenVector;
1644 return TargetLoweringBase::getPreferredVectorAction(VT);
1647 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1649 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1651 const unsigned NumElts = VT.getVectorNumElements();
1652 const EVT EltVT = VT.getVectorElementType();
1653 if (VT.is512BitVector()) {
1654 if (Subtarget->hasAVX512())
1655 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1656 EltVT == MVT::f32 || EltVT == MVT::f64)
1658 case 8: return MVT::v8i1;
1659 case 16: return MVT::v16i1;
1661 if (Subtarget->hasBWI())
1662 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1664 case 32: return MVT::v32i1;
1665 case 64: return MVT::v64i1;
1669 if (VT.is256BitVector() || VT.is128BitVector()) {
1670 if (Subtarget->hasVLX())
1671 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1672 EltVT == MVT::f32 || EltVT == MVT::f64)
1674 case 2: return MVT::v2i1;
1675 case 4: return MVT::v4i1;
1676 case 8: return MVT::v8i1;
1678 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1679 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1681 case 8: return MVT::v8i1;
1682 case 16: return MVT::v16i1;
1683 case 32: return MVT::v32i1;
1687 return VT.changeVectorElementTypeToInteger();
1690 /// Helper for getByValTypeAlignment to determine
1691 /// the desired ByVal argument alignment.
1692 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1695 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1696 if (VTy->getBitWidth() == 128)
1698 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1699 unsigned EltAlign = 0;
1700 getMaxByValAlign(ATy->getElementType(), EltAlign);
1701 if (EltAlign > MaxAlign)
1702 MaxAlign = EltAlign;
1703 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1704 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1705 unsigned EltAlign = 0;
1706 getMaxByValAlign(STy->getElementType(i), EltAlign);
1707 if (EltAlign > MaxAlign)
1708 MaxAlign = EltAlign;
1715 /// Return the desired alignment for ByVal aggregate
1716 /// function arguments in the caller parameter area. For X86, aggregates
1717 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1718 /// are at 4-byte boundaries.
1719 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1720 if (Subtarget->is64Bit()) {
1721 // Max of 8 and alignment of type.
1722 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1729 if (Subtarget->hasSSE1())
1730 getMaxByValAlign(Ty, Align);
1734 /// Returns the target specific optimal type for load
1735 /// and store operations as a result of memset, memcpy, and memmove
1736 /// lowering. If DstAlign is zero that means it's safe to destination
1737 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1738 /// means there isn't a need to check it against alignment requirement,
1739 /// probably because the source does not need to be loaded. If 'IsMemset' is
1740 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1741 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1742 /// source is constant so it does not need to be loaded.
1743 /// It returns EVT::Other if the type should be determined using generic
1744 /// target-independent logic.
1746 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1747 unsigned DstAlign, unsigned SrcAlign,
1748 bool IsMemset, bool ZeroMemset,
1750 MachineFunction &MF) const {
1751 const Function *F = MF.getFunction();
1752 if ((!IsMemset || ZeroMemset) &&
1753 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1755 (Subtarget->isUnalignedMemAccessFast() ||
1756 ((DstAlign == 0 || DstAlign >= 16) &&
1757 (SrcAlign == 0 || SrcAlign >= 16)))) {
1759 if (Subtarget->hasInt256())
1761 if (Subtarget->hasFp256())
1764 if (Subtarget->hasSSE2())
1766 if (Subtarget->hasSSE1())
1768 } else if (!MemcpyStrSrc && Size >= 8 &&
1769 !Subtarget->is64Bit() &&
1770 Subtarget->hasSSE2()) {
1771 // Do not use f64 to lower memcpy if source is string constant. It's
1772 // better to use i32 to avoid the loads.
1776 if (Subtarget->is64Bit() && Size >= 8)
1781 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1783 return X86ScalarSSEf32;
1784 else if (VT == MVT::f64)
1785 return X86ScalarSSEf64;
1790 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1795 *Fast = Subtarget->isUnalignedMemAccessFast();
1799 /// Return the entry encoding for a jump table in the
1800 /// current function. The returned value is a member of the
1801 /// MachineJumpTableInfo::JTEntryKind enum.
1802 unsigned X86TargetLowering::getJumpTableEncoding() const {
1803 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1805 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1806 Subtarget->isPICStyleGOT())
1807 return MachineJumpTableInfo::EK_Custom32;
1809 // Otherwise, use the normal jump table encoding heuristics.
1810 return TargetLowering::getJumpTableEncoding();
1813 bool X86TargetLowering::useSoftFloat() const {
1814 return Subtarget->useSoftFloat();
1818 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1819 const MachineBasicBlock *MBB,
1820 unsigned uid,MCContext &Ctx) const{
1821 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1822 Subtarget->isPICStyleGOT());
1823 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1825 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1826 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1829 /// Returns relocation base for the given PIC jumptable.
1830 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1831 SelectionDAG &DAG) const {
1832 if (!Subtarget->is64Bit())
1833 // This doesn't have SDLoc associated with it, but is not really the
1834 // same as a Register.
1835 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1839 /// This returns the relocation base for the given PIC jumptable,
1840 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1841 const MCExpr *X86TargetLowering::
1842 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1843 MCContext &Ctx) const {
1844 // X86-64 uses RIP relative addressing based on the jump table label.
1845 if (Subtarget->isPICStyleRIPRel())
1846 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1848 // Otherwise, the reference is relative to the PIC base.
1849 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1852 std::pair<const TargetRegisterClass *, uint8_t>
1853 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1855 const TargetRegisterClass *RRC = nullptr;
1857 switch (VT.SimpleTy) {
1859 return TargetLowering::findRepresentativeClass(TRI, VT);
1860 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1861 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1864 RRC = &X86::VR64RegClass;
1866 case MVT::f32: case MVT::f64:
1867 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1868 case MVT::v4f32: case MVT::v2f64:
1869 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1871 RRC = &X86::VR128RegClass;
1874 return std::make_pair(RRC, Cost);
1877 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1878 unsigned &Offset) const {
1879 if (!Subtarget->isTargetLinux())
1882 if (Subtarget->is64Bit()) {
1883 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1885 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1897 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1898 unsigned DestAS) const {
1899 assert(SrcAS != DestAS && "Expected different address spaces!");
1901 return SrcAS < 256 && DestAS < 256;
1904 //===----------------------------------------------------------------------===//
1905 // Return Value Calling Convention Implementation
1906 //===----------------------------------------------------------------------===//
1908 #include "X86GenCallingConv.inc"
1911 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1912 MachineFunction &MF, bool isVarArg,
1913 const SmallVectorImpl<ISD::OutputArg> &Outs,
1914 LLVMContext &Context) const {
1915 SmallVector<CCValAssign, 16> RVLocs;
1916 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1917 return CCInfo.CheckReturn(Outs, RetCC_X86);
1920 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1921 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1926 X86TargetLowering::LowerReturn(SDValue Chain,
1927 CallingConv::ID CallConv, bool isVarArg,
1928 const SmallVectorImpl<ISD::OutputArg> &Outs,
1929 const SmallVectorImpl<SDValue> &OutVals,
1930 SDLoc dl, SelectionDAG &DAG) const {
1931 MachineFunction &MF = DAG.getMachineFunction();
1932 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1934 SmallVector<CCValAssign, 16> RVLocs;
1935 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1936 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1939 SmallVector<SDValue, 6> RetOps;
1940 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1941 // Operand #1 = Bytes To Pop
1942 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1945 // Copy the result values into the output registers.
1946 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1947 CCValAssign &VA = RVLocs[i];
1948 assert(VA.isRegLoc() && "Can only return in registers!");
1949 SDValue ValToCopy = OutVals[i];
1950 EVT ValVT = ValToCopy.getValueType();
1952 // Promote values to the appropriate types.
1953 if (VA.getLocInfo() == CCValAssign::SExt)
1954 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1955 else if (VA.getLocInfo() == CCValAssign::ZExt)
1956 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1957 else if (VA.getLocInfo() == CCValAssign::AExt) {
1958 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1959 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1961 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1963 else if (VA.getLocInfo() == CCValAssign::BCvt)
1964 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1966 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1967 "Unexpected FP-extend for return value.");
1969 // If this is x86-64, and we disabled SSE, we can't return FP values,
1970 // or SSE or MMX vectors.
1971 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1972 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1973 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1974 report_fatal_error("SSE register return with SSE disabled");
1976 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1977 // llvm-gcc has never done it right and no one has noticed, so this
1978 // should be OK for now.
1979 if (ValVT == MVT::f64 &&
1980 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1981 report_fatal_error("SSE2 register return with SSE2 disabled");
1983 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1984 // the RET instruction and handled by the FP Stackifier.
1985 if (VA.getLocReg() == X86::FP0 ||
1986 VA.getLocReg() == X86::FP1) {
1987 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1988 // change the value to the FP stack register class.
1989 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1990 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1991 RetOps.push_back(ValToCopy);
1992 // Don't emit a copytoreg.
1996 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1997 // which is returned in RAX / RDX.
1998 if (Subtarget->is64Bit()) {
1999 if (ValVT == MVT::x86mmx) {
2000 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2001 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2002 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2004 // If we don't have SSE2 available, convert to v4f32 so the generated
2005 // register is legal.
2006 if (!Subtarget->hasSSE2())
2007 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2012 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2013 Flag = Chain.getValue(1);
2014 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2017 // All x86 ABIs require that for returning structs by value we copy
2018 // the sret argument into %rax/%eax (depending on ABI) for the return.
2019 // We saved the argument into a virtual register in the entry block,
2020 // so now we copy the value out and into %rax/%eax.
2022 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2023 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2024 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2025 // either case FuncInfo->setSRetReturnReg() will have been called.
2026 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2027 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2030 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2031 X86::RAX : X86::EAX;
2032 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2033 Flag = Chain.getValue(1);
2035 // RAX/EAX now acts like a return value.
2036 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2039 RetOps[0] = Chain; // Update chain.
2041 // Add the flag if we have it.
2043 RetOps.push_back(Flag);
2045 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2048 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2049 if (N->getNumValues() != 1)
2051 if (!N->hasNUsesOfValue(1, 0))
2054 SDValue TCChain = Chain;
2055 SDNode *Copy = *N->use_begin();
2056 if (Copy->getOpcode() == ISD::CopyToReg) {
2057 // If the copy has a glue operand, we conservatively assume it isn't safe to
2058 // perform a tail call.
2059 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2061 TCChain = Copy->getOperand(0);
2062 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2065 bool HasRet = false;
2066 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2068 if (UI->getOpcode() != X86ISD::RET_FLAG)
2070 // If we are returning more than one value, we can definitely
2071 // not make a tail call see PR19530
2072 if (UI->getNumOperands() > 4)
2074 if (UI->getNumOperands() == 4 &&
2075 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2088 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2089 ISD::NodeType ExtendKind) const {
2091 // TODO: Is this also valid on 32-bit?
2092 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2093 ReturnMVT = MVT::i8;
2095 ReturnMVT = MVT::i32;
2097 EVT MinVT = getRegisterType(Context, ReturnMVT);
2098 return VT.bitsLT(MinVT) ? MinVT : VT;
2101 /// Lower the result values of a call into the
2102 /// appropriate copies out of appropriate physical registers.
2105 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2106 CallingConv::ID CallConv, bool isVarArg,
2107 const SmallVectorImpl<ISD::InputArg> &Ins,
2108 SDLoc dl, SelectionDAG &DAG,
2109 SmallVectorImpl<SDValue> &InVals) const {
2111 // Assign locations to each value returned by this call.
2112 SmallVector<CCValAssign, 16> RVLocs;
2113 bool Is64Bit = Subtarget->is64Bit();
2114 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2116 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2118 // Copy all of the result registers out of their specified physreg.
2119 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2120 CCValAssign &VA = RVLocs[i];
2121 EVT CopyVT = VA.getLocVT();
2123 // If this is x86-64, and we disabled SSE, we can't return FP values
2124 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2125 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2126 report_fatal_error("SSE register return with SSE disabled");
2129 // If we prefer to use the value in xmm registers, copy it out as f80 and
2130 // use a truncate to move it from fp stack reg to xmm reg.
2131 bool RoundAfterCopy = false;
2132 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2133 isScalarFPTypeInSSEReg(VA.getValVT())) {
2135 RoundAfterCopy = (CopyVT != VA.getLocVT());
2138 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2139 CopyVT, InFlag).getValue(1);
2140 SDValue Val = Chain.getValue(0);
2143 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2144 // This truncation won't change the value.
2145 DAG.getIntPtrConstant(1, dl));
2147 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2148 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2150 InFlag = Chain.getValue(2);
2151 InVals.push_back(Val);
2157 //===----------------------------------------------------------------------===//
2158 // C & StdCall & Fast Calling Convention implementation
2159 //===----------------------------------------------------------------------===//
2160 // StdCall calling convention seems to be standard for many Windows' API
2161 // routines and around. It differs from C calling convention just a little:
2162 // callee should clean up the stack, not caller. Symbols should be also
2163 // decorated in some fancy way :) It doesn't support any vector arguments.
2164 // For info on fast calling convention see Fast Calling Convention (tail call)
2165 // implementation LowerX86_32FastCCCallTo.
2167 /// CallIsStructReturn - Determines whether a call uses struct return
2169 enum StructReturnType {
2174 static StructReturnType
2175 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2177 return NotStructReturn;
2179 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2180 if (!Flags.isSRet())
2181 return NotStructReturn;
2182 if (Flags.isInReg())
2183 return RegStructReturn;
2184 return StackStructReturn;
2187 /// Determines whether a function uses struct return semantics.
2188 static StructReturnType
2189 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2191 return NotStructReturn;
2193 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2194 if (!Flags.isSRet())
2195 return NotStructReturn;
2196 if (Flags.isInReg())
2197 return RegStructReturn;
2198 return StackStructReturn;
2201 /// Make a copy of an aggregate at address specified by "Src" to address
2202 /// "Dst" with size and alignment information specified by the specific
2203 /// parameter attribute. The copy will be passed as a byval function parameter.
2205 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2206 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2208 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2210 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2211 /*isVolatile*/false, /*AlwaysInline=*/true,
2212 /*isTailCall*/false,
2213 MachinePointerInfo(), MachinePointerInfo());
2216 /// Return true if the calling convention is one that
2217 /// supports tail call optimization.
2218 static bool IsTailCallConvention(CallingConv::ID CC) {
2219 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2220 CC == CallingConv::HiPE);
2223 /// \brief Return true if the calling convention is a C calling convention.
2224 static bool IsCCallConvention(CallingConv::ID CC) {
2225 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2226 CC == CallingConv::X86_64_SysV);
2229 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2230 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2234 CallingConv::ID CalleeCC = CS.getCallingConv();
2235 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2241 /// Return true if the function is being made into
2242 /// a tailcall target by changing its ABI.
2243 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2244 bool GuaranteedTailCallOpt) {
2245 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2249 X86TargetLowering::LowerMemArgument(SDValue Chain,
2250 CallingConv::ID CallConv,
2251 const SmallVectorImpl<ISD::InputArg> &Ins,
2252 SDLoc dl, SelectionDAG &DAG,
2253 const CCValAssign &VA,
2254 MachineFrameInfo *MFI,
2256 // Create the nodes corresponding to a load from this parameter slot.
2257 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2258 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2259 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2260 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2263 // If value is passed by pointer we have address passed instead of the value
2265 bool ExtendedInMem = VA.isExtInLoc() &&
2266 VA.getValVT().getScalarType() == MVT::i1;
2268 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2269 ValVT = VA.getLocVT();
2271 ValVT = VA.getValVT();
2273 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2274 // changed with more analysis.
2275 // In case of tail call optimization mark all arguments mutable. Since they
2276 // could be overwritten by lowering of arguments in case of a tail call.
2277 if (Flags.isByVal()) {
2278 unsigned Bytes = Flags.getByValSize();
2279 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2280 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2281 return DAG.getFrameIndex(FI, getPointerTy());
2283 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2284 VA.getLocMemOffset(), isImmutable);
2285 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2286 SDValue Val = DAG.getLoad(ValVT, dl, Chain, FIN,
2287 MachinePointerInfo::getFixedStack(FI),
2288 false, false, false, 0);
2289 return ExtendedInMem ?
2290 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2294 // FIXME: Get this from tablegen.
2295 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2296 const X86Subtarget *Subtarget) {
2297 assert(Subtarget->is64Bit());
2299 if (Subtarget->isCallingConvWin64(CallConv)) {
2300 static const MCPhysReg GPR64ArgRegsWin64[] = {
2301 X86::RCX, X86::RDX, X86::R8, X86::R9
2303 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2306 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2307 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2309 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2312 // FIXME: Get this from tablegen.
2313 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2314 CallingConv::ID CallConv,
2315 const X86Subtarget *Subtarget) {
2316 assert(Subtarget->is64Bit());
2317 if (Subtarget->isCallingConvWin64(CallConv)) {
2318 // The XMM registers which might contain var arg parameters are shadowed
2319 // in their paired GPR. So we only need to save the GPR to their home
2321 // TODO: __vectorcall will change this.
2325 const Function *Fn = MF.getFunction();
2326 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2327 bool isSoftFloat = Subtarget->useSoftFloat();
2328 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2329 "SSE register cannot be used when SSE is disabled!");
2330 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2331 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2335 static const MCPhysReg XMMArgRegs64Bit[] = {
2336 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2337 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2339 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2343 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2344 CallingConv::ID CallConv,
2346 const SmallVectorImpl<ISD::InputArg> &Ins,
2349 SmallVectorImpl<SDValue> &InVals)
2351 MachineFunction &MF = DAG.getMachineFunction();
2352 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2353 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2355 const Function* Fn = MF.getFunction();
2356 if (Fn->hasExternalLinkage() &&
2357 Subtarget->isTargetCygMing() &&
2358 Fn->getName() == "main")
2359 FuncInfo->setForceFramePointer(true);
2361 MachineFrameInfo *MFI = MF.getFrameInfo();
2362 bool Is64Bit = Subtarget->is64Bit();
2363 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2365 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2366 "Var args not supported with calling convention fastcc, ghc or hipe");
2368 // Assign locations to all of the incoming arguments.
2369 SmallVector<CCValAssign, 16> ArgLocs;
2370 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2372 // Allocate shadow area for Win64
2374 CCInfo.AllocateStack(32, 8);
2376 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2378 unsigned LastVal = ~0U;
2380 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381 CCValAssign &VA = ArgLocs[i];
2382 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2384 assert(VA.getValNo() != LastVal &&
2385 "Don't support value assigned to multiple locs yet");
2387 LastVal = VA.getValNo();
2389 if (VA.isRegLoc()) {
2390 EVT RegVT = VA.getLocVT();
2391 const TargetRegisterClass *RC;
2392 if (RegVT == MVT::i32)
2393 RC = &X86::GR32RegClass;
2394 else if (Is64Bit && RegVT == MVT::i64)
2395 RC = &X86::GR64RegClass;
2396 else if (RegVT == MVT::f32)
2397 RC = &X86::FR32RegClass;
2398 else if (RegVT == MVT::f64)
2399 RC = &X86::FR64RegClass;
2400 else if (RegVT.is512BitVector())
2401 RC = &X86::VR512RegClass;
2402 else if (RegVT.is256BitVector())
2403 RC = &X86::VR256RegClass;
2404 else if (RegVT.is128BitVector())
2405 RC = &X86::VR128RegClass;
2406 else if (RegVT == MVT::x86mmx)
2407 RC = &X86::VR64RegClass;
2408 else if (RegVT == MVT::i1)
2409 RC = &X86::VK1RegClass;
2410 else if (RegVT == MVT::v8i1)
2411 RC = &X86::VK8RegClass;
2412 else if (RegVT == MVT::v16i1)
2413 RC = &X86::VK16RegClass;
2414 else if (RegVT == MVT::v32i1)
2415 RC = &X86::VK32RegClass;
2416 else if (RegVT == MVT::v64i1)
2417 RC = &X86::VK64RegClass;
2419 llvm_unreachable("Unknown argument type!");
2421 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2422 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2424 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2425 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2427 if (VA.getLocInfo() == CCValAssign::SExt)
2428 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2429 DAG.getValueType(VA.getValVT()));
2430 else if (VA.getLocInfo() == CCValAssign::ZExt)
2431 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2432 DAG.getValueType(VA.getValVT()));
2433 else if (VA.getLocInfo() == CCValAssign::BCvt)
2434 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2436 if (VA.isExtInLoc()) {
2437 // Handle MMX values passed in XMM regs.
2438 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2439 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2441 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2444 assert(VA.isMemLoc());
2445 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2448 // If value is passed via pointer - do a load.
2449 if (VA.getLocInfo() == CCValAssign::Indirect)
2450 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2451 MachinePointerInfo(), false, false, false, 0);
2453 InVals.push_back(ArgValue);
2456 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2457 // All x86 ABIs require that for returning structs by value we copy the
2458 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2459 // the argument into a virtual register so that we can access it from the
2461 if (Ins[i].Flags.isSRet()) {
2462 unsigned Reg = FuncInfo->getSRetReturnReg();
2464 MVT PtrTy = getPointerTy();
2465 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2466 FuncInfo->setSRetReturnReg(Reg);
2468 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2469 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2474 unsigned StackSize = CCInfo.getNextStackOffset();
2475 // Align stack specially for tail calls.
2476 if (FuncIsMadeTailCallSafe(CallConv,
2477 MF.getTarget().Options.GuaranteedTailCallOpt))
2478 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2480 // If the function takes variable number of arguments, make a frame index for
2481 // the start of the first vararg value... for expansion of llvm.va_start. We
2482 // can skip this if there are no va_start calls.
2483 if (MFI->hasVAStart() &&
2484 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2485 CallConv != CallingConv::X86_ThisCall))) {
2486 FuncInfo->setVarArgsFrameIndex(
2487 MFI->CreateFixedObject(1, StackSize, true));
2490 MachineModuleInfo &MMI = MF.getMMI();
2491 const Function *WinEHParent = nullptr;
2492 if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2493 WinEHParent = MMI.getWinEHParent(Fn);
2494 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2495 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2497 // Figure out if XMM registers are in use.
2498 assert(!(Subtarget->useSoftFloat() &&
2499 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2500 "SSE register cannot be used when SSE is disabled!");
2502 // 64-bit calling conventions support varargs and register parameters, so we
2503 // have to do extra work to spill them in the prologue.
2504 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2505 // Find the first unallocated argument registers.
2506 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2507 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2508 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2509 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2510 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2511 "SSE register cannot be used when SSE is disabled!");
2513 // Gather all the live in physical registers.
2514 SmallVector<SDValue, 6> LiveGPRs;
2515 SmallVector<SDValue, 8> LiveXMMRegs;
2517 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2518 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2520 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2522 if (!ArgXMMs.empty()) {
2523 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2524 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2525 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2526 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2527 LiveXMMRegs.push_back(
2528 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2533 // Get to the caller-allocated home save location. Add 8 to account
2534 // for the return address.
2535 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2536 FuncInfo->setRegSaveFrameIndex(
2537 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2538 // Fixup to set vararg frame on shadow area (4 x i64).
2540 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2542 // For X86-64, if there are vararg parameters that are passed via
2543 // registers, then we must store them to their spots on the stack so
2544 // they may be loaded by deferencing the result of va_next.
2545 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2546 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2547 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2548 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2551 // Store the integer parameter registers.
2552 SmallVector<SDValue, 8> MemOps;
2553 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2555 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2556 for (SDValue Val : LiveGPRs) {
2557 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2558 DAG.getIntPtrConstant(Offset, dl));
2560 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2561 MachinePointerInfo::getFixedStack(
2562 FuncInfo->getRegSaveFrameIndex(), Offset),
2564 MemOps.push_back(Store);
2568 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2569 // Now store the XMM (fp + vector) parameter registers.
2570 SmallVector<SDValue, 12> SaveXMMOps;
2571 SaveXMMOps.push_back(Chain);
2572 SaveXMMOps.push_back(ALVal);
2573 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2574 FuncInfo->getRegSaveFrameIndex(), dl));
2575 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2576 FuncInfo->getVarArgsFPOffset(), dl));
2577 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2579 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2580 MVT::Other, SaveXMMOps));
2583 if (!MemOps.empty())
2584 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2585 } else if (IsWinEHOutlined) {
2586 // Get to the caller-allocated home save location. Add 8 to account
2587 // for the return address.
2588 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2589 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2590 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2592 MMI.getWinEHFuncInfo(Fn)
2593 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2594 FuncInfo->getRegSaveFrameIndex();
2596 // Store the second integer parameter (rdx) into rsp+16 relative to the
2597 // stack pointer at the entry of the function.
2599 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2600 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2601 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2602 Chain = DAG.getStore(
2603 Val.getValue(1), dl, Val, RSFIN,
2604 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2605 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2608 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2609 // Find the largest legal vector type.
2610 MVT VecVT = MVT::Other;
2611 // FIXME: Only some x86_32 calling conventions support AVX512.
2612 if (Subtarget->hasAVX512() &&
2613 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2614 CallConv == CallingConv::Intel_OCL_BI)))
2615 VecVT = MVT::v16f32;
2616 else if (Subtarget->hasAVX())
2618 else if (Subtarget->hasSSE2())
2621 // We forward some GPRs and some vector types.
2622 SmallVector<MVT, 2> RegParmTypes;
2623 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2624 RegParmTypes.push_back(IntVT);
2625 if (VecVT != MVT::Other)
2626 RegParmTypes.push_back(VecVT);
2628 // Compute the set of forwarded registers. The rest are scratch.
2629 SmallVectorImpl<ForwardedRegister> &Forwards =
2630 FuncInfo->getForwardedMustTailRegParms();
2631 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2633 // Conservatively forward AL on x86_64, since it might be used for varargs.
2634 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2635 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2636 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2639 // Copy all forwards from physical to virtual registers.
2640 for (ForwardedRegister &F : Forwards) {
2641 // FIXME: Can we use a less constrained schedule?
2642 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2643 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2644 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2648 // Some CCs need callee pop.
2649 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2650 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2651 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2653 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2654 // If this is an sret function, the return should pop the hidden pointer.
2655 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2656 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2657 argsAreStructReturn(Ins) == StackStructReturn)
2658 FuncInfo->setBytesToPopOnReturn(4);
2662 // RegSaveFrameIndex is X86-64 only.
2663 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2664 if (CallConv == CallingConv::X86_FastCall ||
2665 CallConv == CallingConv::X86_ThisCall)
2666 // fastcc functions can't have varargs.
2667 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2670 FuncInfo->setArgumentStackSize(StackSize);
2672 if (IsWinEHParent) {
2673 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2674 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2675 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2676 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2677 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2678 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2679 /*isVolatile=*/true,
2680 /*isNonTemporal=*/false, /*Alignment=*/0);
2687 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2688 SDValue StackPtr, SDValue Arg,
2689 SDLoc dl, SelectionDAG &DAG,
2690 const CCValAssign &VA,
2691 ISD::ArgFlagsTy Flags) const {
2692 unsigned LocMemOffset = VA.getLocMemOffset();
2693 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2694 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2695 if (Flags.isByVal())
2696 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2698 return DAG.getStore(Chain, dl, Arg, PtrOff,
2699 MachinePointerInfo::getStack(LocMemOffset),
2703 /// Emit a load of return address if tail call
2704 /// optimization is performed and it is required.
2706 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2707 SDValue &OutRetAddr, SDValue Chain,
2708 bool IsTailCall, bool Is64Bit,
2709 int FPDiff, SDLoc dl) const {
2710 // Adjust the Return address stack slot.
2711 EVT VT = getPointerTy();
2712 OutRetAddr = getReturnAddressFrameIndex(DAG);
2714 // Load the "old" Return address.
2715 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2716 false, false, false, 0);
2717 return SDValue(OutRetAddr.getNode(), 1);
2720 /// Emit a store of the return address if tail call
2721 /// optimization is performed and it is required (FPDiff!=0).
2722 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2723 SDValue Chain, SDValue RetAddrFrIdx,
2724 EVT PtrVT, unsigned SlotSize,
2725 int FPDiff, SDLoc dl) {
2726 // Store the return address to the appropriate stack slot.
2727 if (!FPDiff) return Chain;
2728 // Calculate the new stack slot for the return address.
2729 int NewReturnAddrFI =
2730 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2732 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2733 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2734 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2740 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2741 SmallVectorImpl<SDValue> &InVals) const {
2742 SelectionDAG &DAG = CLI.DAG;
2744 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2745 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2746 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2747 SDValue Chain = CLI.Chain;
2748 SDValue Callee = CLI.Callee;
2749 CallingConv::ID CallConv = CLI.CallConv;
2750 bool &isTailCall = CLI.IsTailCall;
2751 bool isVarArg = CLI.IsVarArg;
2753 MachineFunction &MF = DAG.getMachineFunction();
2754 bool Is64Bit = Subtarget->is64Bit();
2755 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2756 StructReturnType SR = callIsStructReturn(Outs);
2757 bool IsSibcall = false;
2758 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2760 if (MF.getTarget().Options.DisableTailCalls)
2763 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2765 // Force this to be a tail call. The verifier rules are enough to ensure
2766 // that we can lower this successfully without moving the return address
2769 } else if (isTailCall) {
2770 // Check if it's really possible to do a tail call.
2771 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2772 isVarArg, SR != NotStructReturn,
2773 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2774 Outs, OutVals, Ins, DAG);
2776 // Sibcalls are automatically detected tailcalls which do not require
2778 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2785 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2786 "Var args not supported with calling convention fastcc, ghc or hipe");
2788 // Analyze operands of the call, assigning locations to each operand.
2789 SmallVector<CCValAssign, 16> ArgLocs;
2790 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2792 // Allocate shadow area for Win64
2794 CCInfo.AllocateStack(32, 8);
2796 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2798 // Get a count of how many bytes are to be pushed on the stack.
2799 unsigned NumBytes = CCInfo.getNextStackOffset();
2801 // This is a sibcall. The memory operands are available in caller's
2802 // own caller's stack.
2804 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2805 IsTailCallConvention(CallConv))
2806 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2809 if (isTailCall && !IsSibcall && !IsMustTail) {
2810 // Lower arguments at fp - stackoffset + fpdiff.
2811 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2813 FPDiff = NumBytesCallerPushed - NumBytes;
2815 // Set the delta of movement of the returnaddr stackslot.
2816 // But only set if delta is greater than previous delta.
2817 if (FPDiff < X86Info->getTCReturnAddrDelta())
2818 X86Info->setTCReturnAddrDelta(FPDiff);
2821 unsigned NumBytesToPush = NumBytes;
2822 unsigned NumBytesToPop = NumBytes;
2824 // If we have an inalloca argument, all stack space has already been allocated
2825 // for us and be right at the top of the stack. We don't support multiple
2826 // arguments passed in memory when using inalloca.
2827 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2829 if (!ArgLocs.back().isMemLoc())
2830 report_fatal_error("cannot use inalloca attribute on a register "
2832 if (ArgLocs.back().getLocMemOffset() != 0)
2833 report_fatal_error("any parameter with the inalloca attribute must be "
2834 "the only memory argument");
2838 Chain = DAG.getCALLSEQ_START(
2839 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2841 SDValue RetAddrFrIdx;
2842 // Load return address for tail calls.
2843 if (isTailCall && FPDiff)
2844 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2845 Is64Bit, FPDiff, dl);
2847 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2848 SmallVector<SDValue, 8> MemOpChains;
2851 // Walk the register/memloc assignments, inserting copies/loads. In the case
2852 // of tail call optimization arguments are handle later.
2853 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2854 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2855 // Skip inalloca arguments, they have already been written.
2856 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2857 if (Flags.isInAlloca())
2860 CCValAssign &VA = ArgLocs[i];
2861 EVT RegVT = VA.getLocVT();
2862 SDValue Arg = OutVals[i];
2863 bool isByVal = Flags.isByVal();
2865 // Promote the value if needed.
2866 switch (VA.getLocInfo()) {
2867 default: llvm_unreachable("Unknown loc info!");
2868 case CCValAssign::Full: break;
2869 case CCValAssign::SExt:
2870 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2872 case CCValAssign::ZExt:
2873 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2875 case CCValAssign::AExt:
2876 if (Arg.getValueType().isVector() &&
2877 Arg.getValueType().getScalarType() == MVT::i1)
2878 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2879 else if (RegVT.is128BitVector()) {
2880 // Special case: passing MMX values in XMM registers.
2881 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2882 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2883 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2885 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2887 case CCValAssign::BCvt:
2888 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2890 case CCValAssign::Indirect: {
2891 // Store the argument.
2892 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2893 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2894 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2895 MachinePointerInfo::getFixedStack(FI),
2902 if (VA.isRegLoc()) {
2903 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2904 if (isVarArg && IsWin64) {
2905 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2906 // shadow reg if callee is a varargs function.
2907 unsigned ShadowReg = 0;
2908 switch (VA.getLocReg()) {
2909 case X86::XMM0: ShadowReg = X86::RCX; break;
2910 case X86::XMM1: ShadowReg = X86::RDX; break;
2911 case X86::XMM2: ShadowReg = X86::R8; break;
2912 case X86::XMM3: ShadowReg = X86::R9; break;
2915 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2917 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2918 assert(VA.isMemLoc());
2919 if (!StackPtr.getNode())
2920 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2922 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2923 dl, DAG, VA, Flags));
2927 if (!MemOpChains.empty())
2928 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2930 if (Subtarget->isPICStyleGOT()) {
2931 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2934 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2935 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2937 // If we are tail calling and generating PIC/GOT style code load the
2938 // address of the callee into ECX. The value in ecx is used as target of
2939 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2940 // for tail calls on PIC/GOT architectures. Normally we would just put the
2941 // address of GOT into ebx and then call target@PLT. But for tail calls
2942 // ebx would be restored (since ebx is callee saved) before jumping to the
2945 // Note: The actual moving to ECX is done further down.
2946 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2947 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2948 !G->getGlobal()->hasProtectedVisibility())
2949 Callee = LowerGlobalAddress(Callee, DAG);
2950 else if (isa<ExternalSymbolSDNode>(Callee))
2951 Callee = LowerExternalSymbol(Callee, DAG);
2955 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2956 // From AMD64 ABI document:
2957 // For calls that may call functions that use varargs or stdargs
2958 // (prototype-less calls or calls to functions containing ellipsis (...) in
2959 // the declaration) %al is used as hidden argument to specify the number
2960 // of SSE registers used. The contents of %al do not need to match exactly
2961 // the number of registers, but must be an ubound on the number of SSE
2962 // registers used and is in the range 0 - 8 inclusive.
2964 // Count the number of XMM registers allocated.
2965 static const MCPhysReg XMMArgRegs[] = {
2966 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2967 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2969 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2970 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2971 && "SSE registers cannot be used when SSE is disabled");
2973 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2974 DAG.getConstant(NumXMMRegs, dl,
2978 if (isVarArg && IsMustTail) {
2979 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2980 for (const auto &F : Forwards) {
2981 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2982 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2986 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2987 // don't need this because the eligibility check rejects calls that require
2988 // shuffling arguments passed in memory.
2989 if (!IsSibcall && isTailCall) {
2990 // Force all the incoming stack arguments to be loaded from the stack
2991 // before any new outgoing arguments are stored to the stack, because the
2992 // outgoing stack slots may alias the incoming argument stack slots, and
2993 // the alias isn't otherwise explicit. This is slightly more conservative
2994 // than necessary, because it means that each store effectively depends
2995 // on every argument instead of just those arguments it would clobber.
2996 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2998 SmallVector<SDValue, 8> MemOpChains2;
3001 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3002 CCValAssign &VA = ArgLocs[i];
3005 assert(VA.isMemLoc());
3006 SDValue Arg = OutVals[i];
3007 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3008 // Skip inalloca arguments. They don't require any work.
3009 if (Flags.isInAlloca())
3011 // Create frame index.
3012 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3013 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3014 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3015 FIN = DAG.getFrameIndex(FI, getPointerTy());
3017 if (Flags.isByVal()) {
3018 // Copy relative to framepointer.
3019 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3020 if (!StackPtr.getNode())
3021 StackPtr = DAG.getCopyFromReg(Chain, dl,
3022 RegInfo->getStackRegister(),
3024 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3026 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3030 // Store relative to framepointer.
3031 MemOpChains2.push_back(
3032 DAG.getStore(ArgChain, dl, Arg, FIN,
3033 MachinePointerInfo::getFixedStack(FI),
3038 if (!MemOpChains2.empty())
3039 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3041 // Store the return address to the appropriate stack slot.
3042 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3043 getPointerTy(), RegInfo->getSlotSize(),
3047 // Build a sequence of copy-to-reg nodes chained together with token chain
3048 // and flag operands which copy the outgoing args into registers.
3050 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3051 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3052 RegsToPass[i].second, InFlag);
3053 InFlag = Chain.getValue(1);
3056 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3057 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3058 // In the 64-bit large code model, we have to make all calls
3059 // through a register, since the call instruction's 32-bit
3060 // pc-relative offset may not be large enough to hold the whole
3062 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3063 // If the callee is a GlobalAddress node (quite common, every direct call
3064 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3066 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3068 // We should use extra load for direct calls to dllimported functions in
3070 const GlobalValue *GV = G->getGlobal();
3071 if (!GV->hasDLLImportStorageClass()) {
3072 unsigned char OpFlags = 0;
3073 bool ExtraLoad = false;
3074 unsigned WrapperKind = ISD::DELETED_NODE;
3076 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3077 // external symbols most go through the PLT in PIC mode. If the symbol
3078 // has hidden or protected visibility, or if it is static or local, then
3079 // we don't need to use the PLT - we can directly call it.
3080 if (Subtarget->isTargetELF() &&
3081 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3082 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3083 OpFlags = X86II::MO_PLT;
3084 } else if (Subtarget->isPICStyleStubAny() &&
3085 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3086 (!Subtarget->getTargetTriple().isMacOSX() ||
3087 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3088 // PC-relative references to external symbols should go through $stub,
3089 // unless we're building with the leopard linker or later, which
3090 // automatically synthesizes these stubs.
3091 OpFlags = X86II::MO_DARWIN_STUB;
3092 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3093 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3094 // If the function is marked as non-lazy, generate an indirect call
3095 // which loads from the GOT directly. This avoids runtime overhead
3096 // at the cost of eager binding (and one extra byte of encoding).
3097 OpFlags = X86II::MO_GOTPCREL;
3098 WrapperKind = X86ISD::WrapperRIP;
3102 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3103 G->getOffset(), OpFlags);
3105 // Add a wrapper if needed.
3106 if (WrapperKind != ISD::DELETED_NODE)
3107 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3108 // Add extra indirection if needed.
3110 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3111 MachinePointerInfo::getGOT(),
3112 false, false, false, 0);
3114 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3115 unsigned char OpFlags = 0;
3117 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3118 // external symbols should go through the PLT.
3119 if (Subtarget->isTargetELF() &&
3120 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3121 OpFlags = X86II::MO_PLT;
3122 } else if (Subtarget->isPICStyleStubAny() &&
3123 (!Subtarget->getTargetTriple().isMacOSX() ||
3124 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3125 // PC-relative references to external symbols should go through $stub,
3126 // unless we're building with the leopard linker or later, which
3127 // automatically synthesizes these stubs.
3128 OpFlags = X86II::MO_DARWIN_STUB;
3131 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3133 } else if (Subtarget->isTarget64BitILP32() &&
3134 Callee->getValueType(0) == MVT::i32) {
3135 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3136 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3139 // Returns a chain & a flag for retval copy to use.
3140 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3141 SmallVector<SDValue, 8> Ops;
3143 if (!IsSibcall && isTailCall) {
3144 Chain = DAG.getCALLSEQ_END(Chain,
3145 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3146 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3147 InFlag = Chain.getValue(1);
3150 Ops.push_back(Chain);
3151 Ops.push_back(Callee);
3154 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3156 // Add argument registers to the end of the list so that they are known live
3158 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3159 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3160 RegsToPass[i].second.getValueType()));
3162 // Add a register mask operand representing the call-preserved registers.
3163 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3164 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3165 assert(Mask && "Missing call preserved mask for calling convention");
3166 Ops.push_back(DAG.getRegisterMask(Mask));
3168 if (InFlag.getNode())
3169 Ops.push_back(InFlag);
3173 //// If this is the first return lowered for this function, add the regs
3174 //// to the liveout set for the function.
3175 // This isn't right, although it's probably harmless on x86; liveouts
3176 // should be computed from returns not tail calls. Consider a void
3177 // function making a tail call to a function returning int.
3178 MF.getFrameInfo()->setHasTailCall();
3179 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3182 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3183 InFlag = Chain.getValue(1);
3185 // Create the CALLSEQ_END node.
3186 unsigned NumBytesForCalleeToPop;
3187 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3188 DAG.getTarget().Options.GuaranteedTailCallOpt))
3189 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3190 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3191 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3192 SR == StackStructReturn)
3193 // If this is a call to a struct-return function, the callee
3194 // pops the hidden struct pointer, so we have to push it back.
3195 // This is common for Darwin/X86, Linux & Mingw32 targets.
3196 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3197 NumBytesForCalleeToPop = 4;
3199 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3201 // Returns a flag for retval copy to use.
3203 Chain = DAG.getCALLSEQ_END(Chain,
3204 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3205 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3208 InFlag = Chain.getValue(1);
3211 // Handle result values, copying them out of physregs into vregs that we
3213 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3214 Ins, dl, DAG, InVals);
3217 //===----------------------------------------------------------------------===//
3218 // Fast Calling Convention (tail call) implementation
3219 //===----------------------------------------------------------------------===//
3221 // Like std call, callee cleans arguments, convention except that ECX is
3222 // reserved for storing the tail called function address. Only 2 registers are
3223 // free for argument passing (inreg). Tail call optimization is performed
3225 // * tailcallopt is enabled
3226 // * caller/callee are fastcc
3227 // On X86_64 architecture with GOT-style position independent code only local
3228 // (within module) calls are supported at the moment.
3229 // To keep the stack aligned according to platform abi the function
3230 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3231 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3232 // If a tail called function callee has more arguments than the caller the
3233 // caller needs to make sure that there is room to move the RETADDR to. This is
3234 // achieved by reserving an area the size of the argument delta right after the
3235 // original RETADDR, but before the saved framepointer or the spilled registers
3236 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3248 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3249 /// for a 16 byte align requirement.
3251 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3252 SelectionDAG& DAG) const {
3253 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3254 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3255 unsigned StackAlignment = TFI.getStackAlignment();
3256 uint64_t AlignMask = StackAlignment - 1;
3257 int64_t Offset = StackSize;
3258 unsigned SlotSize = RegInfo->getSlotSize();
3259 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3260 // Number smaller than 12 so just add the difference.
3261 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3263 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3264 Offset = ((~AlignMask) & Offset) + StackAlignment +
3265 (StackAlignment-SlotSize);
3270 /// MatchingStackOffset - Return true if the given stack call argument is
3271 /// already available in the same position (relatively) of the caller's
3272 /// incoming argument stack.
3274 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3275 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3276 const X86InstrInfo *TII) {
3277 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3279 if (Arg.getOpcode() == ISD::CopyFromReg) {
3280 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3281 if (!TargetRegisterInfo::isVirtualRegister(VR))
3283 MachineInstr *Def = MRI->getVRegDef(VR);
3286 if (!Flags.isByVal()) {
3287 if (!TII->isLoadFromStackSlot(Def, FI))
3290 unsigned Opcode = Def->getOpcode();
3291 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3292 Opcode == X86::LEA64_32r) &&
3293 Def->getOperand(1).isFI()) {
3294 FI = Def->getOperand(1).getIndex();
3295 Bytes = Flags.getByValSize();
3299 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3300 if (Flags.isByVal())
3301 // ByVal argument is passed in as a pointer but it's now being
3302 // dereferenced. e.g.
3303 // define @foo(%struct.X* %A) {
3304 // tail call @bar(%struct.X* byval %A)
3307 SDValue Ptr = Ld->getBasePtr();
3308 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3311 FI = FINode->getIndex();
3312 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3313 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3314 FI = FINode->getIndex();
3315 Bytes = Flags.getByValSize();
3319 assert(FI != INT_MAX);
3320 if (!MFI->isFixedObjectIndex(FI))
3322 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3325 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3326 /// for tail call optimization. Targets which want to do tail call
3327 /// optimization should implement this function.
3329 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3330 CallingConv::ID CalleeCC,
3332 bool isCalleeStructRet,
3333 bool isCallerStructRet,
3335 const SmallVectorImpl<ISD::OutputArg> &Outs,
3336 const SmallVectorImpl<SDValue> &OutVals,
3337 const SmallVectorImpl<ISD::InputArg> &Ins,
3338 SelectionDAG &DAG) const {
3339 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3342 // If -tailcallopt is specified, make fastcc functions tail-callable.
3343 const MachineFunction &MF = DAG.getMachineFunction();
3344 const Function *CallerF = MF.getFunction();
3346 // If the function return type is x86_fp80 and the callee return type is not,
3347 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3348 // perform a tailcall optimization here.
3349 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3352 CallingConv::ID CallerCC = CallerF->getCallingConv();
3353 bool CCMatch = CallerCC == CalleeCC;
3354 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3355 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3357 // Win64 functions have extra shadow space for argument homing. Don't do the
3358 // sibcall if the caller and callee have mismatched expectations for this
3360 if (IsCalleeWin64 != IsCallerWin64)
3363 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3364 if (IsTailCallConvention(CalleeCC) && CCMatch)
3369 // Look for obvious safe cases to perform tail call optimization that do not
3370 // require ABI changes. This is what gcc calls sibcall.
3372 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3373 // emit a special epilogue.
3374 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3375 if (RegInfo->needsStackRealignment(MF))
3378 // Also avoid sibcall optimization if either caller or callee uses struct
3379 // return semantics.
3380 if (isCalleeStructRet || isCallerStructRet)
3383 // An stdcall/thiscall caller is expected to clean up its arguments; the
3384 // callee isn't going to do that.
3385 // FIXME: this is more restrictive than needed. We could produce a tailcall
3386 // when the stack adjustment matches. For example, with a thiscall that takes
3387 // only one argument.
3388 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3389 CallerCC == CallingConv::X86_ThisCall))
3392 // Do not sibcall optimize vararg calls unless all arguments are passed via
3394 if (isVarArg && !Outs.empty()) {
3396 // Optimizing for varargs on Win64 is unlikely to be safe without
3397 // additional testing.
3398 if (IsCalleeWin64 || IsCallerWin64)
3401 SmallVector<CCValAssign, 16> ArgLocs;
3402 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3405 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3406 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3407 if (!ArgLocs[i].isRegLoc())
3411 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3412 // stack. Therefore, if it's not used by the call it is not safe to optimize
3413 // this into a sibcall.
3414 bool Unused = false;
3415 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3422 SmallVector<CCValAssign, 16> RVLocs;
3423 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3425 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3426 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3427 CCValAssign &VA = RVLocs[i];
3428 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3433 // If the calling conventions do not match, then we'd better make sure the
3434 // results are returned in the same way as what the caller expects.
3436 SmallVector<CCValAssign, 16> RVLocs1;
3437 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3439 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3441 SmallVector<CCValAssign, 16> RVLocs2;
3442 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3444 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3446 if (RVLocs1.size() != RVLocs2.size())
3448 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3449 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3451 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3453 if (RVLocs1[i].isRegLoc()) {
3454 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3457 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3463 // If the callee takes no arguments then go on to check the results of the
3465 if (!Outs.empty()) {
3466 // Check if stack adjustment is needed. For now, do not do this if any
3467 // argument is passed on the stack.
3468 SmallVector<CCValAssign, 16> ArgLocs;
3469 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3472 // Allocate shadow area for Win64
3474 CCInfo.AllocateStack(32, 8);
3476 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3477 if (CCInfo.getNextStackOffset()) {
3478 MachineFunction &MF = DAG.getMachineFunction();
3479 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3482 // Check if the arguments are already laid out in the right way as
3483 // the caller's fixed stack objects.
3484 MachineFrameInfo *MFI = MF.getFrameInfo();
3485 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3486 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3487 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3488 CCValAssign &VA = ArgLocs[i];
3489 SDValue Arg = OutVals[i];
3490 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3491 if (VA.getLocInfo() == CCValAssign::Indirect)
3493 if (!VA.isRegLoc()) {
3494 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3501 // If the tailcall address may be in a register, then make sure it's
3502 // possible to register allocate for it. In 32-bit, the call address can
3503 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3504 // callee-saved registers are restored. These happen to be the same
3505 // registers used to pass 'inreg' arguments so watch out for those.
3506 if (!Subtarget->is64Bit() &&
3507 ((!isa<GlobalAddressSDNode>(Callee) &&
3508 !isa<ExternalSymbolSDNode>(Callee)) ||
3509 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3510 unsigned NumInRegs = 0;
3511 // In PIC we need an extra register to formulate the address computation
3513 unsigned MaxInRegs =
3514 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3516 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3517 CCValAssign &VA = ArgLocs[i];
3520 unsigned Reg = VA.getLocReg();
3523 case X86::EAX: case X86::EDX: case X86::ECX:
3524 if (++NumInRegs == MaxInRegs)
3536 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3537 const TargetLibraryInfo *libInfo) const {
3538 return X86::createFastISel(funcInfo, libInfo);
3541 //===----------------------------------------------------------------------===//
3542 // Other Lowering Hooks
3543 //===----------------------------------------------------------------------===//
3545 static bool MayFoldLoad(SDValue Op) {
3546 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3549 static bool MayFoldIntoStore(SDValue Op) {
3550 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3553 static bool isTargetShuffle(unsigned Opcode) {
3555 default: return false;
3556 case X86ISD::BLENDI:
3557 case X86ISD::PSHUFB:
3558 case X86ISD::PSHUFD:
3559 case X86ISD::PSHUFHW:
3560 case X86ISD::PSHUFLW:
3562 case X86ISD::PALIGNR:
3563 case X86ISD::MOVLHPS:
3564 case X86ISD::MOVLHPD:
3565 case X86ISD::MOVHLPS:
3566 case X86ISD::MOVLPS:
3567 case X86ISD::MOVLPD:
3568 case X86ISD::MOVSHDUP:
3569 case X86ISD::MOVSLDUP:
3570 case X86ISD::MOVDDUP:
3573 case X86ISD::UNPCKL:
3574 case X86ISD::UNPCKH:
3575 case X86ISD::VPERMILPI:
3576 case X86ISD::VPERM2X128:
3577 case X86ISD::VPERMI:
3582 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3583 SDValue V1, unsigned TargetMask,
3584 SelectionDAG &DAG) {
3586 default: llvm_unreachable("Unknown x86 shuffle node");
3587 case X86ISD::PSHUFD:
3588 case X86ISD::PSHUFHW:
3589 case X86ISD::PSHUFLW:
3590 case X86ISD::VPERMILPI:
3591 case X86ISD::VPERMI:
3592 return DAG.getNode(Opc, dl, VT, V1,
3593 DAG.getConstant(TargetMask, dl, MVT::i8));
3597 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3598 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3600 default: llvm_unreachable("Unknown x86 shuffle node");
3601 case X86ISD::MOVLHPS:
3602 case X86ISD::MOVLHPD:
3603 case X86ISD::MOVHLPS:
3604 case X86ISD::MOVLPS:
3605 case X86ISD::MOVLPD:
3608 case X86ISD::UNPCKL:
3609 case X86ISD::UNPCKH:
3610 return DAG.getNode(Opc, dl, VT, V1, V2);
3614 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3615 MachineFunction &MF = DAG.getMachineFunction();
3616 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3617 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3618 int ReturnAddrIndex = FuncInfo->getRAIndex();
3620 if (ReturnAddrIndex == 0) {
3621 // Set up a frame object for the return address.
3622 unsigned SlotSize = RegInfo->getSlotSize();
3623 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3626 FuncInfo->setRAIndex(ReturnAddrIndex);
3629 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3632 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3633 bool hasSymbolicDisplacement) {
3634 // Offset should fit into 32 bit immediate field.
3635 if (!isInt<32>(Offset))
3638 // If we don't have a symbolic displacement - we don't have any extra
3640 if (!hasSymbolicDisplacement)
3643 // FIXME: Some tweaks might be needed for medium code model.
3644 if (M != CodeModel::Small && M != CodeModel::Kernel)
3647 // For small code model we assume that latest object is 16MB before end of 31
3648 // bits boundary. We may also accept pretty large negative constants knowing
3649 // that all objects are in the positive half of address space.
3650 if (M == CodeModel::Small && Offset < 16*1024*1024)
3653 // For kernel code model we know that all object resist in the negative half
3654 // of 32bits address space. We may not accept negative offsets, since they may
3655 // be just off and we may accept pretty large positive ones.
3656 if (M == CodeModel::Kernel && Offset >= 0)
3662 /// isCalleePop - Determines whether the callee is required to pop its
3663 /// own arguments. Callee pop is necessary to support tail calls.
3664 bool X86::isCalleePop(CallingConv::ID CallingConv,
3665 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3666 switch (CallingConv) {
3669 case CallingConv::X86_StdCall:
3670 case CallingConv::X86_FastCall:
3671 case CallingConv::X86_ThisCall:
3673 case CallingConv::Fast:
3674 case CallingConv::GHC:
3675 case CallingConv::HiPE:
3682 /// \brief Return true if the condition is an unsigned comparison operation.
3683 static bool isX86CCUnsigned(unsigned X86CC) {
3685 default: llvm_unreachable("Invalid integer condition!");
3686 case X86::COND_E: return true;
3687 case X86::COND_G: return false;
3688 case X86::COND_GE: return false;
3689 case X86::COND_L: return false;
3690 case X86::COND_LE: return false;
3691 case X86::COND_NE: return true;
3692 case X86::COND_B: return true;
3693 case X86::COND_A: return true;
3694 case X86::COND_BE: return true;
3695 case X86::COND_AE: return true;
3697 llvm_unreachable("covered switch fell through?!");
3700 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3701 /// specific condition code, returning the condition code and the LHS/RHS of the
3702 /// comparison to make.
3703 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3704 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3706 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3707 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3708 // X > -1 -> X == 0, jump !sign.
3709 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3710 return X86::COND_NS;
3712 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3713 // X < 0 -> X == 0, jump on sign.
3716 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3718 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3719 return X86::COND_LE;
3723 switch (SetCCOpcode) {
3724 default: llvm_unreachable("Invalid integer condition!");
3725 case ISD::SETEQ: return X86::COND_E;
3726 case ISD::SETGT: return X86::COND_G;
3727 case ISD::SETGE: return X86::COND_GE;
3728 case ISD::SETLT: return X86::COND_L;
3729 case ISD::SETLE: return X86::COND_LE;
3730 case ISD::SETNE: return X86::COND_NE;
3731 case ISD::SETULT: return X86::COND_B;
3732 case ISD::SETUGT: return X86::COND_A;
3733 case ISD::SETULE: return X86::COND_BE;
3734 case ISD::SETUGE: return X86::COND_AE;
3738 // First determine if it is required or is profitable to flip the operands.
3740 // If LHS is a foldable load, but RHS is not, flip the condition.
3741 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3742 !ISD::isNON_EXTLoad(RHS.getNode())) {
3743 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3744 std::swap(LHS, RHS);
3747 switch (SetCCOpcode) {
3753 std::swap(LHS, RHS);
3757 // On a floating point condition, the flags are set as follows:
3759 // 0 | 0 | 0 | X > Y
3760 // 0 | 0 | 1 | X < Y
3761 // 1 | 0 | 0 | X == Y
3762 // 1 | 1 | 1 | unordered
3763 switch (SetCCOpcode) {
3764 default: llvm_unreachable("Condcode should be pre-legalized away");
3766 case ISD::SETEQ: return X86::COND_E;
3767 case ISD::SETOLT: // flipped
3769 case ISD::SETGT: return X86::COND_A;
3770 case ISD::SETOLE: // flipped
3772 case ISD::SETGE: return X86::COND_AE;
3773 case ISD::SETUGT: // flipped
3775 case ISD::SETLT: return X86::COND_B;
3776 case ISD::SETUGE: // flipped
3778 case ISD::SETLE: return X86::COND_BE;
3780 case ISD::SETNE: return X86::COND_NE;
3781 case ISD::SETUO: return X86::COND_P;
3782 case ISD::SETO: return X86::COND_NP;
3784 case ISD::SETUNE: return X86::COND_INVALID;
3788 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3789 /// code. Current x86 isa includes the following FP cmov instructions:
3790 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3791 static bool hasFPCMov(unsigned X86CC) {
3807 /// isFPImmLegal - Returns true if the target can instruction select the
3808 /// specified FP immediate natively. If false, the legalizer will
3809 /// materialize the FP immediate as a load from a constant pool.
3810 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3811 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3812 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3818 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3819 ISD::LoadExtType ExtTy,
3821 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3822 // relocation target a movq or addq instruction: don't let the load shrink.
3823 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3824 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3825 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3826 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3830 /// \brief Returns true if it is beneficial to convert a load of a constant
3831 /// to just the constant itself.
3832 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3834 assert(Ty->isIntegerTy());
3836 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3837 if (BitSize == 0 || BitSize > 64)
3842 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3843 unsigned Index) const {
3844 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3847 return (Index == 0 || Index == ResVT.getVectorNumElements());
3850 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3851 // Speculate cttz only if we can directly use TZCNT.
3852 return Subtarget->hasBMI();
3855 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3856 // Speculate ctlz only if we can directly use LZCNT.
3857 return Subtarget->hasLZCNT();
3860 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3861 /// the specified range (L, H].
3862 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3863 return (Val < 0) || (Val >= Low && Val < Hi);
3866 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3867 /// specified value.
3868 static bool isUndefOrEqual(int Val, int CmpVal) {
3869 return (Val < 0 || Val == CmpVal);
3872 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3873 /// from position Pos and ending in Pos+Size, falls within the specified
3874 /// sequential range (Low, Low+Size]. or is undef.
3875 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3876 unsigned Pos, unsigned Size, int Low) {
3877 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3878 if (!isUndefOrEqual(Mask[i], Low))
3883 /// isVEXTRACTIndex - Return true if the specified
3884 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3885 /// suitable for instruction that extract 128 or 256 bit vectors
3886 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3887 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3888 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3891 // The index should be aligned on a vecWidth-bit boundary.
3893 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3895 MVT VT = N->getSimpleValueType(0);
3896 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3897 bool Result = (Index * ElSize) % vecWidth == 0;
3902 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3903 /// operand specifies a subvector insert that is suitable for input to
3904 /// insertion of 128 or 256-bit subvectors
3905 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3906 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3907 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3909 // The index should be aligned on a vecWidth-bit boundary.
3911 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3913 MVT VT = N->getSimpleValueType(0);
3914 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3915 bool Result = (Index * ElSize) % vecWidth == 0;
3920 bool X86::isVINSERT128Index(SDNode *N) {
3921 return isVINSERTIndex(N, 128);
3924 bool X86::isVINSERT256Index(SDNode *N) {
3925 return isVINSERTIndex(N, 256);
3928 bool X86::isVEXTRACT128Index(SDNode *N) {
3929 return isVEXTRACTIndex(N, 128);
3932 bool X86::isVEXTRACT256Index(SDNode *N) {
3933 return isVEXTRACTIndex(N, 256);
3936 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3937 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3938 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3939 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3942 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3944 MVT VecVT = N->getOperand(0).getSimpleValueType();
3945 MVT ElVT = VecVT.getVectorElementType();
3947 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3948 return Index / NumElemsPerChunk;
3951 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3952 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3953 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3954 llvm_unreachable("Illegal insert subvector for VINSERT");
3957 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3959 MVT VecVT = N->getSimpleValueType(0);
3960 MVT ElVT = VecVT.getVectorElementType();
3962 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3963 return Index / NumElemsPerChunk;
3966 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3967 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3968 /// and VINSERTI128 instructions.
3969 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3970 return getExtractVEXTRACTImmediate(N, 128);
3973 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3974 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3975 /// and VINSERTI64x4 instructions.
3976 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3977 return getExtractVEXTRACTImmediate(N, 256);
3980 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3981 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3982 /// and VINSERTI128 instructions.
3983 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3984 return getInsertVINSERTImmediate(N, 128);
3987 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3988 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3989 /// and VINSERTI64x4 instructions.
3990 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3991 return getInsertVINSERTImmediate(N, 256);
3994 /// isZero - Returns true if Elt is a constant integer zero
3995 static bool isZero(SDValue V) {
3996 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3997 return C && C->isNullValue();
4000 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4002 bool X86::isZeroNode(SDValue Elt) {
4005 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4006 return CFP->getValueAPF().isPosZero();
4010 /// getZeroVector - Returns a vector of specified type with all zero elements.
4012 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4013 SelectionDAG &DAG, SDLoc dl) {
4014 assert(VT.isVector() && "Expected a vector type");
4016 // Always build SSE zero vectors as <4 x i32> bitcasted
4017 // to their dest type. This ensures they get CSE'd.
4019 if (VT.is128BitVector()) { // SSE
4020 if (Subtarget->hasSSE2()) { // SSE2
4021 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4022 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4024 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4025 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4027 } else if (VT.is256BitVector()) { // AVX
4028 if (Subtarget->hasInt256()) { // AVX2
4029 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4030 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4031 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4033 // 256-bit logic and arithmetic instructions in AVX are all
4034 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4035 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4036 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4037 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4039 } else if (VT.is512BitVector()) { // AVX-512
4040 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4041 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4042 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4043 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4044 } else if (VT.getScalarType() == MVT::i1) {
4046 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4047 && "Unexpected vector type");
4048 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4049 && "Unexpected vector type");
4050 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4051 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4052 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4054 llvm_unreachable("Unexpected vector type");
4056 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4059 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4060 SelectionDAG &DAG, SDLoc dl,
4061 unsigned vectorWidth) {
4062 assert((vectorWidth == 128 || vectorWidth == 256) &&
4063 "Unsupported vector width");
4064 EVT VT = Vec.getValueType();
4065 EVT ElVT = VT.getVectorElementType();
4066 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4067 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4068 VT.getVectorNumElements()/Factor);
4070 // Extract from UNDEF is UNDEF.
4071 if (Vec.getOpcode() == ISD::UNDEF)
4072 return DAG.getUNDEF(ResultVT);
4074 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4075 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4077 // This is the index of the first element of the vectorWidth-bit chunk
4079 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4082 // If the input is a buildvector just emit a smaller one.
4083 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4084 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4085 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4088 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4089 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4092 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4093 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4094 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4095 /// instructions or a simple subregister reference. Idx is an index in the
4096 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4097 /// lowering EXTRACT_VECTOR_ELT operations easier.
4098 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4099 SelectionDAG &DAG, SDLoc dl) {
4100 assert((Vec.getValueType().is256BitVector() ||
4101 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4102 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4105 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4106 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4107 SelectionDAG &DAG, SDLoc dl) {
4108 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4109 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4112 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4113 unsigned IdxVal, SelectionDAG &DAG,
4114 SDLoc dl, unsigned vectorWidth) {
4115 assert((vectorWidth == 128 || vectorWidth == 256) &&
4116 "Unsupported vector width");
4117 // Inserting UNDEF is Result
4118 if (Vec.getOpcode() == ISD::UNDEF)
4120 EVT VT = Vec.getValueType();
4121 EVT ElVT = VT.getVectorElementType();
4122 EVT ResultVT = Result.getValueType();
4124 // Insert the relevant vectorWidth bits.
4125 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4127 // This is the index of the first element of the vectorWidth-bit chunk
4129 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4132 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4133 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4136 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4137 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4138 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4139 /// simple superregister reference. Idx is an index in the 128 bits
4140 /// we want. It need not be aligned to a 128-bit boundary. That makes
4141 /// lowering INSERT_VECTOR_ELT operations easier.
4142 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4143 SelectionDAG &DAG, SDLoc dl) {
4144 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4146 // For insertion into the zero index (low half) of a 256-bit vector, it is
4147 // more efficient to generate a blend with immediate instead of an insert*128.
4148 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4149 // extend the subvector to the size of the result vector. Make sure that
4150 // we are not recursing on that node by checking for undef here.
4151 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4152 Result.getOpcode() != ISD::UNDEF) {
4153 EVT ResultVT = Result.getValueType();
4154 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4155 SDValue Undef = DAG.getUNDEF(ResultVT);
4156 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4159 // The blend instruction, and therefore its mask, depend on the data type.
4160 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4161 if (ScalarType.isFloatingPoint()) {
4162 // Choose either vblendps (float) or vblendpd (double).
4163 unsigned ScalarSize = ScalarType.getSizeInBits();
4164 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4165 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4166 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4167 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4170 const X86Subtarget &Subtarget =
4171 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4173 // AVX2 is needed for 256-bit integer blend support.
4174 // Integers must be cast to 32-bit because there is only vpblendd;
4175 // vpblendw can't be used for this because it has a handicapped mask.
4177 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4178 // is still more efficient than using the wrong domain vinsertf128 that
4179 // will be created by InsertSubVector().
4180 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4182 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4183 Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4184 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4185 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4188 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4191 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4192 SelectionDAG &DAG, SDLoc dl) {
4193 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4194 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4197 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4198 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4199 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4200 /// large BUILD_VECTORS.
4201 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4202 unsigned NumElems, SelectionDAG &DAG,
4204 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4205 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4208 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4209 unsigned NumElems, SelectionDAG &DAG,
4211 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4212 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4215 /// getOnesVector - Returns a vector of specified type with all bits set.
4216 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4217 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4218 /// Then bitcast to their original type, ensuring they get CSE'd.
4219 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4221 assert(VT.isVector() && "Expected a vector type");
4223 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4225 if (VT.is256BitVector()) {
4226 if (HasInt256) { // AVX2
4227 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4228 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4230 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4231 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4233 } else if (VT.is128BitVector()) {
4234 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4236 llvm_unreachable("Unexpected vector type");
4238 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4241 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4242 /// operation of specified width.
4243 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4245 unsigned NumElems = VT.getVectorNumElements();
4246 SmallVector<int, 8> Mask;
4247 Mask.push_back(NumElems);
4248 for (unsigned i = 1; i != NumElems; ++i)
4250 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4253 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4254 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4256 unsigned NumElems = VT.getVectorNumElements();
4257 SmallVector<int, 8> Mask;
4258 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4260 Mask.push_back(i + NumElems);
4262 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4265 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4266 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4268 unsigned NumElems = VT.getVectorNumElements();
4269 SmallVector<int, 8> Mask;
4270 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4271 Mask.push_back(i + Half);
4272 Mask.push_back(i + NumElems + Half);
4274 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4277 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4278 /// vector of zero or undef vector. This produces a shuffle where the low
4279 /// element of V2 is swizzled into the zero/undef vector, landing at element
4280 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4281 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4283 const X86Subtarget *Subtarget,
4284 SelectionDAG &DAG) {
4285 MVT VT = V2.getSimpleValueType();
4287 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4288 unsigned NumElems = VT.getVectorNumElements();
4289 SmallVector<int, 16> MaskVec;
4290 for (unsigned i = 0; i != NumElems; ++i)
4291 // If this is the insertion idx, put the low elt of V2 here.
4292 MaskVec.push_back(i == Idx ? NumElems : i);
4293 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4296 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4297 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4298 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4299 /// shuffles which use a single input multiple times, and in those cases it will
4300 /// adjust the mask to only have indices within that single input.
4301 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4302 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4303 unsigned NumElems = VT.getVectorNumElements();
4307 bool IsFakeUnary = false;
4308 switch(N->getOpcode()) {
4309 case X86ISD::BLENDI:
4310 ImmN = N->getOperand(N->getNumOperands()-1);
4311 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4314 ImmN = N->getOperand(N->getNumOperands()-1);
4315 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4316 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4318 case X86ISD::UNPCKH:
4319 DecodeUNPCKHMask(VT, Mask);
4320 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4322 case X86ISD::UNPCKL:
4323 DecodeUNPCKLMask(VT, Mask);
4324 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4326 case X86ISD::MOVHLPS:
4327 DecodeMOVHLPSMask(NumElems, Mask);
4328 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4330 case X86ISD::MOVLHPS:
4331 DecodeMOVLHPSMask(NumElems, Mask);
4332 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4334 case X86ISD::PALIGNR:
4335 ImmN = N->getOperand(N->getNumOperands()-1);
4336 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4338 case X86ISD::PSHUFD:
4339 case X86ISD::VPERMILPI:
4340 ImmN = N->getOperand(N->getNumOperands()-1);
4341 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4344 case X86ISD::PSHUFHW:
4345 ImmN = N->getOperand(N->getNumOperands()-1);
4346 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4349 case X86ISD::PSHUFLW:
4350 ImmN = N->getOperand(N->getNumOperands()-1);
4351 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4354 case X86ISD::PSHUFB: {
4356 SDValue MaskNode = N->getOperand(1);
4357 while (MaskNode->getOpcode() == ISD::BITCAST)
4358 MaskNode = MaskNode->getOperand(0);
4360 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4361 // If we have a build-vector, then things are easy.
4362 EVT VT = MaskNode.getValueType();
4363 assert(VT.isVector() &&
4364 "Can't produce a non-vector with a build_vector!");
4365 if (!VT.isInteger())
4368 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4370 SmallVector<uint64_t, 32> RawMask;
4371 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4372 SDValue Op = MaskNode->getOperand(i);
4373 if (Op->getOpcode() == ISD::UNDEF) {
4374 RawMask.push_back((uint64_t)SM_SentinelUndef);
4377 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4380 APInt MaskElement = CN->getAPIntValue();
4382 // We now have to decode the element which could be any integer size and
4383 // extract each byte of it.
4384 for (int j = 0; j < NumBytesPerElement; ++j) {
4385 // Note that this is x86 and so always little endian: the low byte is
4386 // the first byte of the mask.
4387 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4388 MaskElement = MaskElement.lshr(8);
4391 DecodePSHUFBMask(RawMask, Mask);
4395 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4399 SDValue Ptr = MaskLoad->getBasePtr();
4400 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4401 Ptr->getOpcode() == X86ISD::WrapperRIP)
4402 Ptr = Ptr->getOperand(0);
4404 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4405 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4408 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4409 DecodePSHUFBMask(C, Mask);
4417 case X86ISD::VPERMI:
4418 ImmN = N->getOperand(N->getNumOperands()-1);
4419 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4424 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4426 case X86ISD::VPERM2X128:
4427 ImmN = N->getOperand(N->getNumOperands()-1);
4428 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4429 if (Mask.empty()) return false;
4431 case X86ISD::MOVSLDUP:
4432 DecodeMOVSLDUPMask(VT, Mask);
4435 case X86ISD::MOVSHDUP:
4436 DecodeMOVSHDUPMask(VT, Mask);
4439 case X86ISD::MOVDDUP:
4440 DecodeMOVDDUPMask(VT, Mask);
4443 case X86ISD::MOVLHPD:
4444 case X86ISD::MOVLPD:
4445 case X86ISD::MOVLPS:
4446 // Not yet implemented
4448 default: llvm_unreachable("unknown target shuffle node");
4451 // If we have a fake unary shuffle, the shuffle mask is spread across two
4452 // inputs that are actually the same node. Re-map the mask to always point
4453 // into the first input.
4456 if (M >= (int)Mask.size())
4462 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4463 /// element of the result of the vector shuffle.
4464 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4467 return SDValue(); // Limit search depth.
4469 SDValue V = SDValue(N, 0);
4470 EVT VT = V.getValueType();
4471 unsigned Opcode = V.getOpcode();
4473 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4474 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4475 int Elt = SV->getMaskElt(Index);
4478 return DAG.getUNDEF(VT.getVectorElementType());
4480 unsigned NumElems = VT.getVectorNumElements();
4481 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4482 : SV->getOperand(1);
4483 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4486 // Recurse into target specific vector shuffles to find scalars.
4487 if (isTargetShuffle(Opcode)) {
4488 MVT ShufVT = V.getSimpleValueType();
4489 unsigned NumElems = ShufVT.getVectorNumElements();
4490 SmallVector<int, 16> ShuffleMask;
4493 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4496 int Elt = ShuffleMask[Index];
4498 return DAG.getUNDEF(ShufVT.getVectorElementType());
4500 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4502 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4506 // Actual nodes that may contain scalar elements
4507 if (Opcode == ISD::BITCAST) {
4508 V = V.getOperand(0);
4509 EVT SrcVT = V.getValueType();
4510 unsigned NumElems = VT.getVectorNumElements();
4512 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4516 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4517 return (Index == 0) ? V.getOperand(0)
4518 : DAG.getUNDEF(VT.getVectorElementType());
4520 if (V.getOpcode() == ISD::BUILD_VECTOR)
4521 return V.getOperand(Index);
4526 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4528 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4529 unsigned NumNonZero, unsigned NumZero,
4531 const X86Subtarget* Subtarget,
4532 const TargetLowering &TLI) {
4540 // SSE4.1 - use PINSRB to insert each byte directly.
4541 if (Subtarget->hasSSE41()) {
4542 for (unsigned i = 0; i < 16; ++i) {
4543 bool isNonZero = (NonZeros & (1 << i)) != 0;
4547 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4549 V = DAG.getUNDEF(MVT::v16i8);
4552 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4553 MVT::v16i8, V, Op.getOperand(i),
4554 DAG.getIntPtrConstant(i, dl));
4561 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4562 for (unsigned i = 0; i < 16; ++i) {
4563 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4564 if (ThisIsNonZero && First) {
4566 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4568 V = DAG.getUNDEF(MVT::v8i16);
4573 SDValue ThisElt, LastElt;
4574 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4575 if (LastIsNonZero) {
4576 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4577 MVT::i16, Op.getOperand(i-1));
4579 if (ThisIsNonZero) {
4580 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4581 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4582 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4584 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4588 if (ThisElt.getNode())
4589 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4590 DAG.getIntPtrConstant(i/2, dl));
4594 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4597 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4599 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4600 unsigned NumNonZero, unsigned NumZero,
4602 const X86Subtarget* Subtarget,
4603 const TargetLowering &TLI) {
4610 for (unsigned i = 0; i < 8; ++i) {
4611 bool isNonZero = (NonZeros & (1 << i)) != 0;
4615 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4617 V = DAG.getUNDEF(MVT::v8i16);
4620 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4621 MVT::v8i16, V, Op.getOperand(i),
4622 DAG.getIntPtrConstant(i, dl));
4629 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4630 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4631 const X86Subtarget *Subtarget,
4632 const TargetLowering &TLI) {
4633 // Find all zeroable elements.
4634 std::bitset<4> Zeroable;
4635 for (int i=0; i < 4; ++i) {
4636 SDValue Elt = Op->getOperand(i);
4637 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4639 assert(Zeroable.size() - Zeroable.count() > 1 &&
4640 "We expect at least two non-zero elements!");
4642 // We only know how to deal with build_vector nodes where elements are either
4643 // zeroable or extract_vector_elt with constant index.
4644 SDValue FirstNonZero;
4645 unsigned FirstNonZeroIdx;
4646 for (unsigned i=0; i < 4; ++i) {
4649 SDValue Elt = Op->getOperand(i);
4650 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4651 !isa<ConstantSDNode>(Elt.getOperand(1)))
4653 // Make sure that this node is extracting from a 128-bit vector.
4654 MVT VT = Elt.getOperand(0).getSimpleValueType();
4655 if (!VT.is128BitVector())
4657 if (!FirstNonZero.getNode()) {
4659 FirstNonZeroIdx = i;
4663 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4664 SDValue V1 = FirstNonZero.getOperand(0);
4665 MVT VT = V1.getSimpleValueType();
4667 // See if this build_vector can be lowered as a blend with zero.
4669 unsigned EltMaskIdx, EltIdx;
4671 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4672 if (Zeroable[EltIdx]) {
4673 // The zero vector will be on the right hand side.
4674 Mask[EltIdx] = EltIdx+4;
4678 Elt = Op->getOperand(EltIdx);
4679 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4680 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4681 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4683 Mask[EltIdx] = EltIdx;
4687 // Let the shuffle legalizer deal with blend operations.
4688 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4689 if (V1.getSimpleValueType() != VT)
4690 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4691 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4694 // See if we can lower this build_vector to a INSERTPS.
4695 if (!Subtarget->hasSSE41())
4698 SDValue V2 = Elt.getOperand(0);
4699 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4702 bool CanFold = true;
4703 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4707 SDValue Current = Op->getOperand(i);
4708 SDValue SrcVector = Current->getOperand(0);
4711 CanFold = SrcVector == V1 &&
4712 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4718 assert(V1.getNode() && "Expected at least two non-zero elements!");
4719 if (V1.getSimpleValueType() != MVT::v4f32)
4720 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4721 if (V2.getSimpleValueType() != MVT::v4f32)
4722 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4724 // Ok, we can emit an INSERTPS instruction.
4725 unsigned ZMask = Zeroable.to_ulong();
4727 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4728 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4730 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4731 DAG.getIntPtrConstant(InsertPSMask, DL));
4732 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4735 /// Return a vector logical shift node.
4736 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4737 unsigned NumBits, SelectionDAG &DAG,
4738 const TargetLowering &TLI, SDLoc dl) {
4739 assert(VT.is128BitVector() && "Unknown type for VShift");
4740 MVT ShVT = MVT::v2i64;
4741 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4742 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4743 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4744 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4745 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4746 return DAG.getNode(ISD::BITCAST, dl, VT,
4747 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4751 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4753 // Check if the scalar load can be widened into a vector load. And if
4754 // the address is "base + cst" see if the cst can be "absorbed" into
4755 // the shuffle mask.
4756 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4757 SDValue Ptr = LD->getBasePtr();
4758 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4760 EVT PVT = LD->getValueType(0);
4761 if (PVT != MVT::i32 && PVT != MVT::f32)
4766 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4767 FI = FINode->getIndex();
4769 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4770 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4771 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4772 Offset = Ptr.getConstantOperandVal(1);
4773 Ptr = Ptr.getOperand(0);
4778 // FIXME: 256-bit vector instructions don't require a strict alignment,
4779 // improve this code to support it better.
4780 unsigned RequiredAlign = VT.getSizeInBits()/8;
4781 SDValue Chain = LD->getChain();
4782 // Make sure the stack object alignment is at least 16 or 32.
4783 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4784 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4785 if (MFI->isFixedObjectIndex(FI)) {
4786 // Can't change the alignment. FIXME: It's possible to compute
4787 // the exact stack offset and reference FI + adjust offset instead.
4788 // If someone *really* cares about this. That's the way to implement it.
4791 MFI->setObjectAlignment(FI, RequiredAlign);
4795 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4796 // Ptr + (Offset & ~15).
4799 if ((Offset % RequiredAlign) & 3)
4801 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4804 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4805 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4808 int EltNo = (Offset - StartOffset) >> 2;
4809 unsigned NumElems = VT.getVectorNumElements();
4811 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4812 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4813 LD->getPointerInfo().getWithOffset(StartOffset),
4814 false, false, false, 0);
4816 SmallVector<int, 8> Mask(NumElems, EltNo);
4818 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4824 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4825 /// elements can be replaced by a single large load which has the same value as
4826 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4828 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4830 /// FIXME: we'd also like to handle the case where the last elements are zero
4831 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4832 /// There's even a handy isZeroNode for that purpose.
4833 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4834 SDLoc &DL, SelectionDAG &DAG,
4835 bool isAfterLegalize) {
4836 unsigned NumElems = Elts.size();
4838 LoadSDNode *LDBase = nullptr;
4839 unsigned LastLoadedElt = -1U;
4841 // For each element in the initializer, see if we've found a load or an undef.
4842 // If we don't find an initial load element, or later load elements are
4843 // non-consecutive, bail out.
4844 for (unsigned i = 0; i < NumElems; ++i) {
4845 SDValue Elt = Elts[i];
4846 // Look through a bitcast.
4847 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4848 Elt = Elt.getOperand(0);
4849 if (!Elt.getNode() ||
4850 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4853 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4855 LDBase = cast<LoadSDNode>(Elt.getNode());
4859 if (Elt.getOpcode() == ISD::UNDEF)
4862 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4863 EVT LdVT = Elt.getValueType();
4864 // Each loaded element must be the correct fractional portion of the
4865 // requested vector load.
4866 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4868 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4873 // If we have found an entire vector of loads and undefs, then return a large
4874 // load of the entire vector width starting at the base pointer. If we found
4875 // consecutive loads for the low half, generate a vzext_load node.
4876 if (LastLoadedElt == NumElems - 1) {
4877 assert(LDBase && "Did not find base load for merging consecutive loads");
4878 EVT EltVT = LDBase->getValueType(0);
4879 // Ensure that the input vector size for the merged loads matches the
4880 // cumulative size of the input elements.
4881 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4884 if (isAfterLegalize &&
4885 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4888 SDValue NewLd = SDValue();
4890 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4891 LDBase->getPointerInfo(), LDBase->isVolatile(),
4892 LDBase->isNonTemporal(), LDBase->isInvariant(),
4893 LDBase->getAlignment());
4895 if (LDBase->hasAnyUseOfValue(1)) {
4896 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4898 SDValue(NewLd.getNode(), 1));
4899 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4900 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4901 SDValue(NewLd.getNode(), 1));
4907 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4908 //of a v4i32 / v4f32. It's probably worth generalizing.
4909 EVT EltVT = VT.getVectorElementType();
4910 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4911 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4912 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4913 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4915 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4916 LDBase->getPointerInfo(),
4917 LDBase->getAlignment(),
4918 false/*isVolatile*/, true/*ReadMem*/,
4921 // Make sure the newly-created LOAD is in the same position as LDBase in
4922 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4923 // update uses of LDBase's output chain to use the TokenFactor.
4924 if (LDBase->hasAnyUseOfValue(1)) {
4925 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4926 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4927 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4928 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4929 SDValue(ResNode.getNode(), 1));
4932 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4937 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4938 /// to generate a splat value for the following cases:
4939 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4940 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4941 /// a scalar load, or a constant.
4942 /// The VBROADCAST node is returned when a pattern is found,
4943 /// or SDValue() otherwise.
4944 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4945 SelectionDAG &DAG) {
4946 // VBROADCAST requires AVX.
4947 // TODO: Splats could be generated for non-AVX CPUs using SSE
4948 // instructions, but there's less potential gain for only 128-bit vectors.
4949 if (!Subtarget->hasAVX())
4952 MVT VT = Op.getSimpleValueType();
4955 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4956 "Unsupported vector type for broadcast.");
4961 switch (Op.getOpcode()) {
4963 // Unknown pattern found.
4966 case ISD::BUILD_VECTOR: {
4967 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4968 BitVector UndefElements;
4969 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4971 // We need a splat of a single value to use broadcast, and it doesn't
4972 // make any sense if the value is only in one element of the vector.
4973 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4977 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4978 Ld.getOpcode() == ISD::ConstantFP);
4980 // Make sure that all of the users of a non-constant load are from the
4981 // BUILD_VECTOR node.
4982 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4987 case ISD::VECTOR_SHUFFLE: {
4988 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4990 // Shuffles must have a splat mask where the first element is
4992 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4995 SDValue Sc = Op.getOperand(0);
4996 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4997 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4999 if (!Subtarget->hasInt256())
5002 // Use the register form of the broadcast instruction available on AVX2.
5003 if (VT.getSizeInBits() >= 256)
5004 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5005 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5008 Ld = Sc.getOperand(0);
5009 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5010 Ld.getOpcode() == ISD::ConstantFP);
5012 // The scalar_to_vector node and the suspected
5013 // load node must have exactly one user.
5014 // Constants may have multiple users.
5016 // AVX-512 has register version of the broadcast
5017 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5018 Ld.getValueType().getSizeInBits() >= 32;
5019 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5026 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5027 bool IsGE256 = (VT.getSizeInBits() >= 256);
5029 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5030 // instruction to save 8 or more bytes of constant pool data.
5031 // TODO: If multiple splats are generated to load the same constant,
5032 // it may be detrimental to overall size. There needs to be a way to detect
5033 // that condition to know if this is truly a size win.
5034 const Function *F = DAG.getMachineFunction().getFunction();
5035 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5037 // Handle broadcasting a single constant scalar from the constant pool
5039 // On Sandybridge (no AVX2), it is still better to load a constant vector
5040 // from the constant pool and not to broadcast it from a scalar.
5041 // But override that restriction when optimizing for size.
5042 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5043 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5044 EVT CVT = Ld.getValueType();
5045 assert(!CVT.isVector() && "Must not broadcast a vector type");
5047 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5048 // For size optimization, also splat v2f64 and v2i64, and for size opt
5049 // with AVX2, also splat i8 and i16.
5050 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5051 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5052 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5053 const Constant *C = nullptr;
5054 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5055 C = CI->getConstantIntValue();
5056 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5057 C = CF->getConstantFPValue();
5059 assert(C && "Invalid constant type");
5061 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5062 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5063 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5064 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5065 MachinePointerInfo::getConstantPool(),
5066 false, false, false, Alignment);
5068 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5072 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5074 // Handle AVX2 in-register broadcasts.
5075 if (!IsLoad && Subtarget->hasInt256() &&
5076 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5077 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5079 // The scalar source must be a normal load.
5083 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5084 (Subtarget->hasVLX() && ScalarSize == 64))
5085 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5087 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5088 // double since there is no vbroadcastsd xmm
5089 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5090 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5091 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5094 // Unsupported broadcast.
5098 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5099 /// underlying vector and index.
5101 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5103 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5105 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5106 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5109 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5111 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5113 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5114 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5117 // In this case the vector is the extract_subvector expression and the index
5118 // is 2, as specified by the shuffle.
5119 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5120 SDValue ShuffleVec = SVOp->getOperand(0);
5121 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5122 assert(ShuffleVecVT.getVectorElementType() ==
5123 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5125 int ShuffleIdx = SVOp->getMaskElt(Idx);
5126 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5127 ExtractedFromVec = ShuffleVec;
5133 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5134 MVT VT = Op.getSimpleValueType();
5136 // Skip if insert_vec_elt is not supported.
5137 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5138 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5142 unsigned NumElems = Op.getNumOperands();
5146 SmallVector<unsigned, 4> InsertIndices;
5147 SmallVector<int, 8> Mask(NumElems, -1);
5149 for (unsigned i = 0; i != NumElems; ++i) {
5150 unsigned Opc = Op.getOperand(i).getOpcode();
5152 if (Opc == ISD::UNDEF)
5155 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5156 // Quit if more than 1 elements need inserting.
5157 if (InsertIndices.size() > 1)
5160 InsertIndices.push_back(i);
5164 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5165 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5166 // Quit if non-constant index.
5167 if (!isa<ConstantSDNode>(ExtIdx))
5169 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5171 // Quit if extracted from vector of different type.
5172 if (ExtractedFromVec.getValueType() != VT)
5175 if (!VecIn1.getNode())
5176 VecIn1 = ExtractedFromVec;
5177 else if (VecIn1 != ExtractedFromVec) {
5178 if (!VecIn2.getNode())
5179 VecIn2 = ExtractedFromVec;
5180 else if (VecIn2 != ExtractedFromVec)
5181 // Quit if more than 2 vectors to shuffle
5185 if (ExtractedFromVec == VecIn1)
5187 else if (ExtractedFromVec == VecIn2)
5188 Mask[i] = Idx + NumElems;
5191 if (!VecIn1.getNode())
5194 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5195 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5196 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5197 unsigned Idx = InsertIndices[i];
5198 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5199 DAG.getIntPtrConstant(Idx, DL));
5205 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5206 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5207 Op.getScalarValueSizeInBits() == 1 &&
5208 "Can not convert non-constant vector");
5209 uint64_t Immediate = 0;
5210 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5211 SDValue In = Op.getOperand(idx);
5212 if (In.getOpcode() != ISD::UNDEF)
5213 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5217 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5218 return DAG.getConstant(Immediate, dl, VT);
5220 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5222 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5224 MVT VT = Op.getSimpleValueType();
5225 assert((VT.getVectorElementType() == MVT::i1) &&
5226 "Unexpected type in LowerBUILD_VECTORvXi1!");
5229 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5230 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5231 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5232 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5235 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5236 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5237 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5238 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5241 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5242 SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5243 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5244 return DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5245 SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5246 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5247 DAG.getIntPtrConstant(0, dl));
5250 // Vector has one or more non-const elements
5251 uint64_t Immediate = 0;
5252 SmallVector<unsigned, 16> NonConstIdx;
5253 bool IsSplat = true;
5254 bool HasConstElts = false;
5256 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5257 SDValue In = Op.getOperand(idx);
5258 if (In.getOpcode() == ISD::UNDEF)
5260 if (!isa<ConstantSDNode>(In))
5261 NonConstIdx.push_back(idx);
5263 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5264 HasConstElts = true;
5268 else if (In != Op.getOperand(SplatIdx))
5272 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5274 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5275 DAG.getConstant(1, dl, VT),
5276 DAG.getConstant(0, dl, VT));
5278 // insert elements one by one
5282 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5283 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5285 else if (HasConstElts)
5286 Imm = DAG.getConstant(0, dl, VT);
5288 Imm = DAG.getUNDEF(VT);
5289 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5290 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5292 SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5293 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5294 DAG.getIntPtrConstant(0, dl));
5297 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5298 unsigned InsertIdx = NonConstIdx[i];
5299 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5300 Op.getOperand(InsertIdx),
5301 DAG.getIntPtrConstant(InsertIdx, dl));
5306 /// \brief Return true if \p N implements a horizontal binop and return the
5307 /// operands for the horizontal binop into V0 and V1.
5309 /// This is a helper function of LowerToHorizontalOp().
5310 /// This function checks that the build_vector \p N in input implements a
5311 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5312 /// operation to match.
5313 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5314 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5315 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5318 /// This function only analyzes elements of \p N whose indices are
5319 /// in range [BaseIdx, LastIdx).
5320 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5322 unsigned BaseIdx, unsigned LastIdx,
5323 SDValue &V0, SDValue &V1) {
5324 EVT VT = N->getValueType(0);
5326 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5327 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5328 "Invalid Vector in input!");
5330 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5331 bool CanFold = true;
5332 unsigned ExpectedVExtractIdx = BaseIdx;
5333 unsigned NumElts = LastIdx - BaseIdx;
5334 V0 = DAG.getUNDEF(VT);
5335 V1 = DAG.getUNDEF(VT);
5337 // Check if N implements a horizontal binop.
5338 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5339 SDValue Op = N->getOperand(i + BaseIdx);
5342 if (Op->getOpcode() == ISD::UNDEF) {
5343 // Update the expected vector extract index.
5344 if (i * 2 == NumElts)
5345 ExpectedVExtractIdx = BaseIdx;
5346 ExpectedVExtractIdx += 2;
5350 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5355 SDValue Op0 = Op.getOperand(0);
5356 SDValue Op1 = Op.getOperand(1);
5358 // Try to match the following pattern:
5359 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5360 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5361 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5362 Op0.getOperand(0) == Op1.getOperand(0) &&
5363 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5364 isa<ConstantSDNode>(Op1.getOperand(1)));
5368 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5369 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5371 if (i * 2 < NumElts) {
5372 if (V0.getOpcode() == ISD::UNDEF) {
5373 V0 = Op0.getOperand(0);
5374 if (V0.getValueType() != VT)
5378 if (V1.getOpcode() == ISD::UNDEF) {
5379 V1 = Op0.getOperand(0);
5380 if (V1.getValueType() != VT)
5383 if (i * 2 == NumElts)
5384 ExpectedVExtractIdx = BaseIdx;
5387 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5388 if (I0 == ExpectedVExtractIdx)
5389 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5390 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5391 // Try to match the following dag sequence:
5392 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5393 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5397 ExpectedVExtractIdx += 2;
5403 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5404 /// a concat_vector.
5406 /// This is a helper function of LowerToHorizontalOp().
5407 /// This function expects two 256-bit vectors called V0 and V1.
5408 /// At first, each vector is split into two separate 128-bit vectors.
5409 /// Then, the resulting 128-bit vectors are used to implement two
5410 /// horizontal binary operations.
5412 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5414 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5415 /// the two new horizontal binop.
5416 /// When Mode is set, the first horizontal binop dag node would take as input
5417 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5418 /// horizontal binop dag node would take as input the lower 128-bit of V1
5419 /// and the upper 128-bit of V1.
5421 /// HADD V0_LO, V0_HI
5422 /// HADD V1_LO, V1_HI
5424 /// Otherwise, the first horizontal binop dag node takes as input the lower
5425 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5426 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5428 /// HADD V0_LO, V1_LO
5429 /// HADD V0_HI, V1_HI
5431 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5432 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5433 /// the upper 128-bits of the result.
5434 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5435 SDLoc DL, SelectionDAG &DAG,
5436 unsigned X86Opcode, bool Mode,
5437 bool isUndefLO, bool isUndefHI) {
5438 EVT VT = V0.getValueType();
5439 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5440 "Invalid nodes in input!");
5442 unsigned NumElts = VT.getVectorNumElements();
5443 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5444 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5445 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5446 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5447 EVT NewVT = V0_LO.getValueType();
5449 SDValue LO = DAG.getUNDEF(NewVT);
5450 SDValue HI = DAG.getUNDEF(NewVT);
5453 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5454 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5455 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5456 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5457 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5459 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5460 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5461 V1_LO->getOpcode() != ISD::UNDEF))
5462 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5464 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5465 V1_HI->getOpcode() != ISD::UNDEF))
5466 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5469 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5472 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5474 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5475 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5476 EVT VT = BV->getValueType(0);
5477 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5478 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5482 unsigned NumElts = VT.getVectorNumElements();
5483 SDValue InVec0 = DAG.getUNDEF(VT);
5484 SDValue InVec1 = DAG.getUNDEF(VT);
5486 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5487 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5489 // Odd-numbered elements in the input build vector are obtained from
5490 // adding two integer/float elements.
5491 // Even-numbered elements in the input build vector are obtained from
5492 // subtracting two integer/float elements.
5493 unsigned ExpectedOpcode = ISD::FSUB;
5494 unsigned NextExpectedOpcode = ISD::FADD;
5495 bool AddFound = false;
5496 bool SubFound = false;
5498 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5499 SDValue Op = BV->getOperand(i);
5501 // Skip 'undef' values.
5502 unsigned Opcode = Op.getOpcode();
5503 if (Opcode == ISD::UNDEF) {
5504 std::swap(ExpectedOpcode, NextExpectedOpcode);
5508 // Early exit if we found an unexpected opcode.
5509 if (Opcode != ExpectedOpcode)
5512 SDValue Op0 = Op.getOperand(0);
5513 SDValue Op1 = Op.getOperand(1);
5515 // Try to match the following pattern:
5516 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5517 // Early exit if we cannot match that sequence.
5518 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5519 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5520 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5521 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5522 Op0.getOperand(1) != Op1.getOperand(1))
5525 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5529 // We found a valid add/sub node. Update the information accordingly.
5535 // Update InVec0 and InVec1.
5536 if (InVec0.getOpcode() == ISD::UNDEF) {
5537 InVec0 = Op0.getOperand(0);
5538 if (InVec0.getValueType() != VT)
5541 if (InVec1.getOpcode() == ISD::UNDEF) {
5542 InVec1 = Op1.getOperand(0);
5543 if (InVec1.getValueType() != VT)
5547 // Make sure that operands in input to each add/sub node always
5548 // come from a same pair of vectors.
5549 if (InVec0 != Op0.getOperand(0)) {
5550 if (ExpectedOpcode == ISD::FSUB)
5553 // FADD is commutable. Try to commute the operands
5554 // and then test again.
5555 std::swap(Op0, Op1);
5556 if (InVec0 != Op0.getOperand(0))
5560 if (InVec1 != Op1.getOperand(0))
5563 // Update the pair of expected opcodes.
5564 std::swap(ExpectedOpcode, NextExpectedOpcode);
5567 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5568 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5569 InVec1.getOpcode() != ISD::UNDEF)
5570 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5575 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5576 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5577 const X86Subtarget *Subtarget,
5578 SelectionDAG &DAG) {
5579 EVT VT = BV->getValueType(0);
5580 unsigned NumElts = VT.getVectorNumElements();
5581 unsigned NumUndefsLO = 0;
5582 unsigned NumUndefsHI = 0;
5583 unsigned Half = NumElts/2;
5585 // Count the number of UNDEF operands in the build_vector in input.
5586 for (unsigned i = 0, e = Half; i != e; ++i)
5587 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5590 for (unsigned i = Half, e = NumElts; i != e; ++i)
5591 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5594 // Early exit if this is either a build_vector of all UNDEFs or all the
5595 // operands but one are UNDEF.
5596 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5600 SDValue InVec0, InVec1;
5601 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5602 // Try to match an SSE3 float HADD/HSUB.
5603 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5604 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5606 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5607 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5608 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5609 // Try to match an SSSE3 integer HADD/HSUB.
5610 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5611 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5613 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5614 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5617 if (!Subtarget->hasAVX())
5620 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5621 // Try to match an AVX horizontal add/sub of packed single/double
5622 // precision floating point values from 256-bit vectors.
5623 SDValue InVec2, InVec3;
5624 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5625 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5626 ((InVec0.getOpcode() == ISD::UNDEF ||
5627 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5628 ((InVec1.getOpcode() == ISD::UNDEF ||
5629 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5630 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5632 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5633 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5634 ((InVec0.getOpcode() == ISD::UNDEF ||
5635 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5636 ((InVec1.getOpcode() == ISD::UNDEF ||
5637 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5638 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5639 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5640 // Try to match an AVX2 horizontal add/sub of signed integers.
5641 SDValue InVec2, InVec3;
5643 bool CanFold = true;
5645 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5646 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5647 ((InVec0.getOpcode() == ISD::UNDEF ||
5648 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5649 ((InVec1.getOpcode() == ISD::UNDEF ||
5650 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5651 X86Opcode = X86ISD::HADD;
5652 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5653 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5654 ((InVec0.getOpcode() == ISD::UNDEF ||
5655 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5656 ((InVec1.getOpcode() == ISD::UNDEF ||
5657 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5658 X86Opcode = X86ISD::HSUB;
5663 // Fold this build_vector into a single horizontal add/sub.
5664 // Do this only if the target has AVX2.
5665 if (Subtarget->hasAVX2())
5666 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5668 // Do not try to expand this build_vector into a pair of horizontal
5669 // add/sub if we can emit a pair of scalar add/sub.
5670 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5673 // Convert this build_vector into a pair of horizontal binop followed by
5675 bool isUndefLO = NumUndefsLO == Half;
5676 bool isUndefHI = NumUndefsHI == Half;
5677 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5678 isUndefLO, isUndefHI);
5682 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5683 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5685 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5686 X86Opcode = X86ISD::HADD;
5687 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5688 X86Opcode = X86ISD::HSUB;
5689 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5690 X86Opcode = X86ISD::FHADD;
5691 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5692 X86Opcode = X86ISD::FHSUB;
5696 // Don't try to expand this build_vector into a pair of horizontal add/sub
5697 // if we can simply emit a pair of scalar add/sub.
5698 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5701 // Convert this build_vector into two horizontal add/sub followed by
5703 bool isUndefLO = NumUndefsLO == Half;
5704 bool isUndefHI = NumUndefsHI == Half;
5705 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5706 isUndefLO, isUndefHI);
5713 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5716 MVT VT = Op.getSimpleValueType();
5717 MVT ExtVT = VT.getVectorElementType();
5718 unsigned NumElems = Op.getNumOperands();
5720 // Generate vectors for predicate vectors.
5721 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5722 return LowerBUILD_VECTORvXi1(Op, DAG);
5724 // Vectors containing all zeros can be matched by pxor and xorps later
5725 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5726 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5727 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5728 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5731 return getZeroVector(VT, Subtarget, DAG, dl);
5734 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5735 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5736 // vpcmpeqd on 256-bit vectors.
5737 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5738 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5741 if (!VT.is512BitVector())
5742 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5745 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5746 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5748 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5749 return HorizontalOp;
5750 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5753 unsigned EVTBits = ExtVT.getSizeInBits();
5755 unsigned NumZero = 0;
5756 unsigned NumNonZero = 0;
5757 unsigned NonZeros = 0;
5758 bool IsAllConstants = true;
5759 SmallSet<SDValue, 8> Values;
5760 for (unsigned i = 0; i < NumElems; ++i) {
5761 SDValue Elt = Op.getOperand(i);
5762 if (Elt.getOpcode() == ISD::UNDEF)
5765 if (Elt.getOpcode() != ISD::Constant &&
5766 Elt.getOpcode() != ISD::ConstantFP)
5767 IsAllConstants = false;
5768 if (X86::isZeroNode(Elt))
5771 NonZeros |= (1 << i);
5776 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5777 if (NumNonZero == 0)
5778 return DAG.getUNDEF(VT);
5780 // Special case for single non-zero, non-undef, element.
5781 if (NumNonZero == 1) {
5782 unsigned Idx = countTrailingZeros(NonZeros);
5783 SDValue Item = Op.getOperand(Idx);
5785 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5786 // the value are obviously zero, truncate the value to i32 and do the
5787 // insertion that way. Only do this if the value is non-constant or if the
5788 // value is a constant being inserted into element 0. It is cheaper to do
5789 // a constant pool load than it is to do a movd + shuffle.
5790 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5791 (!IsAllConstants || Idx == 0)) {
5792 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5794 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5795 EVT VecVT = MVT::v4i32;
5797 // Truncate the value (which may itself be a constant) to i32, and
5798 // convert it to a vector with movd (S2V+shuffle to zero extend).
5799 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5800 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5802 ISD::BITCAST, dl, VT,
5803 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5807 // If we have a constant or non-constant insertion into the low element of
5808 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5809 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5810 // depending on what the source datatype is.
5813 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5815 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5816 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5817 if (VT.is512BitVector()) {
5818 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5819 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5820 Item, DAG.getIntPtrConstant(0, dl));
5822 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5823 "Expected an SSE value type!");
5824 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5825 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5826 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5829 // We can't directly insert an i8 or i16 into a vector, so zero extend
5831 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5832 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5833 if (VT.is256BitVector()) {
5834 if (Subtarget->hasAVX()) {
5835 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5836 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5838 // Without AVX, we need to extend to a 128-bit vector and then
5839 // insert into the 256-bit vector.
5840 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5841 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5842 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5845 assert(VT.is128BitVector() && "Expected an SSE value type!");
5846 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5847 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5849 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5853 // Is it a vector logical left shift?
5854 if (NumElems == 2 && Idx == 1 &&
5855 X86::isZeroNode(Op.getOperand(0)) &&
5856 !X86::isZeroNode(Op.getOperand(1))) {
5857 unsigned NumBits = VT.getSizeInBits();
5858 return getVShift(true, VT,
5859 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5860 VT, Op.getOperand(1)),
5861 NumBits/2, DAG, *this, dl);
5864 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5867 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5868 // is a non-constant being inserted into an element other than the low one,
5869 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5870 // movd/movss) to move this into the low element, then shuffle it into
5872 if (EVTBits == 32) {
5873 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5874 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5878 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5879 if (Values.size() == 1) {
5880 if (EVTBits == 32) {
5881 // Instead of a shuffle like this:
5882 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5883 // Check if it's possible to issue this instead.
5884 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5885 unsigned Idx = countTrailingZeros(NonZeros);
5886 SDValue Item = Op.getOperand(Idx);
5887 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5888 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5893 // A vector full of immediates; various special cases are already
5894 // handled, so this is best done with a single constant-pool load.
5898 // For AVX-length vectors, see if we can use a vector load to get all of the
5899 // elements, otherwise build the individual 128-bit pieces and use
5900 // shuffles to put them in place.
5901 if (VT.is256BitVector() || VT.is512BitVector()) {
5902 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5904 // Check for a build vector of consecutive loads.
5905 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5908 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5910 // Build both the lower and upper subvector.
5911 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5912 makeArrayRef(&V[0], NumElems/2));
5913 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5914 makeArrayRef(&V[NumElems / 2], NumElems/2));
5916 // Recreate the wider vector with the lower and upper part.
5917 if (VT.is256BitVector())
5918 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5919 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5922 // Let legalizer expand 2-wide build_vectors.
5923 if (EVTBits == 64) {
5924 if (NumNonZero == 1) {
5925 // One half is zero or undef.
5926 unsigned Idx = countTrailingZeros(NonZeros);
5927 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5928 Op.getOperand(Idx));
5929 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5934 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5935 if (EVTBits == 8 && NumElems == 16)
5936 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5940 if (EVTBits == 16 && NumElems == 8)
5941 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5945 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5946 if (EVTBits == 32 && NumElems == 4)
5947 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5950 // If element VT is == 32 bits, turn it into a number of shuffles.
5951 SmallVector<SDValue, 8> V(NumElems);
5952 if (NumElems == 4 && NumZero > 0) {
5953 for (unsigned i = 0; i < 4; ++i) {
5954 bool isZero = !(NonZeros & (1 << i));
5956 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5958 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5961 for (unsigned i = 0; i < 2; ++i) {
5962 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5965 V[i] = V[i*2]; // Must be a zero vector.
5968 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5971 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5974 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5979 bool Reverse1 = (NonZeros & 0x3) == 2;
5980 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5984 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5985 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5987 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5990 if (Values.size() > 1 && VT.is128BitVector()) {
5991 // Check for a build vector of consecutive loads.
5992 for (unsigned i = 0; i < NumElems; ++i)
5993 V[i] = Op.getOperand(i);
5995 // Check for elements which are consecutive loads.
5996 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5999 // Check for a build vector from mostly shuffle plus few inserting.
6000 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6003 // For SSE 4.1, use insertps to put the high elements into the low element.
6004 if (Subtarget->hasSSE41()) {
6006 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6007 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6009 Result = DAG.getUNDEF(VT);
6011 for (unsigned i = 1; i < NumElems; ++i) {
6012 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6013 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6014 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6019 // Otherwise, expand into a number of unpckl*, start by extending each of
6020 // our (non-undef) elements to the full vector width with the element in the
6021 // bottom slot of the vector (which generates no code for SSE).
6022 for (unsigned i = 0; i < NumElems; ++i) {
6023 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6024 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6026 V[i] = DAG.getUNDEF(VT);
6029 // Next, we iteratively mix elements, e.g. for v4f32:
6030 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6031 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6032 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6033 unsigned EltStride = NumElems >> 1;
6034 while (EltStride != 0) {
6035 for (unsigned i = 0; i < EltStride; ++i) {
6036 // If V[i+EltStride] is undef and this is the first round of mixing,
6037 // then it is safe to just drop this shuffle: V[i] is already in the
6038 // right place, the one element (since it's the first round) being
6039 // inserted as undef can be dropped. This isn't safe for successive
6040 // rounds because they will permute elements within both vectors.
6041 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6042 EltStride == NumElems/2)
6045 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6054 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6055 // to create 256-bit vectors from two other 128-bit ones.
6056 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6058 MVT ResVT = Op.getSimpleValueType();
6060 assert((ResVT.is256BitVector() ||
6061 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6063 SDValue V1 = Op.getOperand(0);
6064 SDValue V2 = Op.getOperand(1);
6065 unsigned NumElems = ResVT.getVectorNumElements();
6066 if (ResVT.is256BitVector())
6067 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6069 if (Op.getNumOperands() == 4) {
6070 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6071 ResVT.getVectorNumElements()/2);
6072 SDValue V3 = Op.getOperand(2);
6073 SDValue V4 = Op.getOperand(3);
6074 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6075 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6077 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6080 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6081 const X86Subtarget *Subtarget,
6082 SelectionDAG & DAG) {
6084 MVT ResVT = Op.getSimpleValueType();
6085 unsigned NumOfOperands = Op.getNumOperands();
6087 assert(isPowerOf2_32(NumOfOperands) &&
6088 "Unexpected number of operands in CONCAT_VECTORS");
6090 if (NumOfOperands > 2) {
6091 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6092 ResVT.getVectorNumElements()/2);
6093 SmallVector<SDValue, 2> Ops;
6094 for (unsigned i = 0; i < NumOfOperands/2; i++)
6095 Ops.push_back(Op.getOperand(i));
6096 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6098 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6099 Ops.push_back(Op.getOperand(i));
6100 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6101 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6104 SDValue V1 = Op.getOperand(0);
6105 SDValue V2 = Op.getOperand(1);
6106 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6107 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6109 if (IsZeroV1 && IsZeroV2)
6110 return getZeroVector(ResVT, Subtarget, DAG, dl);
6112 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6113 SDValue Undef = DAG.getUNDEF(ResVT);
6114 unsigned NumElems = ResVT.getVectorNumElements();
6115 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6117 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6118 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6122 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6123 // Zero the upper bits of V1
6124 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6125 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6128 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6131 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6132 const X86Subtarget *Subtarget,
6133 SelectionDAG &DAG) {
6134 MVT VT = Op.getSimpleValueType();
6135 if (VT.getVectorElementType() == MVT::i1)
6136 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6138 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6139 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6140 Op.getNumOperands() == 4)));
6142 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6143 // from two other 128-bit ones.
6145 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6146 return LowerAVXCONCAT_VECTORS(Op, DAG);
6150 //===----------------------------------------------------------------------===//
6151 // Vector shuffle lowering
6153 // This is an experimental code path for lowering vector shuffles on x86. It is
6154 // designed to handle arbitrary vector shuffles and blends, gracefully
6155 // degrading performance as necessary. It works hard to recognize idiomatic
6156 // shuffles and lower them to optimal instruction patterns without leaving
6157 // a framework that allows reasonably efficient handling of all vector shuffle
6159 //===----------------------------------------------------------------------===//
6161 /// \brief Tiny helper function to identify a no-op mask.
6163 /// This is a somewhat boring predicate function. It checks whether the mask
6164 /// array input, which is assumed to be a single-input shuffle mask of the kind
6165 /// used by the X86 shuffle instructions (not a fully general
6166 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6167 /// in-place shuffle are 'no-op's.
6168 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6169 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6170 if (Mask[i] != -1 && Mask[i] != i)
6175 /// \brief Helper function to classify a mask as a single-input mask.
6177 /// This isn't a generic single-input test because in the vector shuffle
6178 /// lowering we canonicalize single inputs to be the first input operand. This
6179 /// means we can more quickly test for a single input by only checking whether
6180 /// an input from the second operand exists. We also assume that the size of
6181 /// mask corresponds to the size of the input vectors which isn't true in the
6182 /// fully general case.
6183 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6185 if (M >= (int)Mask.size())
6190 /// \brief Test whether there are elements crossing 128-bit lanes in this
6193 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6194 /// and we routinely test for these.
6195 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6196 int LaneSize = 128 / VT.getScalarSizeInBits();
6197 int Size = Mask.size();
6198 for (int i = 0; i < Size; ++i)
6199 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6204 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6206 /// This checks a shuffle mask to see if it is performing the same
6207 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6208 /// that it is also not lane-crossing. It may however involve a blend from the
6209 /// same lane of a second vector.
6211 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6212 /// non-trivial to compute in the face of undef lanes. The representation is
6213 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6214 /// entries from both V1 and V2 inputs to the wider mask.
6216 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6217 SmallVectorImpl<int> &RepeatedMask) {
6218 int LaneSize = 128 / VT.getScalarSizeInBits();
6219 RepeatedMask.resize(LaneSize, -1);
6220 int Size = Mask.size();
6221 for (int i = 0; i < Size; ++i) {
6224 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6225 // This entry crosses lanes, so there is no way to model this shuffle.
6228 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6229 if (RepeatedMask[i % LaneSize] == -1)
6230 // This is the first non-undef entry in this slot of a 128-bit lane.
6231 RepeatedMask[i % LaneSize] =
6232 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6233 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6234 // Found a mismatch with the repeated mask.
6240 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6243 /// This is a fast way to test a shuffle mask against a fixed pattern:
6245 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6247 /// It returns true if the mask is exactly as wide as the argument list, and
6248 /// each element of the mask is either -1 (signifying undef) or the value given
6249 /// in the argument.
6250 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6251 ArrayRef<int> ExpectedMask) {
6252 if (Mask.size() != ExpectedMask.size())
6255 int Size = Mask.size();
6257 // If the values are build vectors, we can look through them to find
6258 // equivalent inputs that make the shuffles equivalent.
6259 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6260 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6262 for (int i = 0; i < Size; ++i)
6263 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6264 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6265 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6266 if (!MaskBV || !ExpectedBV ||
6267 MaskBV->getOperand(Mask[i] % Size) !=
6268 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6275 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6277 /// This helper function produces an 8-bit shuffle immediate corresponding to
6278 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6279 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6282 /// NB: We rely heavily on "undef" masks preserving the input lane.
6283 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6284 SelectionDAG &DAG) {
6285 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6286 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6287 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6288 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6289 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6292 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6293 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6294 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6295 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6296 return DAG.getConstant(Imm, DL, MVT::i8);
6299 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6301 /// This is used as a fallback approach when first class blend instructions are
6302 /// unavailable. Currently it is only suitable for integer vectors, but could
6303 /// be generalized for floating point vectors if desirable.
6304 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6305 SDValue V2, ArrayRef<int> Mask,
6306 SelectionDAG &DAG) {
6307 assert(VT.isInteger() && "Only supports integer vector types!");
6308 MVT EltVT = VT.getScalarType();
6309 int NumEltBits = EltVT.getSizeInBits();
6310 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6311 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6313 SmallVector<SDValue, 16> MaskOps;
6314 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6315 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6316 return SDValue(); // Shuffled input!
6317 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6320 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6321 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6322 // We have to cast V2 around.
6323 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6324 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6325 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6326 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6327 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6328 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6331 /// \brief Try to emit a blend instruction for a shuffle.
6333 /// This doesn't do any checks for the availability of instructions for blending
6334 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6335 /// be matched in the backend with the type given. What it does check for is
6336 /// that the shuffle mask is in fact a blend.
6337 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6338 SDValue V2, ArrayRef<int> Mask,
6339 const X86Subtarget *Subtarget,
6340 SelectionDAG &DAG) {
6341 unsigned BlendMask = 0;
6342 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6343 if (Mask[i] >= Size) {
6344 if (Mask[i] != i + Size)
6345 return SDValue(); // Shuffled V2 input!
6346 BlendMask |= 1u << i;
6349 if (Mask[i] >= 0 && Mask[i] != i)
6350 return SDValue(); // Shuffled V1 input!
6352 switch (VT.SimpleTy) {
6357 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6358 DAG.getConstant(BlendMask, DL, MVT::i8));
6362 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6366 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6367 // that instruction.
6368 if (Subtarget->hasAVX2()) {
6369 // Scale the blend by the number of 32-bit dwords per element.
6370 int Scale = VT.getScalarSizeInBits() / 32;
6372 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6373 if (Mask[i] >= Size)
6374 for (int j = 0; j < Scale; ++j)
6375 BlendMask |= 1u << (i * Scale + j);
6377 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6378 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6379 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6380 return DAG.getNode(ISD::BITCAST, DL, VT,
6381 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6382 DAG.getConstant(BlendMask, DL, MVT::i8)));
6386 // For integer shuffles we need to expand the mask and cast the inputs to
6387 // v8i16s prior to blending.
6388 int Scale = 8 / VT.getVectorNumElements();
6390 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6391 if (Mask[i] >= Size)
6392 for (int j = 0; j < Scale; ++j)
6393 BlendMask |= 1u << (i * Scale + j);
6395 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6396 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6397 return DAG.getNode(ISD::BITCAST, DL, VT,
6398 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6399 DAG.getConstant(BlendMask, DL, MVT::i8)));
6403 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6404 SmallVector<int, 8> RepeatedMask;
6405 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6406 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6407 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6409 for (int i = 0; i < 8; ++i)
6410 if (RepeatedMask[i] >= 16)
6411 BlendMask |= 1u << i;
6412 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6413 DAG.getConstant(BlendMask, DL, MVT::i8));
6419 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6420 "256-bit byte-blends require AVX2 support!");
6422 // Scale the blend by the number of bytes per element.
6423 int Scale = VT.getScalarSizeInBits() / 8;
6425 // This form of blend is always done on bytes. Compute the byte vector
6427 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6429 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6430 // mix of LLVM's code generator and the x86 backend. We tell the code
6431 // generator that boolean values in the elements of an x86 vector register
6432 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6433 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6434 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6435 // of the element (the remaining are ignored) and 0 in that high bit would
6436 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6437 // the LLVM model for boolean values in vector elements gets the relevant
6438 // bit set, it is set backwards and over constrained relative to x86's
6440 SmallVector<SDValue, 32> VSELECTMask;
6441 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6442 for (int j = 0; j < Scale; ++j)
6443 VSELECTMask.push_back(
6444 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6445 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6448 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6449 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6451 ISD::BITCAST, DL, VT,
6452 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6453 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6458 llvm_unreachable("Not a supported integer vector type!");
6462 /// \brief Try to lower as a blend of elements from two inputs followed by
6463 /// a single-input permutation.
6465 /// This matches the pattern where we can blend elements from two inputs and
6466 /// then reduce the shuffle to a single-input permutation.
6467 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6470 SelectionDAG &DAG) {
6471 // We build up the blend mask while checking whether a blend is a viable way
6472 // to reduce the shuffle.
6473 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6474 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6476 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6480 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6482 if (BlendMask[Mask[i] % Size] == -1)
6483 BlendMask[Mask[i] % Size] = Mask[i];
6484 else if (BlendMask[Mask[i] % Size] != Mask[i])
6485 return SDValue(); // Can't blend in the needed input!
6487 PermuteMask[i] = Mask[i] % Size;
6490 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6491 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6494 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6495 /// blends and permutes.
6497 /// This matches the extremely common pattern for handling combined
6498 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6499 /// operations. It will try to pick the best arrangement of shuffles and
6501 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6505 SelectionDAG &DAG) {
6506 // Shuffle the input elements into the desired positions in V1 and V2 and
6507 // blend them together.
6508 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6509 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6510 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6511 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6512 if (Mask[i] >= 0 && Mask[i] < Size) {
6513 V1Mask[i] = Mask[i];
6515 } else if (Mask[i] >= Size) {
6516 V2Mask[i] = Mask[i] - Size;
6517 BlendMask[i] = i + Size;
6520 // Try to lower with the simpler initial blend strategy unless one of the
6521 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6522 // shuffle may be able to fold with a load or other benefit. However, when
6523 // we'll have to do 2x as many shuffles in order to achieve this, blending
6524 // first is a better strategy.
6525 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6526 if (SDValue BlendPerm =
6527 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6530 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6531 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6532 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6535 /// \brief Try to lower a vector shuffle as a byte rotation.
6537 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6538 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6539 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6540 /// try to generically lower a vector shuffle through such an pattern. It
6541 /// does not check for the profitability of lowering either as PALIGNR or
6542 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6543 /// This matches shuffle vectors that look like:
6545 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6547 /// Essentially it concatenates V1 and V2, shifts right by some number of
6548 /// elements, and takes the low elements as the result. Note that while this is
6549 /// specified as a *right shift* because x86 is little-endian, it is a *left
6550 /// rotate* of the vector lanes.
6551 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6554 const X86Subtarget *Subtarget,
6555 SelectionDAG &DAG) {
6556 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6558 int NumElts = Mask.size();
6559 int NumLanes = VT.getSizeInBits() / 128;
6560 int NumLaneElts = NumElts / NumLanes;
6562 // We need to detect various ways of spelling a rotation:
6563 // [11, 12, 13, 14, 15, 0, 1, 2]
6564 // [-1, 12, 13, 14, -1, -1, 1, -1]
6565 // [-1, -1, -1, -1, -1, -1, 1, 2]
6566 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6567 // [-1, 4, 5, 6, -1, -1, 9, -1]
6568 // [-1, 4, 5, 6, -1, -1, -1, -1]
6571 for (int l = 0; l < NumElts; l += NumLaneElts) {
6572 for (int i = 0; i < NumLaneElts; ++i) {
6573 if (Mask[l + i] == -1)
6575 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6577 // Get the mod-Size index and lane correct it.
6578 int LaneIdx = (Mask[l + i] % NumElts) - l;
6579 // Make sure it was in this lane.
6580 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6583 // Determine where a rotated vector would have started.
6584 int StartIdx = i - LaneIdx;
6586 // The identity rotation isn't interesting, stop.
6589 // If we found the tail of a vector the rotation must be the missing
6590 // front. If we found the head of a vector, it must be how much of the
6592 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6595 Rotation = CandidateRotation;
6596 else if (Rotation != CandidateRotation)
6597 // The rotations don't match, so we can't match this mask.
6600 // Compute which value this mask is pointing at.
6601 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6603 // Compute which of the two target values this index should be assigned
6604 // to. This reflects whether the high elements are remaining or the low
6605 // elements are remaining.
6606 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6608 // Either set up this value if we've not encountered it before, or check
6609 // that it remains consistent.
6612 else if (TargetV != MaskV)
6613 // This may be a rotation, but it pulls from the inputs in some
6614 // unsupported interleaving.
6619 // Check that we successfully analyzed the mask, and normalize the results.
6620 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6621 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6627 // The actual rotate instruction rotates bytes, so we need to scale the
6628 // rotation based on how many bytes are in the vector lane.
6629 int Scale = 16 / NumLaneElts;
6631 // SSSE3 targets can use the palignr instruction.
6632 if (Subtarget->hasSSSE3()) {
6633 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6634 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6635 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6636 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6638 return DAG.getNode(ISD::BITCAST, DL, VT,
6639 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6640 DAG.getConstant(Rotation * Scale, DL,
6644 assert(VT.getSizeInBits() == 128 &&
6645 "Rotate-based lowering only supports 128-bit lowering!");
6646 assert(Mask.size() <= 16 &&
6647 "Can shuffle at most 16 bytes in a 128-bit vector!");
6649 // Default SSE2 implementation
6650 int LoByteShift = 16 - Rotation * Scale;
6651 int HiByteShift = Rotation * Scale;
6653 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6654 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6655 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6657 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6658 DAG.getConstant(LoByteShift, DL, MVT::i8));
6659 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6660 DAG.getConstant(HiByteShift, DL, MVT::i8));
6661 return DAG.getNode(ISD::BITCAST, DL, VT,
6662 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6665 /// \brief Compute whether each element of a shuffle is zeroable.
6667 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6668 /// Either it is an undef element in the shuffle mask, the element of the input
6669 /// referenced is undef, or the element of the input referenced is known to be
6670 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6671 /// as many lanes with this technique as possible to simplify the remaining
6673 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6674 SDValue V1, SDValue V2) {
6675 SmallBitVector Zeroable(Mask.size(), false);
6677 while (V1.getOpcode() == ISD::BITCAST)
6678 V1 = V1->getOperand(0);
6679 while (V2.getOpcode() == ISD::BITCAST)
6680 V2 = V2->getOperand(0);
6682 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6683 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6685 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6687 // Handle the easy cases.
6688 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6693 // If this is an index into a build_vector node (which has the same number
6694 // of elements), dig out the input value and use it.
6695 SDValue V = M < Size ? V1 : V2;
6696 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6699 SDValue Input = V.getOperand(M % Size);
6700 // The UNDEF opcode check really should be dead code here, but not quite
6701 // worth asserting on (it isn't invalid, just unexpected).
6702 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6709 /// \brief Try to emit a bitmask instruction for a shuffle.
6711 /// This handles cases where we can model a blend exactly as a bitmask due to
6712 /// one of the inputs being zeroable.
6713 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6714 SDValue V2, ArrayRef<int> Mask,
6715 SelectionDAG &DAG) {
6716 MVT EltVT = VT.getScalarType();
6717 int NumEltBits = EltVT.getSizeInBits();
6718 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6719 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6720 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6722 if (EltVT.isFloatingPoint()) {
6723 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6724 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6726 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6727 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6729 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6732 if (Mask[i] % Size != i)
6733 return SDValue(); // Not a blend.
6735 V = Mask[i] < Size ? V1 : V2;
6736 else if (V != (Mask[i] < Size ? V1 : V2))
6737 return SDValue(); // Can only let one input through the mask.
6739 VMaskOps[i] = AllOnes;
6742 return SDValue(); // No non-zeroable elements!
6744 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6745 V = DAG.getNode(VT.isFloatingPoint()
6746 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6751 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6753 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6754 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6755 /// matches elements from one of the input vectors shuffled to the left or
6756 /// right with zeroable elements 'shifted in'. It handles both the strictly
6757 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6760 /// PSHL : (little-endian) left bit shift.
6761 /// [ zz, 0, zz, 2 ]
6762 /// [ -1, 4, zz, -1 ]
6763 /// PSRL : (little-endian) right bit shift.
6765 /// [ -1, -1, 7, zz]
6766 /// PSLLDQ : (little-endian) left byte shift
6767 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6768 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6769 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6770 /// PSRLDQ : (little-endian) right byte shift
6771 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6772 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6773 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6774 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6775 SDValue V2, ArrayRef<int> Mask,
6776 SelectionDAG &DAG) {
6777 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6779 int Size = Mask.size();
6780 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6782 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6783 for (int i = 0; i < Size; i += Scale)
6784 for (int j = 0; j < Shift; ++j)
6785 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6791 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6792 for (int i = 0; i != Size; i += Scale) {
6793 unsigned Pos = Left ? i + Shift : i;
6794 unsigned Low = Left ? i : i + Shift;
6795 unsigned Len = Scale - Shift;
6796 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6797 Low + (V == V1 ? 0 : Size)))
6801 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6802 bool ByteShift = ShiftEltBits > 64;
6803 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6804 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6805 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6807 // Normalize the scale for byte shifts to still produce an i64 element
6809 Scale = ByteShift ? Scale / 2 : Scale;
6811 // We need to round trip through the appropriate type for the shift.
6812 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6813 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6814 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6815 "Illegal integer vector type");
6816 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6818 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6819 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6820 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6823 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6824 // keep doubling the size of the integer elements up to that. We can
6825 // then shift the elements of the integer vector by whole multiples of
6826 // their width within the elements of the larger integer vector. Test each
6827 // multiple to see if we can find a match with the moved element indices
6828 // and that the shifted in elements are all zeroable.
6829 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6830 for (int Shift = 1; Shift != Scale; ++Shift)
6831 for (bool Left : {true, false})
6832 if (CheckZeros(Shift, Scale, Left))
6833 for (SDValue V : {V1, V2})
6834 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6841 /// \brief Lower a vector shuffle as a zero or any extension.
6843 /// Given a specific number of elements, element bit width, and extension
6844 /// stride, produce either a zero or any extension based on the available
6845 /// features of the subtarget.
6846 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6847 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6848 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6849 assert(Scale > 1 && "Need a scale to extend.");
6850 int NumElements = VT.getVectorNumElements();
6851 int EltBits = VT.getScalarSizeInBits();
6852 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6853 "Only 8, 16, and 32 bit elements can be extended.");
6854 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6856 // Found a valid zext mask! Try various lowering strategies based on the
6857 // input type and available ISA extensions.
6858 if (Subtarget->hasSSE41()) {
6859 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6860 NumElements / Scale);
6861 return DAG.getNode(ISD::BITCAST, DL, VT,
6862 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6865 // For any extends we can cheat for larger element sizes and use shuffle
6866 // instructions that can fold with a load and/or copy.
6867 if (AnyExt && EltBits == 32) {
6868 int PSHUFDMask[4] = {0, -1, 1, -1};
6870 ISD::BITCAST, DL, VT,
6871 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6872 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6873 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6875 if (AnyExt && EltBits == 16 && Scale > 2) {
6876 int PSHUFDMask[4] = {0, -1, 0, -1};
6877 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6878 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6879 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6880 int PSHUFHWMask[4] = {1, -1, -1, -1};
6882 ISD::BITCAST, DL, VT,
6883 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6884 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6885 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6888 // If this would require more than 2 unpack instructions to expand, use
6889 // pshufb when available. We can only use more than 2 unpack instructions
6890 // when zero extending i8 elements which also makes it easier to use pshufb.
6891 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6892 assert(NumElements == 16 && "Unexpected byte vector width!");
6893 SDValue PSHUFBMask[16];
6894 for (int i = 0; i < 16; ++i)
6896 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6897 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6898 return DAG.getNode(ISD::BITCAST, DL, VT,
6899 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6900 DAG.getNode(ISD::BUILD_VECTOR, DL,
6901 MVT::v16i8, PSHUFBMask)));
6904 // Otherwise emit a sequence of unpacks.
6906 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6907 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6908 : getZeroVector(InputVT, Subtarget, DAG, DL);
6909 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6910 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6914 } while (Scale > 1);
6915 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6918 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6920 /// This routine will try to do everything in its power to cleverly lower
6921 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6922 /// check for the profitability of this lowering, it tries to aggressively
6923 /// match this pattern. It will use all of the micro-architectural details it
6924 /// can to emit an efficient lowering. It handles both blends with all-zero
6925 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6926 /// masking out later).
6928 /// The reason we have dedicated lowering for zext-style shuffles is that they
6929 /// are both incredibly common and often quite performance sensitive.
6930 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6931 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6932 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6933 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6935 int Bits = VT.getSizeInBits();
6936 int NumElements = VT.getVectorNumElements();
6937 assert(VT.getScalarSizeInBits() <= 32 &&
6938 "Exceeds 32-bit integer zero extension limit");
6939 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6941 // Define a helper function to check a particular ext-scale and lower to it if
6943 auto Lower = [&](int Scale) -> SDValue {
6946 for (int i = 0; i < NumElements; ++i) {
6948 continue; // Valid anywhere but doesn't tell us anything.
6949 if (i % Scale != 0) {
6950 // Each of the extended elements need to be zeroable.
6954 // We no longer are in the anyext case.
6959 // Each of the base elements needs to be consecutive indices into the
6960 // same input vector.
6961 SDValue V = Mask[i] < NumElements ? V1 : V2;
6964 else if (InputV != V)
6965 return SDValue(); // Flip-flopping inputs.
6967 if (Mask[i] % NumElements != i / Scale)
6968 return SDValue(); // Non-consecutive strided elements.
6971 // If we fail to find an input, we have a zero-shuffle which should always
6972 // have already been handled.
6973 // FIXME: Maybe handle this here in case during blending we end up with one?
6977 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6978 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6981 // The widest scale possible for extending is to a 64-bit integer.
6982 assert(Bits % 64 == 0 &&
6983 "The number of bits in a vector must be divisible by 64 on x86!");
6984 int NumExtElements = Bits / 64;
6986 // Each iteration, try extending the elements half as much, but into twice as
6988 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6989 assert(NumElements % NumExtElements == 0 &&
6990 "The input vector size must be divisible by the extended size.");
6991 if (SDValue V = Lower(NumElements / NumExtElements))
6995 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6999 // Returns one of the source operands if the shuffle can be reduced to a
7000 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7001 auto CanZExtLowHalf = [&]() {
7002 for (int i = NumElements / 2; i != NumElements; ++i)
7005 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7007 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7012 if (SDValue V = CanZExtLowHalf()) {
7013 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
7014 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7015 return DAG.getNode(ISD::BITCAST, DL, VT, V);
7018 // No viable ext lowering found.
7022 /// \brief Try to get a scalar value for a specific element of a vector.
7024 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7025 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7026 SelectionDAG &DAG) {
7027 MVT VT = V.getSimpleValueType();
7028 MVT EltVT = VT.getVectorElementType();
7029 while (V.getOpcode() == ISD::BITCAST)
7030 V = V.getOperand(0);
7031 // If the bitcasts shift the element size, we can't extract an equivalent
7033 MVT NewVT = V.getSimpleValueType();
7034 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7037 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7038 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7039 // Ensure the scalar operand is the same size as the destination.
7040 // FIXME: Add support for scalar truncation where possible.
7041 SDValue S = V.getOperand(Idx);
7042 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7043 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7049 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7051 /// This is particularly important because the set of instructions varies
7052 /// significantly based on whether the operand is a load or not.
7053 static bool isShuffleFoldableLoad(SDValue V) {
7054 while (V.getOpcode() == ISD::BITCAST)
7055 V = V.getOperand(0);
7057 return ISD::isNON_EXTLoad(V.getNode());
7060 /// \brief Try to lower insertion of a single element into a zero vector.
7062 /// This is a common pattern that we have especially efficient patterns to lower
7063 /// across all subtarget feature sets.
7064 static SDValue lowerVectorShuffleAsElementInsertion(
7065 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7066 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7067 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7069 MVT EltVT = VT.getVectorElementType();
7071 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7072 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7074 bool IsV1Zeroable = true;
7075 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7076 if (i != V2Index && !Zeroable[i]) {
7077 IsV1Zeroable = false;
7081 // Check for a single input from a SCALAR_TO_VECTOR node.
7082 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7083 // all the smarts here sunk into that routine. However, the current
7084 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7085 // vector shuffle lowering is dead.
7086 if (SDValue V2S = getScalarValueForVectorElement(
7087 V2, Mask[V2Index] - Mask.size(), DAG)) {
7088 // We need to zext the scalar if it is smaller than an i32.
7089 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7090 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7091 // Using zext to expand a narrow element won't work for non-zero
7096 // Zero-extend directly to i32.
7098 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7100 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7101 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7102 EltVT == MVT::i16) {
7103 // Either not inserting from the low element of the input or the input
7104 // element size is too small to use VZEXT_MOVL to clear the high bits.
7108 if (!IsV1Zeroable) {
7109 // If V1 can't be treated as a zero vector we have fewer options to lower
7110 // this. We can't support integer vectors or non-zero targets cheaply, and
7111 // the V1 elements can't be permuted in any way.
7112 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7113 if (!VT.isFloatingPoint() || V2Index != 0)
7115 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7116 V1Mask[V2Index] = -1;
7117 if (!isNoopShuffleMask(V1Mask))
7119 // This is essentially a special case blend operation, but if we have
7120 // general purpose blend operations, they are always faster. Bail and let
7121 // the rest of the lowering handle these as blends.
7122 if (Subtarget->hasSSE41())
7125 // Otherwise, use MOVSD or MOVSS.
7126 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7127 "Only two types of floating point element types to handle!");
7128 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7132 // This lowering only works for the low element with floating point vectors.
7133 if (VT.isFloatingPoint() && V2Index != 0)
7136 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7138 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7141 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7142 // the desired position. Otherwise it is more efficient to do a vector
7143 // shift left. We know that we can do a vector shift left because all
7144 // the inputs are zero.
7145 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7146 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7147 V2Shuffle[V2Index] = 0;
7148 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7150 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7152 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7154 V2Index * EltVT.getSizeInBits()/8, DL,
7155 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7156 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7162 /// \brief Try to lower broadcast of a single element.
7164 /// For convenience, this code also bundles all of the subtarget feature set
7165 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7166 /// a convenient way to factor it out.
7167 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7169 const X86Subtarget *Subtarget,
7170 SelectionDAG &DAG) {
7171 if (!Subtarget->hasAVX())
7173 if (VT.isInteger() && !Subtarget->hasAVX2())
7176 // Check that the mask is a broadcast.
7177 int BroadcastIdx = -1;
7179 if (M >= 0 && BroadcastIdx == -1)
7181 else if (M >= 0 && M != BroadcastIdx)
7184 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7185 "a sorted mask where the broadcast "
7188 // Go up the chain of (vector) values to find a scalar load that we can
7189 // combine with the broadcast.
7191 switch (V.getOpcode()) {
7192 case ISD::CONCAT_VECTORS: {
7193 int OperandSize = Mask.size() / V.getNumOperands();
7194 V = V.getOperand(BroadcastIdx / OperandSize);
7195 BroadcastIdx %= OperandSize;
7199 case ISD::INSERT_SUBVECTOR: {
7200 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7201 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7205 int BeginIdx = (int)ConstantIdx->getZExtValue();
7207 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7208 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7209 BroadcastIdx -= BeginIdx;
7220 // Check if this is a broadcast of a scalar. We special case lowering
7221 // for scalars so that we can more effectively fold with loads.
7222 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7223 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7224 V = V.getOperand(BroadcastIdx);
7226 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7227 // Only AVX2 has register broadcasts.
7228 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7230 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7231 // We can't broadcast from a vector register without AVX2, and we can only
7232 // broadcast from the zero-element of a vector register.
7236 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7239 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7240 // INSERTPS when the V1 elements are already in the correct locations
7241 // because otherwise we can just always use two SHUFPS instructions which
7242 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7243 // perform INSERTPS if a single V1 element is out of place and all V2
7244 // elements are zeroable.
7245 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7247 SelectionDAG &DAG) {
7248 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7249 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7250 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7251 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7253 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7256 int V1DstIndex = -1;
7257 int V2DstIndex = -1;
7258 bool V1UsedInPlace = false;
7260 for (int i = 0; i < 4; ++i) {
7261 // Synthesize a zero mask from the zeroable elements (includes undefs).
7267 // Flag if we use any V1 inputs in place.
7269 V1UsedInPlace = true;
7273 // We can only insert a single non-zeroable element.
7274 if (V1DstIndex != -1 || V2DstIndex != -1)
7278 // V1 input out of place for insertion.
7281 // V2 input for insertion.
7286 // Don't bother if we have no (non-zeroable) element for insertion.
7287 if (V1DstIndex == -1 && V2DstIndex == -1)
7290 // Determine element insertion src/dst indices. The src index is from the
7291 // start of the inserted vector, not the start of the concatenated vector.
7292 unsigned V2SrcIndex = 0;
7293 if (V1DstIndex != -1) {
7294 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7295 // and don't use the original V2 at all.
7296 V2SrcIndex = Mask[V1DstIndex];
7297 V2DstIndex = V1DstIndex;
7300 V2SrcIndex = Mask[V2DstIndex] - 4;
7303 // If no V1 inputs are used in place, then the result is created only from
7304 // the zero mask and the V2 insertion - so remove V1 dependency.
7306 V1 = DAG.getUNDEF(MVT::v4f32);
7308 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7309 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7311 // Insert the V2 element into the desired position.
7313 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7314 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7317 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7318 /// UNPCK instruction.
7320 /// This specifically targets cases where we end up with alternating between
7321 /// the two inputs, and so can permute them into something that feeds a single
7322 /// UNPCK instruction. Note that this routine only targets integer vectors
7323 /// because for floating point vectors we have a generalized SHUFPS lowering
7324 /// strategy that handles everything that doesn't *exactly* match an unpack,
7325 /// making this clever lowering unnecessary.
7326 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7327 SDValue V2, ArrayRef<int> Mask,
7328 SelectionDAG &DAG) {
7329 assert(!VT.isFloatingPoint() &&
7330 "This routine only supports integer vectors.");
7331 assert(!isSingleInputShuffleMask(Mask) &&
7332 "This routine should only be used when blending two inputs.");
7333 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7335 int Size = Mask.size();
7337 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7338 return M >= 0 && M % Size < Size / 2;
7340 int NumHiInputs = std::count_if(
7341 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7343 bool UnpackLo = NumLoInputs >= NumHiInputs;
7345 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7346 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7347 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7349 for (int i = 0; i < Size; ++i) {
7353 // Each element of the unpack contains Scale elements from this mask.
7354 int UnpackIdx = i / Scale;
7356 // We only handle the case where V1 feeds the first slots of the unpack.
7357 // We rely on canonicalization to ensure this is the case.
7358 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7361 // Setup the mask for this input. The indexing is tricky as we have to
7362 // handle the unpack stride.
7363 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7364 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7368 // If we will have to shuffle both inputs to use the unpack, check whether
7369 // we can just unpack first and shuffle the result. If so, skip this unpack.
7370 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7371 !isNoopShuffleMask(V2Mask))
7374 // Shuffle the inputs into place.
7375 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7376 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7378 // Cast the inputs to the type we will use to unpack them.
7379 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7380 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7382 // Unpack the inputs and cast the result back to the desired type.
7383 return DAG.getNode(ISD::BITCAST, DL, VT,
7384 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7385 DL, UnpackVT, V1, V2));
7388 // We try each unpack from the largest to the smallest to try and find one
7389 // that fits this mask.
7390 int OrigNumElements = VT.getVectorNumElements();
7391 int OrigScalarSize = VT.getScalarSizeInBits();
7392 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7393 int Scale = ScalarSize / OrigScalarSize;
7394 int NumElements = OrigNumElements / Scale;
7395 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7396 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7400 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7402 if (NumLoInputs == 0 || NumHiInputs == 0) {
7403 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7404 "We have to have *some* inputs!");
7405 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7407 // FIXME: We could consider the total complexity of the permute of each
7408 // possible unpacking. Or at the least we should consider how many
7409 // half-crossings are created.
7410 // FIXME: We could consider commuting the unpacks.
7412 SmallVector<int, 32> PermMask;
7413 PermMask.assign(Size, -1);
7414 for (int i = 0; i < Size; ++i) {
7418 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7421 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7423 return DAG.getVectorShuffle(
7424 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7426 DAG.getUNDEF(VT), PermMask);
7432 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7434 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7435 /// support for floating point shuffles but not integer shuffles. These
7436 /// instructions will incur a domain crossing penalty on some chips though so
7437 /// it is better to avoid lowering through this for integer vectors where
7439 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7440 const X86Subtarget *Subtarget,
7441 SelectionDAG &DAG) {
7443 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7444 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7445 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7446 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7447 ArrayRef<int> Mask = SVOp->getMask();
7448 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7450 if (isSingleInputShuffleMask(Mask)) {
7451 // Use low duplicate instructions for masks that match their pattern.
7452 if (Subtarget->hasSSE3())
7453 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7454 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7456 // Straight shuffle of a single input vector. Simulate this by using the
7457 // single input as both of the "inputs" to this instruction..
7458 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7460 if (Subtarget->hasAVX()) {
7461 // If we have AVX, we can use VPERMILPS which will allow folding a load
7462 // into the shuffle.
7463 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7464 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7467 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7468 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7470 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7471 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7473 // If we have a single input, insert that into V1 if we can do so cheaply.
7474 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7475 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7476 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7478 // Try inverting the insertion since for v2 masks it is easy to do and we
7479 // can't reliably sort the mask one way or the other.
7480 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7481 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7482 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7483 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7487 // Try to use one of the special instruction patterns to handle two common
7488 // blend patterns if a zero-blend above didn't work.
7489 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7490 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7491 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7492 // We can either use a special instruction to load over the low double or
7493 // to move just the low double.
7495 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7497 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7499 if (Subtarget->hasSSE41())
7500 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7504 // Use dedicated unpack instructions for masks that match their pattern.
7505 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7506 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7507 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7508 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7510 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7511 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7512 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7515 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7517 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7518 /// the integer unit to minimize domain crossing penalties. However, for blends
7519 /// it falls back to the floating point shuffle operation with appropriate bit
7521 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7522 const X86Subtarget *Subtarget,
7523 SelectionDAG &DAG) {
7525 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7526 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7527 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7528 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7529 ArrayRef<int> Mask = SVOp->getMask();
7530 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7532 if (isSingleInputShuffleMask(Mask)) {
7533 // Check for being able to broadcast a single element.
7534 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7535 Mask, Subtarget, DAG))
7538 // Straight shuffle of a single input vector. For everything from SSE2
7539 // onward this has a single fast instruction with no scary immediates.
7540 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7541 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7542 int WidenedMask[4] = {
7543 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7544 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7546 ISD::BITCAST, DL, MVT::v2i64,
7547 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7548 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7550 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7551 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7552 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7553 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7555 // If we have a blend of two PACKUS operations an the blend aligns with the
7556 // low and half halves, we can just merge the PACKUS operations. This is
7557 // particularly important as it lets us merge shuffles that this routine itself
7559 auto GetPackNode = [](SDValue V) {
7560 while (V.getOpcode() == ISD::BITCAST)
7561 V = V.getOperand(0);
7563 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7565 if (SDValue V1Pack = GetPackNode(V1))
7566 if (SDValue V2Pack = GetPackNode(V2))
7567 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7568 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7569 Mask[0] == 0 ? V1Pack.getOperand(0)
7570 : V1Pack.getOperand(1),
7571 Mask[1] == 2 ? V2Pack.getOperand(0)
7572 : V2Pack.getOperand(1)));
7574 // Try to use shift instructions.
7576 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7579 // When loading a scalar and then shuffling it into a vector we can often do
7580 // the insertion cheaply.
7581 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7582 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7584 // Try inverting the insertion since for v2 masks it is easy to do and we
7585 // can't reliably sort the mask one way or the other.
7586 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7587 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7588 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7591 // We have different paths for blend lowering, but they all must use the
7592 // *exact* same predicate.
7593 bool IsBlendSupported = Subtarget->hasSSE41();
7594 if (IsBlendSupported)
7595 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7599 // Use dedicated unpack instructions for masks that match their pattern.
7600 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7601 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7602 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7603 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7605 // Try to use byte rotation instructions.
7606 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7607 if (Subtarget->hasSSSE3())
7608 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7609 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7612 // If we have direct support for blends, we should lower by decomposing into
7613 // a permute. That will be faster than the domain cross.
7614 if (IsBlendSupported)
7615 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7618 // We implement this with SHUFPD which is pretty lame because it will likely
7619 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7620 // However, all the alternatives are still more cycles and newer chips don't
7621 // have this problem. It would be really nice if x86 had better shuffles here.
7622 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7623 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7624 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7625 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7628 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7630 /// This is used to disable more specialized lowerings when the shufps lowering
7631 /// will happen to be efficient.
7632 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7633 // This routine only handles 128-bit shufps.
7634 assert(Mask.size() == 4 && "Unsupported mask size!");
7636 // To lower with a single SHUFPS we need to have the low half and high half
7637 // each requiring a single input.
7638 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7640 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7646 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7648 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7649 /// It makes no assumptions about whether this is the *best* lowering, it simply
7651 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7652 ArrayRef<int> Mask, SDValue V1,
7653 SDValue V2, SelectionDAG &DAG) {
7654 SDValue LowV = V1, HighV = V2;
7655 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7658 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7660 if (NumV2Elements == 1) {
7662 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7665 // Compute the index adjacent to V2Index and in the same half by toggling
7667 int V2AdjIndex = V2Index ^ 1;
7669 if (Mask[V2AdjIndex] == -1) {
7670 // Handles all the cases where we have a single V2 element and an undef.
7671 // This will only ever happen in the high lanes because we commute the
7672 // vector otherwise.
7674 std::swap(LowV, HighV);
7675 NewMask[V2Index] -= 4;
7677 // Handle the case where the V2 element ends up adjacent to a V1 element.
7678 // To make this work, blend them together as the first step.
7679 int V1Index = V2AdjIndex;
7680 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7681 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7682 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7684 // Now proceed to reconstruct the final blend as we have the necessary
7685 // high or low half formed.
7692 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7693 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7695 } else if (NumV2Elements == 2) {
7696 if (Mask[0] < 4 && Mask[1] < 4) {
7697 // Handle the easy case where we have V1 in the low lanes and V2 in the
7701 } else if (Mask[2] < 4 && Mask[3] < 4) {
7702 // We also handle the reversed case because this utility may get called
7703 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7704 // arrange things in the right direction.
7710 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7711 // trying to place elements directly, just blend them and set up the final
7712 // shuffle to place them.
7714 // The first two blend mask elements are for V1, the second two are for
7716 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7717 Mask[2] < 4 ? Mask[2] : Mask[3],
7718 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7719 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7720 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7721 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7723 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7726 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7727 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7728 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7729 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7732 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7733 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7736 /// \brief Lower 4-lane 32-bit floating point shuffles.
7738 /// Uses instructions exclusively from the floating point unit to minimize
7739 /// domain crossing penalties, as these are sufficient to implement all v4f32
7741 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7742 const X86Subtarget *Subtarget,
7743 SelectionDAG &DAG) {
7745 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7746 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7747 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7748 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7749 ArrayRef<int> Mask = SVOp->getMask();
7750 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7753 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7755 if (NumV2Elements == 0) {
7756 // Check for being able to broadcast a single element.
7757 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7758 Mask, Subtarget, DAG))
7761 // Use even/odd duplicate instructions for masks that match their pattern.
7762 if (Subtarget->hasSSE3()) {
7763 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7764 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7765 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7766 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7769 if (Subtarget->hasAVX()) {
7770 // If we have AVX, we can use VPERMILPS which will allow folding a load
7771 // into the shuffle.
7772 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7773 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7776 // Otherwise, use a straight shuffle of a single input vector. We pass the
7777 // input vector to both operands to simulate this with a SHUFPS.
7778 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7779 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7782 // There are special ways we can lower some single-element blends. However, we
7783 // have custom ways we can lower more complex single-element blends below that
7784 // we defer to if both this and BLENDPS fail to match, so restrict this to
7785 // when the V2 input is targeting element 0 of the mask -- that is the fast
7787 if (NumV2Elements == 1 && Mask[0] >= 4)
7788 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7789 Mask, Subtarget, DAG))
7792 if (Subtarget->hasSSE41()) {
7793 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7797 // Use INSERTPS if we can complete the shuffle efficiently.
7798 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7801 if (!isSingleSHUFPSMask(Mask))
7802 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7803 DL, MVT::v4f32, V1, V2, Mask, DAG))
7807 // Use dedicated unpack instructions for masks that match their pattern.
7808 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7809 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7810 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7811 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7812 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7813 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7814 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7815 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7817 // Otherwise fall back to a SHUFPS lowering strategy.
7818 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7821 /// \brief Lower 4-lane i32 vector shuffles.
7823 /// We try to handle these with integer-domain shuffles where we can, but for
7824 /// blends we use the floating point domain blend instructions.
7825 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7826 const X86Subtarget *Subtarget,
7827 SelectionDAG &DAG) {
7829 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7830 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7831 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7832 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7833 ArrayRef<int> Mask = SVOp->getMask();
7834 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7836 // Whenever we can lower this as a zext, that instruction is strictly faster
7837 // than any alternative. It also allows us to fold memory operands into the
7838 // shuffle in many cases.
7839 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7840 Mask, Subtarget, DAG))
7844 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7846 if (NumV2Elements == 0) {
7847 // Check for being able to broadcast a single element.
7848 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7849 Mask, Subtarget, DAG))
7852 // Straight shuffle of a single input vector. For everything from SSE2
7853 // onward this has a single fast instruction with no scary immediates.
7854 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7855 // but we aren't actually going to use the UNPCK instruction because doing
7856 // so prevents folding a load into this instruction or making a copy.
7857 const int UnpackLoMask[] = {0, 0, 1, 1};
7858 const int UnpackHiMask[] = {2, 2, 3, 3};
7859 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7860 Mask = UnpackLoMask;
7861 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7862 Mask = UnpackHiMask;
7864 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7865 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7868 // Try to use shift instructions.
7870 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7873 // There are special ways we can lower some single-element blends.
7874 if (NumV2Elements == 1)
7875 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7876 Mask, Subtarget, DAG))
7879 // We have different paths for blend lowering, but they all must use the
7880 // *exact* same predicate.
7881 bool IsBlendSupported = Subtarget->hasSSE41();
7882 if (IsBlendSupported)
7883 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7887 if (SDValue Masked =
7888 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7891 // Use dedicated unpack instructions for masks that match their pattern.
7892 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7893 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7894 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7895 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7896 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7897 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7898 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7899 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7901 // Try to use byte rotation instructions.
7902 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7903 if (Subtarget->hasSSSE3())
7904 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7905 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7908 // If we have direct support for blends, we should lower by decomposing into
7909 // a permute. That will be faster than the domain cross.
7910 if (IsBlendSupported)
7911 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7914 // Try to lower by permuting the inputs into an unpack instruction.
7915 if (SDValue Unpack =
7916 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7919 // We implement this with SHUFPS because it can blend from two vectors.
7920 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7921 // up the inputs, bypassing domain shift penalties that we would encur if we
7922 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7924 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7925 DAG.getVectorShuffle(
7927 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7928 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7931 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7932 /// shuffle lowering, and the most complex part.
7934 /// The lowering strategy is to try to form pairs of input lanes which are
7935 /// targeted at the same half of the final vector, and then use a dword shuffle
7936 /// to place them onto the right half, and finally unpack the paired lanes into
7937 /// their final position.
7939 /// The exact breakdown of how to form these dword pairs and align them on the
7940 /// correct sides is really tricky. See the comments within the function for
7941 /// more of the details.
7943 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7944 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7945 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7946 /// vector, form the analogous 128-bit 8-element Mask.
7947 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7948 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7949 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7950 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7951 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7953 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7954 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7955 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7957 SmallVector<int, 4> LoInputs;
7958 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7959 [](int M) { return M >= 0; });
7960 std::sort(LoInputs.begin(), LoInputs.end());
7961 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7962 SmallVector<int, 4> HiInputs;
7963 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7964 [](int M) { return M >= 0; });
7965 std::sort(HiInputs.begin(), HiInputs.end());
7966 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7968 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7969 int NumHToL = LoInputs.size() - NumLToL;
7971 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7972 int NumHToH = HiInputs.size() - NumLToH;
7973 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7974 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7975 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7976 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7978 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7979 // such inputs we can swap two of the dwords across the half mark and end up
7980 // with <=2 inputs to each half in each half. Once there, we can fall through
7981 // to the generic code below. For example:
7983 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7984 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7986 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7987 // and an existing 2-into-2 on the other half. In this case we may have to
7988 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7989 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7990 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7991 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7992 // half than the one we target for fixing) will be fixed when we re-enter this
7993 // path. We will also combine away any sequence of PSHUFD instructions that
7994 // result into a single instruction. Here is an example of the tricky case:
7996 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7997 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7999 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8001 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8002 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8004 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8005 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8007 // The result is fine to be handled by the generic logic.
8008 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8009 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8010 int AOffset, int BOffset) {
8011 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8012 "Must call this with A having 3 or 1 inputs from the A half.");
8013 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8014 "Must call this with B having 1 or 3 inputs from the B half.");
8015 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8016 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8018 // Compute the index of dword with only one word among the three inputs in
8019 // a half by taking the sum of the half with three inputs and subtracting
8020 // the sum of the actual three inputs. The difference is the remaining
8023 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8024 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8025 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8026 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8027 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8028 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8029 int TripleNonInputIdx =
8030 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8031 TripleDWord = TripleNonInputIdx / 2;
8033 // We use xor with one to compute the adjacent DWord to whichever one the
8035 OneInputDWord = (OneInput / 2) ^ 1;
8037 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8038 // and BToA inputs. If there is also such a problem with the BToB and AToB
8039 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8040 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8041 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8042 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8043 // Compute how many inputs will be flipped by swapping these DWords. We
8045 // to balance this to ensure we don't form a 3-1 shuffle in the other
8047 int NumFlippedAToBInputs =
8048 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8049 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8050 int NumFlippedBToBInputs =
8051 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8052 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8053 if ((NumFlippedAToBInputs == 1 &&
8054 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8055 (NumFlippedBToBInputs == 1 &&
8056 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8057 // We choose whether to fix the A half or B half based on whether that
8058 // half has zero flipped inputs. At zero, we may not be able to fix it
8059 // with that half. We also bias towards fixing the B half because that
8060 // will more commonly be the high half, and we have to bias one way.
8061 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8062 ArrayRef<int> Inputs) {
8063 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8064 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8065 PinnedIdx ^ 1) != Inputs.end();
8066 // Determine whether the free index is in the flipped dword or the
8067 // unflipped dword based on where the pinned index is. We use this bit
8068 // in an xor to conditionally select the adjacent dword.
8069 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8070 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8071 FixFreeIdx) != Inputs.end();
8072 if (IsFixIdxInput == IsFixFreeIdxInput)
8074 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8075 FixFreeIdx) != Inputs.end();
8076 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8077 "We need to be changing the number of flipped inputs!");
8078 int PSHUFHalfMask[] = {0, 1, 2, 3};
8079 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8080 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8082 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8085 if (M != -1 && M == FixIdx)
8087 else if (M != -1 && M == FixFreeIdx)
8090 if (NumFlippedBToBInputs != 0) {
8092 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8093 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8095 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8097 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8098 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8103 int PSHUFDMask[] = {0, 1, 2, 3};
8104 PSHUFDMask[ADWord] = BDWord;
8105 PSHUFDMask[BDWord] = ADWord;
8106 V = DAG.getNode(ISD::BITCAST, DL, VT,
8107 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8108 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8109 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8112 // Adjust the mask to match the new locations of A and B.
8114 if (M != -1 && M/2 == ADWord)
8115 M = 2 * BDWord + M % 2;
8116 else if (M != -1 && M/2 == BDWord)
8117 M = 2 * ADWord + M % 2;
8119 // Recurse back into this routine to re-compute state now that this isn't
8120 // a 3 and 1 problem.
8121 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8124 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8125 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8126 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8127 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8129 // At this point there are at most two inputs to the low and high halves from
8130 // each half. That means the inputs can always be grouped into dwords and
8131 // those dwords can then be moved to the correct half with a dword shuffle.
8132 // We use at most one low and one high word shuffle to collect these paired
8133 // inputs into dwords, and finally a dword shuffle to place them.
8134 int PSHUFLMask[4] = {-1, -1, -1, -1};
8135 int PSHUFHMask[4] = {-1, -1, -1, -1};
8136 int PSHUFDMask[4] = {-1, -1, -1, -1};
8138 // First fix the masks for all the inputs that are staying in their
8139 // original halves. This will then dictate the targets of the cross-half
8141 auto fixInPlaceInputs =
8142 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8143 MutableArrayRef<int> SourceHalfMask,
8144 MutableArrayRef<int> HalfMask, int HalfOffset) {
8145 if (InPlaceInputs.empty())
8147 if (InPlaceInputs.size() == 1) {
8148 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8149 InPlaceInputs[0] - HalfOffset;
8150 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8153 if (IncomingInputs.empty()) {
8154 // Just fix all of the in place inputs.
8155 for (int Input : InPlaceInputs) {
8156 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8157 PSHUFDMask[Input / 2] = Input / 2;
8162 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8163 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8164 InPlaceInputs[0] - HalfOffset;
8165 // Put the second input next to the first so that they are packed into
8166 // a dword. We find the adjacent index by toggling the low bit.
8167 int AdjIndex = InPlaceInputs[0] ^ 1;
8168 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8169 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8170 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8172 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8173 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8175 // Now gather the cross-half inputs and place them into a free dword of
8176 // their target half.
8177 // FIXME: This operation could almost certainly be simplified dramatically to
8178 // look more like the 3-1 fixing operation.
8179 auto moveInputsToRightHalf = [&PSHUFDMask](
8180 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8181 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8182 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8184 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8185 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8187 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8189 int LowWord = Word & ~1;
8190 int HighWord = Word | 1;
8191 return isWordClobbered(SourceHalfMask, LowWord) ||
8192 isWordClobbered(SourceHalfMask, HighWord);
8195 if (IncomingInputs.empty())
8198 if (ExistingInputs.empty()) {
8199 // Map any dwords with inputs from them into the right half.
8200 for (int Input : IncomingInputs) {
8201 // If the source half mask maps over the inputs, turn those into
8202 // swaps and use the swapped lane.
8203 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8204 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8205 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8206 Input - SourceOffset;
8207 // We have to swap the uses in our half mask in one sweep.
8208 for (int &M : HalfMask)
8209 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8211 else if (M == Input)
8212 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8214 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8215 Input - SourceOffset &&
8216 "Previous placement doesn't match!");
8218 // Note that this correctly re-maps both when we do a swap and when
8219 // we observe the other side of the swap above. We rely on that to
8220 // avoid swapping the members of the input list directly.
8221 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8224 // Map the input's dword into the correct half.
8225 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8226 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8228 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8230 "Previous placement doesn't match!");
8233 // And just directly shift any other-half mask elements to be same-half
8234 // as we will have mirrored the dword containing the element into the
8235 // same position within that half.
8236 for (int &M : HalfMask)
8237 if (M >= SourceOffset && M < SourceOffset + 4) {
8238 M = M - SourceOffset + DestOffset;
8239 assert(M >= 0 && "This should never wrap below zero!");
8244 // Ensure we have the input in a viable dword of its current half. This
8245 // is particularly tricky because the original position may be clobbered
8246 // by inputs being moved and *staying* in that half.
8247 if (IncomingInputs.size() == 1) {
8248 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8249 int InputFixed = std::find(std::begin(SourceHalfMask),
8250 std::end(SourceHalfMask), -1) -
8251 std::begin(SourceHalfMask) + SourceOffset;
8252 SourceHalfMask[InputFixed - SourceOffset] =
8253 IncomingInputs[0] - SourceOffset;
8254 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8256 IncomingInputs[0] = InputFixed;
8258 } else if (IncomingInputs.size() == 2) {
8259 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8260 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8261 // We have two non-adjacent or clobbered inputs we need to extract from
8262 // the source half. To do this, we need to map them into some adjacent
8263 // dword slot in the source mask.
8264 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8265 IncomingInputs[1] - SourceOffset};
8267 // If there is a free slot in the source half mask adjacent to one of
8268 // the inputs, place the other input in it. We use (Index XOR 1) to
8269 // compute an adjacent index.
8270 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8271 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8272 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8273 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8274 InputsFixed[1] = InputsFixed[0] ^ 1;
8275 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8276 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8277 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8278 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8279 InputsFixed[0] = InputsFixed[1] ^ 1;
8280 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8281 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8282 // The two inputs are in the same DWord but it is clobbered and the
8283 // adjacent DWord isn't used at all. Move both inputs to the free
8285 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8286 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8287 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8288 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8290 // The only way we hit this point is if there is no clobbering
8291 // (because there are no off-half inputs to this half) and there is no
8292 // free slot adjacent to one of the inputs. In this case, we have to
8293 // swap an input with a non-input.
8294 for (int i = 0; i < 4; ++i)
8295 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8296 "We can't handle any clobbers here!");
8297 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8298 "Cannot have adjacent inputs here!");
8300 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8301 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8303 // We also have to update the final source mask in this case because
8304 // it may need to undo the above swap.
8305 for (int &M : FinalSourceHalfMask)
8306 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8307 M = InputsFixed[1] + SourceOffset;
8308 else if (M == InputsFixed[1] + SourceOffset)
8309 M = (InputsFixed[0] ^ 1) + SourceOffset;
8311 InputsFixed[1] = InputsFixed[0] ^ 1;
8314 // Point everything at the fixed inputs.
8315 for (int &M : HalfMask)
8316 if (M == IncomingInputs[0])
8317 M = InputsFixed[0] + SourceOffset;
8318 else if (M == IncomingInputs[1])
8319 M = InputsFixed[1] + SourceOffset;
8321 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8322 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8325 llvm_unreachable("Unhandled input size!");
8328 // Now hoist the DWord down to the right half.
8329 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8330 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8331 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8332 for (int &M : HalfMask)
8333 for (int Input : IncomingInputs)
8335 M = FreeDWord * 2 + Input % 2;
8337 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8338 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8339 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8340 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8342 // Now enact all the shuffles we've computed to move the inputs into their
8344 if (!isNoopShuffleMask(PSHUFLMask))
8345 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8346 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8347 if (!isNoopShuffleMask(PSHUFHMask))
8348 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8349 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8350 if (!isNoopShuffleMask(PSHUFDMask))
8351 V = DAG.getNode(ISD::BITCAST, DL, VT,
8352 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8353 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8354 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8357 // At this point, each half should contain all its inputs, and we can then
8358 // just shuffle them into their final position.
8359 assert(std::count_if(LoMask.begin(), LoMask.end(),
8360 [](int M) { return M >= 4; }) == 0 &&
8361 "Failed to lift all the high half inputs to the low mask!");
8362 assert(std::count_if(HiMask.begin(), HiMask.end(),
8363 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8364 "Failed to lift all the low half inputs to the high mask!");
8366 // Do a half shuffle for the low mask.
8367 if (!isNoopShuffleMask(LoMask))
8368 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8369 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8371 // Do a half shuffle with the high mask after shifting its values down.
8372 for (int &M : HiMask)
8375 if (!isNoopShuffleMask(HiMask))
8376 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8377 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8382 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8383 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8384 SDValue V2, ArrayRef<int> Mask,
8385 SelectionDAG &DAG, bool &V1InUse,
8387 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8393 int Size = Mask.size();
8394 int Scale = 16 / Size;
8395 for (int i = 0; i < 16; ++i) {
8396 if (Mask[i / Scale] == -1) {
8397 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8399 const int ZeroMask = 0x80;
8400 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8402 int V2Idx = Mask[i / Scale] < Size
8404 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8405 if (Zeroable[i / Scale])
8406 V1Idx = V2Idx = ZeroMask;
8407 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8408 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8409 V1InUse |= (ZeroMask != V1Idx);
8410 V2InUse |= (ZeroMask != V2Idx);
8415 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8416 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8417 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8419 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8420 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8421 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8423 // If we need shuffled inputs from both, blend the two.
8425 if (V1InUse && V2InUse)
8426 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8428 V = V1InUse ? V1 : V2;
8430 // Cast the result back to the correct type.
8431 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8434 /// \brief Generic lowering of 8-lane i16 shuffles.
8436 /// This handles both single-input shuffles and combined shuffle/blends with
8437 /// two inputs. The single input shuffles are immediately delegated to
8438 /// a dedicated lowering routine.
8440 /// The blends are lowered in one of three fundamental ways. If there are few
8441 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8442 /// of the input is significantly cheaper when lowered as an interleaving of
8443 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8444 /// halves of the inputs separately (making them have relatively few inputs)
8445 /// and then concatenate them.
8446 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8447 const X86Subtarget *Subtarget,
8448 SelectionDAG &DAG) {
8450 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8451 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8452 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8453 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8454 ArrayRef<int> OrigMask = SVOp->getMask();
8455 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8456 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8457 MutableArrayRef<int> Mask(MaskStorage);
8459 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8461 // Whenever we can lower this as a zext, that instruction is strictly faster
8462 // than any alternative.
8463 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8464 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8467 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8469 auto isV2 = [](int M) { return M >= 8; };
8471 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8473 if (NumV2Inputs == 0) {
8474 // Check for being able to broadcast a single element.
8475 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8476 Mask, Subtarget, DAG))
8479 // Try to use shift instructions.
8481 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8484 // Use dedicated unpack instructions for masks that match their pattern.
8485 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8486 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8487 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8488 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8490 // Try to use byte rotation instructions.
8491 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8492 Mask, Subtarget, DAG))
8495 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8499 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8500 "All single-input shuffles should be canonicalized to be V1-input "
8503 // Try to use shift instructions.
8505 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8508 // There are special ways we can lower some single-element blends.
8509 if (NumV2Inputs == 1)
8510 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8511 Mask, Subtarget, DAG))
8514 // We have different paths for blend lowering, but they all must use the
8515 // *exact* same predicate.
8516 bool IsBlendSupported = Subtarget->hasSSE41();
8517 if (IsBlendSupported)
8518 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8522 if (SDValue Masked =
8523 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8526 // Use dedicated unpack instructions for masks that match their pattern.
8527 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8528 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8529 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8530 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8532 // Try to use byte rotation instructions.
8533 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8534 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8537 if (SDValue BitBlend =
8538 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8541 if (SDValue Unpack =
8542 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8545 // If we can't directly blend but can use PSHUFB, that will be better as it
8546 // can both shuffle and set up the inefficient blend.
8547 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8548 bool V1InUse, V2InUse;
8549 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8553 // We can always bit-blend if we have to so the fallback strategy is to
8554 // decompose into single-input permutes and blends.
8555 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8559 /// \brief Check whether a compaction lowering can be done by dropping even
8560 /// elements and compute how many times even elements must be dropped.
8562 /// This handles shuffles which take every Nth element where N is a power of
8563 /// two. Example shuffle masks:
8565 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8566 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8567 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8568 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8569 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8570 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8572 /// Any of these lanes can of course be undef.
8574 /// This routine only supports N <= 3.
8575 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8578 /// \returns N above, or the number of times even elements must be dropped if
8579 /// there is such a number. Otherwise returns zero.
8580 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8581 // Figure out whether we're looping over two inputs or just one.
8582 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8584 // The modulus for the shuffle vector entries is based on whether this is
8585 // a single input or not.
8586 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8587 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8588 "We should only be called with masks with a power-of-2 size!");
8590 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8592 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8593 // and 2^3 simultaneously. This is because we may have ambiguity with
8594 // partially undef inputs.
8595 bool ViableForN[3] = {true, true, true};
8597 for (int i = 0, e = Mask.size(); i < e; ++i) {
8598 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8603 bool IsAnyViable = false;
8604 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8605 if (ViableForN[j]) {
8608 // The shuffle mask must be equal to (i * 2^N) % M.
8609 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8612 ViableForN[j] = false;
8614 // Early exit if we exhaust the possible powers of two.
8619 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8623 // Return 0 as there is no viable power of two.
8627 /// \brief Generic lowering of v16i8 shuffles.
8629 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8630 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8631 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8632 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8634 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8635 const X86Subtarget *Subtarget,
8636 SelectionDAG &DAG) {
8638 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8639 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8640 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8641 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8642 ArrayRef<int> Mask = SVOp->getMask();
8643 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8645 // Try to use shift instructions.
8647 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8650 // Try to use byte rotation instructions.
8651 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8652 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8655 // Try to use a zext lowering.
8656 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8657 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8661 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8663 // For single-input shuffles, there are some nicer lowering tricks we can use.
8664 if (NumV2Elements == 0) {
8665 // Check for being able to broadcast a single element.
8666 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8667 Mask, Subtarget, DAG))
8670 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8671 // Notably, this handles splat and partial-splat shuffles more efficiently.
8672 // However, it only makes sense if the pre-duplication shuffle simplifies
8673 // things significantly. Currently, this means we need to be able to
8674 // express the pre-duplication shuffle as an i16 shuffle.
8676 // FIXME: We should check for other patterns which can be widened into an
8677 // i16 shuffle as well.
8678 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8679 for (int i = 0; i < 16; i += 2)
8680 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8685 auto tryToWidenViaDuplication = [&]() -> SDValue {
8686 if (!canWidenViaDuplication(Mask))
8688 SmallVector<int, 4> LoInputs;
8689 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8690 [](int M) { return M >= 0 && M < 8; });
8691 std::sort(LoInputs.begin(), LoInputs.end());
8692 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8694 SmallVector<int, 4> HiInputs;
8695 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8696 [](int M) { return M >= 8; });
8697 std::sort(HiInputs.begin(), HiInputs.end());
8698 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8701 bool TargetLo = LoInputs.size() >= HiInputs.size();
8702 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8703 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8705 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8706 SmallDenseMap<int, int, 8> LaneMap;
8707 for (int I : InPlaceInputs) {
8708 PreDupI16Shuffle[I/2] = I/2;
8711 int j = TargetLo ? 0 : 4, je = j + 4;
8712 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8713 // Check if j is already a shuffle of this input. This happens when
8714 // there are two adjacent bytes after we move the low one.
8715 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8716 // If we haven't yet mapped the input, search for a slot into which
8718 while (j < je && PreDupI16Shuffle[j] != -1)
8722 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8725 // Map this input with the i16 shuffle.
8726 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8729 // Update the lane map based on the mapping we ended up with.
8730 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8733 ISD::BITCAST, DL, MVT::v16i8,
8734 DAG.getVectorShuffle(MVT::v8i16, DL,
8735 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8736 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8738 // Unpack the bytes to form the i16s that will be shuffled into place.
8739 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8740 MVT::v16i8, V1, V1);
8742 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8743 for (int i = 0; i < 16; ++i)
8744 if (Mask[i] != -1) {
8745 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8746 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8747 if (PostDupI16Shuffle[i / 2] == -1)
8748 PostDupI16Shuffle[i / 2] = MappedMask;
8750 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8751 "Conflicting entrties in the original shuffle!");
8754 ISD::BITCAST, DL, MVT::v16i8,
8755 DAG.getVectorShuffle(MVT::v8i16, DL,
8756 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8757 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8759 if (SDValue V = tryToWidenViaDuplication())
8763 // Use dedicated unpack instructions for masks that match their pattern.
8764 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8765 0, 16, 1, 17, 2, 18, 3, 19,
8767 4, 20, 5, 21, 6, 22, 7, 23}))
8768 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8769 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8770 8, 24, 9, 25, 10, 26, 11, 27,
8772 12, 28, 13, 29, 14, 30, 15, 31}))
8773 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8775 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8776 // with PSHUFB. It is important to do this before we attempt to generate any
8777 // blends but after all of the single-input lowerings. If the single input
8778 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8779 // want to preserve that and we can DAG combine any longer sequences into
8780 // a PSHUFB in the end. But once we start blending from multiple inputs,
8781 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8782 // and there are *very* few patterns that would actually be faster than the
8783 // PSHUFB approach because of its ability to zero lanes.
8785 // FIXME: The only exceptions to the above are blends which are exact
8786 // interleavings with direct instructions supporting them. We currently don't
8787 // handle those well here.
8788 if (Subtarget->hasSSSE3()) {
8789 bool V1InUse = false;
8790 bool V2InUse = false;
8792 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8793 DAG, V1InUse, V2InUse);
8795 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8796 // do so. This avoids using them to handle blends-with-zero which is
8797 // important as a single pshufb is significantly faster for that.
8798 if (V1InUse && V2InUse) {
8799 if (Subtarget->hasSSE41())
8800 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8801 Mask, Subtarget, DAG))
8804 // We can use an unpack to do the blending rather than an or in some
8805 // cases. Even though the or may be (very minorly) more efficient, we
8806 // preference this lowering because there are common cases where part of
8807 // the complexity of the shuffles goes away when we do the final blend as
8809 // FIXME: It might be worth trying to detect if the unpack-feeding
8810 // shuffles will both be pshufb, in which case we shouldn't bother with
8812 if (SDValue Unpack =
8813 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8820 // There are special ways we can lower some single-element blends.
8821 if (NumV2Elements == 1)
8822 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8823 Mask, Subtarget, DAG))
8826 if (SDValue BitBlend =
8827 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8830 // Check whether a compaction lowering can be done. This handles shuffles
8831 // which take every Nth element for some even N. See the helper function for
8834 // We special case these as they can be particularly efficiently handled with
8835 // the PACKUSB instruction on x86 and they show up in common patterns of
8836 // rearranging bytes to truncate wide elements.
8837 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8838 // NumEvenDrops is the power of two stride of the elements. Another way of
8839 // thinking about it is that we need to drop the even elements this many
8840 // times to get the original input.
8841 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8843 // First we need to zero all the dropped bytes.
8844 assert(NumEvenDrops <= 3 &&
8845 "No support for dropping even elements more than 3 times.");
8846 // We use the mask type to pick which bytes are preserved based on how many
8847 // elements are dropped.
8848 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8849 SDValue ByteClearMask =
8850 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8851 DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8852 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8854 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8856 // Now pack things back together.
8857 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8858 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8859 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8860 for (int i = 1; i < NumEvenDrops; ++i) {
8861 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8862 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8868 // Handle multi-input cases by blending single-input shuffles.
8869 if (NumV2Elements > 0)
8870 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8873 // The fallback path for single-input shuffles widens this into two v8i16
8874 // vectors with unpacks, shuffles those, and then pulls them back together
8878 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8879 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8880 for (int i = 0; i < 16; ++i)
8882 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8884 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8886 SDValue VLoHalf, VHiHalf;
8887 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8888 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8890 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8891 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8892 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8893 [](int M) { return M >= 0 && M % 2 == 1; })) {
8894 // Use a mask to drop the high bytes.
8895 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8896 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8897 DAG.getConstant(0x00FF, DL, MVT::v8i16));
8899 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8900 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8902 // Squash the masks to point directly into VLoHalf.
8903 for (int &M : LoBlendMask)
8906 for (int &M : HiBlendMask)
8910 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8911 // VHiHalf so that we can blend them as i16s.
8912 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8913 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8914 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8915 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8918 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8919 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8921 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8924 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8926 /// This routine breaks down the specific type of 128-bit shuffle and
8927 /// dispatches to the lowering routines accordingly.
8928 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8929 MVT VT, const X86Subtarget *Subtarget,
8930 SelectionDAG &DAG) {
8931 switch (VT.SimpleTy) {
8933 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8935 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8937 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8939 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8941 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8943 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8946 llvm_unreachable("Unimplemented!");
8950 /// \brief Helper function to test whether a shuffle mask could be
8951 /// simplified by widening the elements being shuffled.
8953 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8954 /// leaves it in an unspecified state.
8956 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8957 /// shuffle masks. The latter have the special property of a '-2' representing
8958 /// a zero-ed lane of a vector.
8959 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8960 SmallVectorImpl<int> &WidenedMask) {
8961 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8962 // If both elements are undef, its trivial.
8963 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8964 WidenedMask.push_back(SM_SentinelUndef);
8968 // Check for an undef mask and a mask value properly aligned to fit with
8969 // a pair of values. If we find such a case, use the non-undef mask's value.
8970 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8971 WidenedMask.push_back(Mask[i + 1] / 2);
8974 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8975 WidenedMask.push_back(Mask[i] / 2);
8979 // When zeroing, we need to spread the zeroing across both lanes to widen.
8980 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8981 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8982 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8983 WidenedMask.push_back(SM_SentinelZero);
8989 // Finally check if the two mask values are adjacent and aligned with
8991 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8992 WidenedMask.push_back(Mask[i] / 2);
8996 // Otherwise we can't safely widen the elements used in this shuffle.
8999 assert(WidenedMask.size() == Mask.size() / 2 &&
9000 "Incorrect size of mask after widening the elements!");
9005 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9007 /// This routine just extracts two subvectors, shuffles them independently, and
9008 /// then concatenates them back together. This should work effectively with all
9009 /// AVX vector shuffle types.
9010 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9011 SDValue V2, ArrayRef<int> Mask,
9012 SelectionDAG &DAG) {
9013 assert(VT.getSizeInBits() >= 256 &&
9014 "Only for 256-bit or wider vector shuffles!");
9015 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9016 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9018 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9019 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9021 int NumElements = VT.getVectorNumElements();
9022 int SplitNumElements = NumElements / 2;
9023 MVT ScalarVT = VT.getScalarType();
9024 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9026 // Rather than splitting build-vectors, just build two narrower build
9027 // vectors. This helps shuffling with splats and zeros.
9028 auto SplitVector = [&](SDValue V) {
9029 while (V.getOpcode() == ISD::BITCAST)
9030 V = V->getOperand(0);
9032 MVT OrigVT = V.getSimpleValueType();
9033 int OrigNumElements = OrigVT.getVectorNumElements();
9034 int OrigSplitNumElements = OrigNumElements / 2;
9035 MVT OrigScalarVT = OrigVT.getScalarType();
9036 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9040 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9042 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9043 DAG.getIntPtrConstant(0, DL));
9044 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9045 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9048 SmallVector<SDValue, 16> LoOps, HiOps;
9049 for (int i = 0; i < OrigSplitNumElements; ++i) {
9050 LoOps.push_back(BV->getOperand(i));
9051 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9053 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9054 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9056 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9057 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9060 SDValue LoV1, HiV1, LoV2, HiV2;
9061 std::tie(LoV1, HiV1) = SplitVector(V1);
9062 std::tie(LoV2, HiV2) = SplitVector(V2);
9064 // Now create two 4-way blends of these half-width vectors.
9065 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9066 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9067 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9068 for (int i = 0; i < SplitNumElements; ++i) {
9069 int M = HalfMask[i];
9070 if (M >= NumElements) {
9071 if (M >= NumElements + SplitNumElements)
9075 V2BlendMask.push_back(M - NumElements);
9076 V1BlendMask.push_back(-1);
9077 BlendMask.push_back(SplitNumElements + i);
9078 } else if (M >= 0) {
9079 if (M >= SplitNumElements)
9083 V2BlendMask.push_back(-1);
9084 V1BlendMask.push_back(M);
9085 BlendMask.push_back(i);
9087 V2BlendMask.push_back(-1);
9088 V1BlendMask.push_back(-1);
9089 BlendMask.push_back(-1);
9093 // Because the lowering happens after all combining takes place, we need to
9094 // manually combine these blend masks as much as possible so that we create
9095 // a minimal number of high-level vector shuffle nodes.
9097 // First try just blending the halves of V1 or V2.
9098 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9099 return DAG.getUNDEF(SplitVT);
9100 if (!UseLoV2 && !UseHiV2)
9101 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9102 if (!UseLoV1 && !UseHiV1)
9103 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9105 SDValue V1Blend, V2Blend;
9106 if (UseLoV1 && UseHiV1) {
9108 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9110 // We only use half of V1 so map the usage down into the final blend mask.
9111 V1Blend = UseLoV1 ? LoV1 : HiV1;
9112 for (int i = 0; i < SplitNumElements; ++i)
9113 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9114 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9116 if (UseLoV2 && UseHiV2) {
9118 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9120 // We only use half of V2 so map the usage down into the final blend mask.
9121 V2Blend = UseLoV2 ? LoV2 : HiV2;
9122 for (int i = 0; i < SplitNumElements; ++i)
9123 if (BlendMask[i] >= SplitNumElements)
9124 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9126 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9128 SDValue Lo = HalfBlend(LoMask);
9129 SDValue Hi = HalfBlend(HiMask);
9130 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9133 /// \brief Either split a vector in halves or decompose the shuffles and the
9136 /// This is provided as a good fallback for many lowerings of non-single-input
9137 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9138 /// between splitting the shuffle into 128-bit components and stitching those
9139 /// back together vs. extracting the single-input shuffles and blending those
9141 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9142 SDValue V2, ArrayRef<int> Mask,
9143 SelectionDAG &DAG) {
9144 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9145 "lower single-input shuffles as it "
9146 "could then recurse on itself.");
9147 int Size = Mask.size();
9149 // If this can be modeled as a broadcast of two elements followed by a blend,
9150 // prefer that lowering. This is especially important because broadcasts can
9151 // often fold with memory operands.
9152 auto DoBothBroadcast = [&] {
9153 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9156 if (V2BroadcastIdx == -1)
9157 V2BroadcastIdx = M - Size;
9158 else if (M - Size != V2BroadcastIdx)
9160 } else if (M >= 0) {
9161 if (V1BroadcastIdx == -1)
9163 else if (M != V1BroadcastIdx)
9168 if (DoBothBroadcast())
9169 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9172 // If the inputs all stem from a single 128-bit lane of each input, then we
9173 // split them rather than blending because the split will decompose to
9174 // unusually few instructions.
9175 int LaneCount = VT.getSizeInBits() / 128;
9176 int LaneSize = Size / LaneCount;
9177 SmallBitVector LaneInputs[2];
9178 LaneInputs[0].resize(LaneCount, false);
9179 LaneInputs[1].resize(LaneCount, false);
9180 for (int i = 0; i < Size; ++i)
9182 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9183 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9184 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9186 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9187 // that the decomposed single-input shuffles don't end up here.
9188 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9191 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9192 /// a permutation and blend of those lanes.
9194 /// This essentially blends the out-of-lane inputs to each lane into the lane
9195 /// from a permuted copy of the vector. This lowering strategy results in four
9196 /// instructions in the worst case for a single-input cross lane shuffle which
9197 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9198 /// of. Special cases for each particular shuffle pattern should be handled
9199 /// prior to trying this lowering.
9200 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9201 SDValue V1, SDValue V2,
9203 SelectionDAG &DAG) {
9204 // FIXME: This should probably be generalized for 512-bit vectors as well.
9205 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9206 int LaneSize = Mask.size() / 2;
9208 // If there are only inputs from one 128-bit lane, splitting will in fact be
9209 // less expensive. The flags track whether the given lane contains an element
9210 // that crosses to another lane.
9211 bool LaneCrossing[2] = {false, false};
9212 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9213 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9214 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9215 if (!LaneCrossing[0] || !LaneCrossing[1])
9216 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9218 if (isSingleInputShuffleMask(Mask)) {
9219 SmallVector<int, 32> FlippedBlendMask;
9220 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9221 FlippedBlendMask.push_back(
9222 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9224 : Mask[i] % LaneSize +
9225 (i / LaneSize) * LaneSize + Size));
9227 // Flip the vector, and blend the results which should now be in-lane. The
9228 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9229 // 5 for the high source. The value 3 selects the high half of source 2 and
9230 // the value 2 selects the low half of source 2. We only use source 2 to
9231 // allow folding it into a memory operand.
9232 unsigned PERMMask = 3 | 2 << 4;
9233 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9234 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9235 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9238 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9239 // will be handled by the above logic and a blend of the results, much like
9240 // other patterns in AVX.
9241 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9244 /// \brief Handle lowering 2-lane 128-bit shuffles.
9245 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9246 SDValue V2, ArrayRef<int> Mask,
9247 const X86Subtarget *Subtarget,
9248 SelectionDAG &DAG) {
9249 // TODO: If minimizing size and one of the inputs is a zero vector and the
9250 // the zero vector has only one use, we could use a VPERM2X128 to save the
9251 // instruction bytes needed to explicitly generate the zero vector.
9253 // Blends are faster and handle all the non-lane-crossing cases.
9254 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9258 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9259 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9261 // If either input operand is a zero vector, use VPERM2X128 because its mask
9262 // allows us to replace the zero input with an implicit zero.
9263 if (!IsV1Zero && !IsV2Zero) {
9264 // Check for patterns which can be matched with a single insert of a 128-bit
9266 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9267 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9268 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9269 VT.getVectorNumElements() / 2);
9270 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9271 DAG.getIntPtrConstant(0, DL));
9272 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9273 OnlyUsesV1 ? V1 : V2,
9274 DAG.getIntPtrConstant(0, DL));
9275 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9279 // Otherwise form a 128-bit permutation. After accounting for undefs,
9280 // convert the 64-bit shuffle mask selection values into 128-bit
9281 // selection bits by dividing the indexes by 2 and shifting into positions
9282 // defined by a vperm2*128 instruction's immediate control byte.
9284 // The immediate permute control byte looks like this:
9285 // [1:0] - select 128 bits from sources for low half of destination
9287 // [3] - zero low half of destination
9288 // [5:4] - select 128 bits from sources for high half of destination
9290 // [7] - zero high half of destination
9292 int MaskLO = Mask[0];
9293 if (MaskLO == SM_SentinelUndef)
9294 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9296 int MaskHI = Mask[2];
9297 if (MaskHI == SM_SentinelUndef)
9298 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9300 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9302 // If either input is a zero vector, replace it with an undef input.
9303 // Shuffle mask values < 4 are selecting elements of V1.
9304 // Shuffle mask values >= 4 are selecting elements of V2.
9305 // Adjust each half of the permute mask by clearing the half that was
9306 // selecting the zero vector and setting the zero mask bit.
9308 V1 = DAG.getUNDEF(VT);
9310 PermMask = (PermMask & 0xf0) | 0x08;
9312 PermMask = (PermMask & 0x0f) | 0x80;
9315 V2 = DAG.getUNDEF(VT);
9317 PermMask = (PermMask & 0xf0) | 0x08;
9319 PermMask = (PermMask & 0x0f) | 0x80;
9322 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9323 DAG.getConstant(PermMask, DL, MVT::i8));
9326 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9327 /// shuffling each lane.
9329 /// This will only succeed when the result of fixing the 128-bit lanes results
9330 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9331 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9332 /// the lane crosses early and then use simpler shuffles within each lane.
9334 /// FIXME: It might be worthwhile at some point to support this without
9335 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9336 /// in x86 only floating point has interesting non-repeating shuffles, and even
9337 /// those are still *marginally* more expensive.
9338 static SDValue lowerVectorShuffleByMerging128BitLanes(
9339 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9340 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9341 assert(!isSingleInputShuffleMask(Mask) &&
9342 "This is only useful with multiple inputs.");
9344 int Size = Mask.size();
9345 int LaneSize = 128 / VT.getScalarSizeInBits();
9346 int NumLanes = Size / LaneSize;
9347 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9349 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9350 // check whether the in-128-bit lane shuffles share a repeating pattern.
9351 SmallVector<int, 4> Lanes;
9352 Lanes.resize(NumLanes, -1);
9353 SmallVector<int, 4> InLaneMask;
9354 InLaneMask.resize(LaneSize, -1);
9355 for (int i = 0; i < Size; ++i) {
9359 int j = i / LaneSize;
9362 // First entry we've seen for this lane.
9363 Lanes[j] = Mask[i] / LaneSize;
9364 } else if (Lanes[j] != Mask[i] / LaneSize) {
9365 // This doesn't match the lane selected previously!
9369 // Check that within each lane we have a consistent shuffle mask.
9370 int k = i % LaneSize;
9371 if (InLaneMask[k] < 0) {
9372 InLaneMask[k] = Mask[i] % LaneSize;
9373 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9374 // This doesn't fit a repeating in-lane mask.
9379 // First shuffle the lanes into place.
9380 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9381 VT.getSizeInBits() / 64);
9382 SmallVector<int, 8> LaneMask;
9383 LaneMask.resize(NumLanes * 2, -1);
9384 for (int i = 0; i < NumLanes; ++i)
9385 if (Lanes[i] >= 0) {
9386 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9387 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9390 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9391 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9392 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9394 // Cast it back to the type we actually want.
9395 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9397 // Now do a simple shuffle that isn't lane crossing.
9398 SmallVector<int, 8> NewMask;
9399 NewMask.resize(Size, -1);
9400 for (int i = 0; i < Size; ++i)
9402 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9403 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9404 "Must not introduce lane crosses at this point!");
9406 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9409 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9412 /// This returns true if the elements from a particular input are already in the
9413 /// slot required by the given mask and require no permutation.
9414 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9415 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9416 int Size = Mask.size();
9417 for (int i = 0; i < Size; ++i)
9418 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9424 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9426 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9427 /// isn't available.
9428 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9429 const X86Subtarget *Subtarget,
9430 SelectionDAG &DAG) {
9432 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9433 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9434 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9435 ArrayRef<int> Mask = SVOp->getMask();
9436 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9438 SmallVector<int, 4> WidenedMask;
9439 if (canWidenShuffleElements(Mask, WidenedMask))
9440 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9443 if (isSingleInputShuffleMask(Mask)) {
9444 // Check for being able to broadcast a single element.
9445 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9446 Mask, Subtarget, DAG))
9449 // Use low duplicate instructions for masks that match their pattern.
9450 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9451 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9453 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9454 // Non-half-crossing single input shuffles can be lowerid with an
9455 // interleaved permutation.
9456 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9457 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9458 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9459 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9462 // With AVX2 we have direct support for this permutation.
9463 if (Subtarget->hasAVX2())
9464 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9465 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9467 // Otherwise, fall back.
9468 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9472 // X86 has dedicated unpack instructions that can handle specific blend
9473 // operations: UNPCKH and UNPCKL.
9474 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9475 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9476 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9477 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9478 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9479 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9480 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9481 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9483 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9487 // Check if the blend happens to exactly fit that of SHUFPD.
9488 if ((Mask[0] == -1 || Mask[0] < 2) &&
9489 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9490 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9491 (Mask[3] == -1 || Mask[3] >= 6)) {
9492 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9493 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9494 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9495 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9497 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9498 (Mask[1] == -1 || Mask[1] < 2) &&
9499 (Mask[2] == -1 || Mask[2] >= 6) &&
9500 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9501 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9502 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9503 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9504 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9507 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9508 // shuffle. However, if we have AVX2 and either inputs are already in place,
9509 // we will be able to shuffle even across lanes the other input in a single
9510 // instruction so skip this pattern.
9511 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9512 isShuffleMaskInputInPlace(1, Mask))))
9513 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9514 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9517 // If we have AVX2 then we always want to lower with a blend because an v4 we
9518 // can fully permute the elements.
9519 if (Subtarget->hasAVX2())
9520 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9523 // Otherwise fall back on generic lowering.
9524 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9527 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9529 /// This routine is only called when we have AVX2 and thus a reasonable
9530 /// instruction set for v4i64 shuffling..
9531 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9532 const X86Subtarget *Subtarget,
9533 SelectionDAG &DAG) {
9535 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9536 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9537 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9538 ArrayRef<int> Mask = SVOp->getMask();
9539 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9540 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9542 SmallVector<int, 4> WidenedMask;
9543 if (canWidenShuffleElements(Mask, WidenedMask))
9544 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9547 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9551 // Check for being able to broadcast a single element.
9552 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9553 Mask, Subtarget, DAG))
9556 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9557 // use lower latency instructions that will operate on both 128-bit lanes.
9558 SmallVector<int, 2> RepeatedMask;
9559 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9560 if (isSingleInputShuffleMask(Mask)) {
9561 int PSHUFDMask[] = {-1, -1, -1, -1};
9562 for (int i = 0; i < 2; ++i)
9563 if (RepeatedMask[i] >= 0) {
9564 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9565 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9568 ISD::BITCAST, DL, MVT::v4i64,
9569 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9570 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9571 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9575 // AVX2 provides a direct instruction for permuting a single input across
9577 if (isSingleInputShuffleMask(Mask))
9578 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9579 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9581 // Try to use shift instructions.
9583 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9586 // Use dedicated unpack instructions for masks that match their pattern.
9587 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9588 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9589 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9590 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9591 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9592 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9593 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9594 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9596 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9597 // shuffle. However, if we have AVX2 and either inputs are already in place,
9598 // we will be able to shuffle even across lanes the other input in a single
9599 // instruction so skip this pattern.
9600 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9601 isShuffleMaskInputInPlace(1, Mask))))
9602 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9603 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9606 // Otherwise fall back on generic blend lowering.
9607 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9611 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9613 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9614 /// isn't available.
9615 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9616 const X86Subtarget *Subtarget,
9617 SelectionDAG &DAG) {
9619 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9620 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9621 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9622 ArrayRef<int> Mask = SVOp->getMask();
9623 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9625 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9629 // Check for being able to broadcast a single element.
9630 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9631 Mask, Subtarget, DAG))
9634 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9635 // options to efficiently lower the shuffle.
9636 SmallVector<int, 4> RepeatedMask;
9637 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9638 assert(RepeatedMask.size() == 4 &&
9639 "Repeated masks must be half the mask width!");
9641 // Use even/odd duplicate instructions for masks that match their pattern.
9642 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9643 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9644 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9645 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9647 if (isSingleInputShuffleMask(Mask))
9648 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9649 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9651 // Use dedicated unpack instructions for masks that match their pattern.
9652 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9653 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9654 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9655 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9656 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9657 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9658 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9659 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9661 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9662 // have already handled any direct blends. We also need to squash the
9663 // repeated mask into a simulated v4f32 mask.
9664 for (int i = 0; i < 4; ++i)
9665 if (RepeatedMask[i] >= 8)
9666 RepeatedMask[i] -= 4;
9667 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9670 // If we have a single input shuffle with different shuffle patterns in the
9671 // two 128-bit lanes use the variable mask to VPERMILPS.
9672 if (isSingleInputShuffleMask(Mask)) {
9673 SDValue VPermMask[8];
9674 for (int i = 0; i < 8; ++i)
9675 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9676 : DAG.getConstant(Mask[i], DL, MVT::i32);
9677 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9679 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9680 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9682 if (Subtarget->hasAVX2())
9683 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9684 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9685 DAG.getNode(ISD::BUILD_VECTOR, DL,
9686 MVT::v8i32, VPermMask)),
9689 // Otherwise, fall back.
9690 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9694 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9696 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9697 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9700 // If we have AVX2 then we always want to lower with a blend because at v8 we
9701 // can fully permute the elements.
9702 if (Subtarget->hasAVX2())
9703 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9706 // Otherwise fall back on generic lowering.
9707 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9710 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9712 /// This routine is only called when we have AVX2 and thus a reasonable
9713 /// instruction set for v8i32 shuffling..
9714 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9715 const X86Subtarget *Subtarget,
9716 SelectionDAG &DAG) {
9718 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9719 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9720 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9721 ArrayRef<int> Mask = SVOp->getMask();
9722 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9723 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9725 // Whenever we can lower this as a zext, that instruction is strictly faster
9726 // than any alternative. It also allows us to fold memory operands into the
9727 // shuffle in many cases.
9728 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9729 Mask, Subtarget, DAG))
9732 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9736 // Check for being able to broadcast a single element.
9737 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9738 Mask, Subtarget, DAG))
9741 // If the shuffle mask is repeated in each 128-bit lane we can use more
9742 // efficient instructions that mirror the shuffles across the two 128-bit
9744 SmallVector<int, 4> RepeatedMask;
9745 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9746 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9747 if (isSingleInputShuffleMask(Mask))
9748 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9749 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9751 // Use dedicated unpack instructions for masks that match their pattern.
9752 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9753 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9754 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9755 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9756 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9757 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9758 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9759 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9762 // Try to use shift instructions.
9764 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9767 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9768 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9771 // If the shuffle patterns aren't repeated but it is a single input, directly
9772 // generate a cross-lane VPERMD instruction.
9773 if (isSingleInputShuffleMask(Mask)) {
9774 SDValue VPermMask[8];
9775 for (int i = 0; i < 8; ++i)
9776 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9777 : DAG.getConstant(Mask[i], DL, MVT::i32);
9779 X86ISD::VPERMV, DL, MVT::v8i32,
9780 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9783 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9785 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9786 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9789 // Otherwise fall back on generic blend lowering.
9790 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9794 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9796 /// This routine is only called when we have AVX2 and thus a reasonable
9797 /// instruction set for v16i16 shuffling..
9798 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9799 const X86Subtarget *Subtarget,
9800 SelectionDAG &DAG) {
9802 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9803 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9804 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9805 ArrayRef<int> Mask = SVOp->getMask();
9806 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9807 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9809 // Whenever we can lower this as a zext, that instruction is strictly faster
9810 // than any alternative. It also allows us to fold memory operands into the
9811 // shuffle in many cases.
9812 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9813 Mask, Subtarget, DAG))
9816 // Check for being able to broadcast a single element.
9817 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9818 Mask, Subtarget, DAG))
9821 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9825 // Use dedicated unpack instructions for masks that match their pattern.
9826 if (isShuffleEquivalent(V1, V2, Mask,
9827 {// First 128-bit lane:
9828 0, 16, 1, 17, 2, 18, 3, 19,
9829 // Second 128-bit lane:
9830 8, 24, 9, 25, 10, 26, 11, 27}))
9831 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9832 if (isShuffleEquivalent(V1, V2, Mask,
9833 {// First 128-bit lane:
9834 4, 20, 5, 21, 6, 22, 7, 23,
9835 // Second 128-bit lane:
9836 12, 28, 13, 29, 14, 30, 15, 31}))
9837 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9839 // Try to use shift instructions.
9841 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9844 // Try to use byte rotation instructions.
9845 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9846 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9849 if (isSingleInputShuffleMask(Mask)) {
9850 // There are no generalized cross-lane shuffle operations available on i16
9852 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9853 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9856 SmallVector<int, 8> RepeatedMask;
9857 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9858 // As this is a single-input shuffle, the repeated mask should be
9859 // a strictly valid v8i16 mask that we can pass through to the v8i16
9860 // lowering to handle even the v16 case.
9861 return lowerV8I16GeneralSingleInputVectorShuffle(
9862 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9865 SDValue PSHUFBMask[32];
9866 for (int i = 0; i < 16; ++i) {
9867 if (Mask[i] == -1) {
9868 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9872 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9873 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9874 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9875 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9878 ISD::BITCAST, DL, MVT::v16i16,
9880 X86ISD::PSHUFB, DL, MVT::v32i8,
9881 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9882 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9885 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9887 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9888 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9891 // Otherwise fall back on generic lowering.
9892 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9895 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9897 /// This routine is only called when we have AVX2 and thus a reasonable
9898 /// instruction set for v32i8 shuffling..
9899 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9900 const X86Subtarget *Subtarget,
9901 SelectionDAG &DAG) {
9903 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9904 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9905 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9906 ArrayRef<int> Mask = SVOp->getMask();
9907 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9908 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9910 // Whenever we can lower this as a zext, that instruction is strictly faster
9911 // than any alternative. It also allows us to fold memory operands into the
9912 // shuffle in many cases.
9913 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9914 Mask, Subtarget, DAG))
9917 // Check for being able to broadcast a single element.
9918 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9919 Mask, Subtarget, DAG))
9922 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9926 // Use dedicated unpack instructions for masks that match their pattern.
9927 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9929 if (isShuffleEquivalent(
9931 {// First 128-bit lane:
9932 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9933 // Second 128-bit lane:
9934 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9935 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9936 if (isShuffleEquivalent(
9938 {// First 128-bit lane:
9939 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9940 // Second 128-bit lane:
9941 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9942 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9944 // Try to use shift instructions.
9946 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9949 // Try to use byte rotation instructions.
9950 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9951 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9954 if (isSingleInputShuffleMask(Mask)) {
9955 // There are no generalized cross-lane shuffle operations available on i8
9957 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9958 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9961 SDValue PSHUFBMask[32];
9962 for (int i = 0; i < 32; ++i)
9965 ? DAG.getUNDEF(MVT::i8)
9966 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9970 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9971 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9974 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9976 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9977 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9980 // Otherwise fall back on generic lowering.
9981 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9984 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9986 /// This routine either breaks down the specific type of a 256-bit x86 vector
9987 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9988 /// together based on the available instructions.
9989 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9990 MVT VT, const X86Subtarget *Subtarget,
9991 SelectionDAG &DAG) {
9993 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9994 ArrayRef<int> Mask = SVOp->getMask();
9996 // If we have a single input to the zero element, insert that into V1 if we
9997 // can do so cheaply.
9998 int NumElts = VT.getVectorNumElements();
9999 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10000 return M >= NumElts;
10003 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10004 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10005 DL, VT, V1, V2, Mask, Subtarget, DAG))
10008 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10009 // check for those subtargets here and avoid much of the subtarget querying in
10010 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10011 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10012 // floating point types there eventually, just immediately cast everything to
10013 // a float and operate entirely in that domain.
10014 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10015 int ElementBits = VT.getScalarSizeInBits();
10016 if (ElementBits < 32)
10017 // No floating point type available, decompose into 128-bit vectors.
10018 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10020 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10021 VT.getVectorNumElements());
10022 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10023 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10024 return DAG.getNode(ISD::BITCAST, DL, VT,
10025 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10028 switch (VT.SimpleTy) {
10030 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10032 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10034 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10036 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10038 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10040 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10043 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10047 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10048 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10049 const X86Subtarget *Subtarget,
10050 SelectionDAG &DAG) {
10052 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10053 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10054 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10055 ArrayRef<int> Mask = SVOp->getMask();
10056 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10058 // X86 has dedicated unpack instructions that can handle specific blend
10059 // operations: UNPCKH and UNPCKL.
10060 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10061 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10062 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10063 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10065 // FIXME: Implement direct support for this type!
10066 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10069 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10070 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10071 const X86Subtarget *Subtarget,
10072 SelectionDAG &DAG) {
10074 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10075 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10076 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10077 ArrayRef<int> Mask = SVOp->getMask();
10078 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10080 // Use dedicated unpack instructions for masks that match their pattern.
10081 if (isShuffleEquivalent(V1, V2, Mask,
10082 {// First 128-bit lane.
10083 0, 16, 1, 17, 4, 20, 5, 21,
10084 // Second 128-bit lane.
10085 8, 24, 9, 25, 12, 28, 13, 29}))
10086 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10087 if (isShuffleEquivalent(V1, V2, Mask,
10088 {// First 128-bit lane.
10089 2, 18, 3, 19, 6, 22, 7, 23,
10090 // Second 128-bit lane.
10091 10, 26, 11, 27, 14, 30, 15, 31}))
10092 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10094 // FIXME: Implement direct support for this type!
10095 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10098 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10099 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10100 const X86Subtarget *Subtarget,
10101 SelectionDAG &DAG) {
10103 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10104 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10105 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10106 ArrayRef<int> Mask = SVOp->getMask();
10107 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10109 // X86 has dedicated unpack instructions that can handle specific blend
10110 // operations: UNPCKH and UNPCKL.
10111 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10112 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10113 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10114 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10116 // FIXME: Implement direct support for this type!
10117 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10120 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10121 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10122 const X86Subtarget *Subtarget,
10123 SelectionDAG &DAG) {
10125 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10126 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10127 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10128 ArrayRef<int> Mask = SVOp->getMask();
10129 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10131 // Use dedicated unpack instructions for masks that match their pattern.
10132 if (isShuffleEquivalent(V1, V2, Mask,
10133 {// First 128-bit lane.
10134 0, 16, 1, 17, 4, 20, 5, 21,
10135 // Second 128-bit lane.
10136 8, 24, 9, 25, 12, 28, 13, 29}))
10137 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10138 if (isShuffleEquivalent(V1, V2, Mask,
10139 {// First 128-bit lane.
10140 2, 18, 3, 19, 6, 22, 7, 23,
10141 // Second 128-bit lane.
10142 10, 26, 11, 27, 14, 30, 15, 31}))
10143 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10145 // FIXME: Implement direct support for this type!
10146 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10149 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10150 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10151 const X86Subtarget *Subtarget,
10152 SelectionDAG &DAG) {
10154 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10155 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10156 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10157 ArrayRef<int> Mask = SVOp->getMask();
10158 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10159 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10161 // FIXME: Implement direct support for this type!
10162 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10165 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10166 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10167 const X86Subtarget *Subtarget,
10168 SelectionDAG &DAG) {
10170 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10171 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10172 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10173 ArrayRef<int> Mask = SVOp->getMask();
10174 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10175 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10177 // FIXME: Implement direct support for this type!
10178 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10181 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10183 /// This routine either breaks down the specific type of a 512-bit x86 vector
10184 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10185 /// together based on the available instructions.
10186 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10187 MVT VT, const X86Subtarget *Subtarget,
10188 SelectionDAG &DAG) {
10190 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10191 ArrayRef<int> Mask = SVOp->getMask();
10192 assert(Subtarget->hasAVX512() &&
10193 "Cannot lower 512-bit vectors w/ basic ISA!");
10195 // Check for being able to broadcast a single element.
10196 if (SDValue Broadcast =
10197 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10200 // Dispatch to each element type for lowering. If we don't have supprot for
10201 // specific element type shuffles at 512 bits, immediately split them and
10202 // lower them. Each lowering routine of a given type is allowed to assume that
10203 // the requisite ISA extensions for that element type are available.
10204 switch (VT.SimpleTy) {
10206 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10208 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10210 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10212 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10214 if (Subtarget->hasBWI())
10215 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10218 if (Subtarget->hasBWI())
10219 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10223 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10226 // Otherwise fall back on splitting.
10227 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10230 /// \brief Top-level lowering for x86 vector shuffles.
10232 /// This handles decomposition, canonicalization, and lowering of all x86
10233 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10234 /// above in helper routines. The canonicalization attempts to widen shuffles
10235 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10236 /// s.t. only one of the two inputs needs to be tested, etc.
10237 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10238 SelectionDAG &DAG) {
10239 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10240 ArrayRef<int> Mask = SVOp->getMask();
10241 SDValue V1 = Op.getOperand(0);
10242 SDValue V2 = Op.getOperand(1);
10243 MVT VT = Op.getSimpleValueType();
10244 int NumElements = VT.getVectorNumElements();
10247 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10249 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10250 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10251 if (V1IsUndef && V2IsUndef)
10252 return DAG.getUNDEF(VT);
10254 // When we create a shuffle node we put the UNDEF node to second operand,
10255 // but in some cases the first operand may be transformed to UNDEF.
10256 // In this case we should just commute the node.
10258 return DAG.getCommutedVectorShuffle(*SVOp);
10260 // Check for non-undef masks pointing at an undef vector and make the masks
10261 // undef as well. This makes it easier to match the shuffle based solely on
10265 if (M >= NumElements) {
10266 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10267 for (int &M : NewMask)
10268 if (M >= NumElements)
10270 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10273 // We actually see shuffles that are entirely re-arrangements of a set of
10274 // zero inputs. This mostly happens while decomposing complex shuffles into
10275 // simple ones. Directly lower these as a buildvector of zeros.
10276 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10277 if (Zeroable.all())
10278 return getZeroVector(VT, Subtarget, DAG, dl);
10280 // Try to collapse shuffles into using a vector type with fewer elements but
10281 // wider element types. We cap this to not form integers or floating point
10282 // elements wider than 64 bits, but it might be interesting to form i128
10283 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10284 SmallVector<int, 16> WidenedMask;
10285 if (VT.getScalarSizeInBits() < 64 &&
10286 canWidenShuffleElements(Mask, WidenedMask)) {
10287 MVT NewEltVT = VT.isFloatingPoint()
10288 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10289 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10290 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10291 // Make sure that the new vector type is legal. For example, v2f64 isn't
10293 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10294 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10295 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10296 return DAG.getNode(ISD::BITCAST, dl, VT,
10297 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10301 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10302 for (int M : SVOp->getMask())
10304 ++NumUndefElements;
10305 else if (M < NumElements)
10310 // Commute the shuffle as needed such that more elements come from V1 than
10311 // V2. This allows us to match the shuffle pattern strictly on how many
10312 // elements come from V1 without handling the symmetric cases.
10313 if (NumV2Elements > NumV1Elements)
10314 return DAG.getCommutedVectorShuffle(*SVOp);
10316 // When the number of V1 and V2 elements are the same, try to minimize the
10317 // number of uses of V2 in the low half of the vector. When that is tied,
10318 // ensure that the sum of indices for V1 is equal to or lower than the sum
10319 // indices for V2. When those are equal, try to ensure that the number of odd
10320 // indices for V1 is lower than the number of odd indices for V2.
10321 if (NumV1Elements == NumV2Elements) {
10322 int LowV1Elements = 0, LowV2Elements = 0;
10323 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10324 if (M >= NumElements)
10328 if (LowV2Elements > LowV1Elements) {
10329 return DAG.getCommutedVectorShuffle(*SVOp);
10330 } else if (LowV2Elements == LowV1Elements) {
10331 int SumV1Indices = 0, SumV2Indices = 0;
10332 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10333 if (SVOp->getMask()[i] >= NumElements)
10335 else if (SVOp->getMask()[i] >= 0)
10337 if (SumV2Indices < SumV1Indices) {
10338 return DAG.getCommutedVectorShuffle(*SVOp);
10339 } else if (SumV2Indices == SumV1Indices) {
10340 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10341 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10342 if (SVOp->getMask()[i] >= NumElements)
10343 NumV2OddIndices += i % 2;
10344 else if (SVOp->getMask()[i] >= 0)
10345 NumV1OddIndices += i % 2;
10346 if (NumV2OddIndices < NumV1OddIndices)
10347 return DAG.getCommutedVectorShuffle(*SVOp);
10352 // For each vector width, delegate to a specialized lowering routine.
10353 if (VT.getSizeInBits() == 128)
10354 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10356 if (VT.getSizeInBits() == 256)
10357 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10359 // Force AVX-512 vectors to be scalarized for now.
10360 // FIXME: Implement AVX-512 support!
10361 if (VT.getSizeInBits() == 512)
10362 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10364 llvm_unreachable("Unimplemented!");
10367 // This function assumes its argument is a BUILD_VECTOR of constants or
10368 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10370 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10371 unsigned &MaskValue) {
10373 unsigned NumElems = BuildVector->getNumOperands();
10374 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10375 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10376 unsigned NumElemsInLane = NumElems / NumLanes;
10378 // Blend for v16i16 should be symetric for the both lanes.
10379 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10380 SDValue EltCond = BuildVector->getOperand(i);
10381 SDValue SndLaneEltCond =
10382 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10384 int Lane1Cond = -1, Lane2Cond = -1;
10385 if (isa<ConstantSDNode>(EltCond))
10386 Lane1Cond = !isZero(EltCond);
10387 if (isa<ConstantSDNode>(SndLaneEltCond))
10388 Lane2Cond = !isZero(SndLaneEltCond);
10390 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10391 // Lane1Cond != 0, means we want the first argument.
10392 // Lane1Cond == 0, means we want the second argument.
10393 // The encoding of this argument is 0 for the first argument, 1
10394 // for the second. Therefore, invert the condition.
10395 MaskValue |= !Lane1Cond << i;
10396 else if (Lane1Cond < 0)
10397 MaskValue |= !Lane2Cond << i;
10404 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10405 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10406 const X86Subtarget *Subtarget,
10407 SelectionDAG &DAG) {
10408 SDValue Cond = Op.getOperand(0);
10409 SDValue LHS = Op.getOperand(1);
10410 SDValue RHS = Op.getOperand(2);
10412 MVT VT = Op.getSimpleValueType();
10414 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10416 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10418 // Only non-legal VSELECTs reach this lowering, convert those into generic
10419 // shuffles and re-use the shuffle lowering path for blends.
10420 SmallVector<int, 32> Mask;
10421 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10422 SDValue CondElt = CondBV->getOperand(i);
10424 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10426 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10429 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10430 // A vselect where all conditions and data are constants can be optimized into
10431 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10432 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10433 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10434 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10437 // Try to lower this to a blend-style vector shuffle. This can handle all
10438 // constant condition cases.
10439 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10442 // Variable blends are only legal from SSE4.1 onward.
10443 if (!Subtarget->hasSSE41())
10446 // Only some types will be legal on some subtargets. If we can emit a legal
10447 // VSELECT-matching blend, return Op, and but if we need to expand, return
10449 switch (Op.getSimpleValueType().SimpleTy) {
10451 // Most of the vector types have blends past SSE4.1.
10455 // The byte blends for AVX vectors were introduced only in AVX2.
10456 if (Subtarget->hasAVX2())
10463 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10464 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10467 // FIXME: We should custom lower this by fixing the condition and using i8
10473 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10474 MVT VT = Op.getSimpleValueType();
10477 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10480 if (VT.getSizeInBits() == 8) {
10481 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10482 Op.getOperand(0), Op.getOperand(1));
10483 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10484 DAG.getValueType(VT));
10485 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10488 if (VT.getSizeInBits() == 16) {
10489 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10490 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10492 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10493 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10494 DAG.getNode(ISD::BITCAST, dl,
10497 Op.getOperand(1)));
10498 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10499 Op.getOperand(0), Op.getOperand(1));
10500 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10501 DAG.getValueType(VT));
10502 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10505 if (VT == MVT::f32) {
10506 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10507 // the result back to FR32 register. It's only worth matching if the
10508 // result has a single use which is a store or a bitcast to i32. And in
10509 // the case of a store, it's not worth it if the index is a constant 0,
10510 // because a MOVSSmr can be used instead, which is smaller and faster.
10511 if (!Op.hasOneUse())
10513 SDNode *User = *Op.getNode()->use_begin();
10514 if ((User->getOpcode() != ISD::STORE ||
10515 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10516 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10517 (User->getOpcode() != ISD::BITCAST ||
10518 User->getValueType(0) != MVT::i32))
10520 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10521 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10524 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10527 if (VT == MVT::i32 || VT == MVT::i64) {
10528 // ExtractPS/pextrq works with constant index.
10529 if (isa<ConstantSDNode>(Op.getOperand(1)))
10535 /// Extract one bit from mask vector, like v16i1 or v8i1.
10536 /// AVX-512 feature.
10538 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10539 SDValue Vec = Op.getOperand(0);
10541 MVT VecVT = Vec.getSimpleValueType();
10542 SDValue Idx = Op.getOperand(1);
10543 MVT EltVT = Op.getSimpleValueType();
10545 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10546 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10547 "Unexpected vector type in ExtractBitFromMaskVector");
10549 // variable index can't be handled in mask registers,
10550 // extend vector to VR512
10551 if (!isa<ConstantSDNode>(Idx)) {
10552 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10553 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10554 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10555 ExtVT.getVectorElementType(), Ext, Idx);
10556 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10559 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10560 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10561 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10562 rc = getRegClassFor(MVT::v16i1);
10563 unsigned MaxSift = rc->getSize()*8 - 1;
10564 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10565 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10566 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10567 DAG.getConstant(MaxSift, dl, MVT::i8));
10568 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10569 DAG.getIntPtrConstant(0, dl));
10573 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10574 SelectionDAG &DAG) const {
10576 SDValue Vec = Op.getOperand(0);
10577 MVT VecVT = Vec.getSimpleValueType();
10578 SDValue Idx = Op.getOperand(1);
10580 if (Op.getSimpleValueType() == MVT::i1)
10581 return ExtractBitFromMaskVector(Op, DAG);
10583 if (!isa<ConstantSDNode>(Idx)) {
10584 if (VecVT.is512BitVector() ||
10585 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10586 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10589 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10590 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10591 MaskEltVT.getSizeInBits());
10593 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10594 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10595 getZeroVector(MaskVT, Subtarget, DAG, dl),
10596 Idx, DAG.getConstant(0, dl, getPointerTy()));
10597 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10598 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10599 Perm, DAG.getConstant(0, dl, getPointerTy()));
10604 // If this is a 256-bit vector result, first extract the 128-bit vector and
10605 // then extract the element from the 128-bit vector.
10606 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10608 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10609 // Get the 128-bit vector.
10610 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10611 MVT EltVT = VecVT.getVectorElementType();
10613 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10615 //if (IdxVal >= NumElems/2)
10616 // IdxVal -= NumElems/2;
10617 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10618 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10619 DAG.getConstant(IdxVal, dl, MVT::i32));
10622 assert(VecVT.is128BitVector() && "Unexpected vector length");
10624 if (Subtarget->hasSSE41()) {
10625 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10630 MVT VT = Op.getSimpleValueType();
10631 // TODO: handle v16i8.
10632 if (VT.getSizeInBits() == 16) {
10633 SDValue Vec = Op.getOperand(0);
10634 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10636 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10637 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10638 DAG.getNode(ISD::BITCAST, dl,
10640 Op.getOperand(1)));
10641 // Transform it so it match pextrw which produces a 32-bit result.
10642 MVT EltVT = MVT::i32;
10643 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10644 Op.getOperand(0), Op.getOperand(1));
10645 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10646 DAG.getValueType(VT));
10647 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10650 if (VT.getSizeInBits() == 32) {
10651 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10655 // SHUFPS the element to the lowest double word, then movss.
10656 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10657 MVT VVT = Op.getOperand(0).getSimpleValueType();
10658 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10659 DAG.getUNDEF(VVT), Mask);
10660 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10661 DAG.getIntPtrConstant(0, dl));
10664 if (VT.getSizeInBits() == 64) {
10665 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10666 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10667 // to match extract_elt for f64.
10668 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10672 // UNPCKHPD the element to the lowest double word, then movsd.
10673 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10674 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10675 int Mask[2] = { 1, -1 };
10676 MVT VVT = Op.getOperand(0).getSimpleValueType();
10677 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10678 DAG.getUNDEF(VVT), Mask);
10679 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10680 DAG.getIntPtrConstant(0, dl));
10686 /// Insert one bit to mask vector, like v16i1 or v8i1.
10687 /// AVX-512 feature.
10689 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10691 SDValue Vec = Op.getOperand(0);
10692 SDValue Elt = Op.getOperand(1);
10693 SDValue Idx = Op.getOperand(2);
10694 MVT VecVT = Vec.getSimpleValueType();
10696 if (!isa<ConstantSDNode>(Idx)) {
10697 // Non constant index. Extend source and destination,
10698 // insert element and then truncate the result.
10699 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10700 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10701 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10702 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10703 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10704 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10707 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10708 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10710 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10711 DAG.getConstant(IdxVal, dl, MVT::i8));
10712 if (Vec.getOpcode() == ISD::UNDEF)
10714 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10717 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10718 SelectionDAG &DAG) const {
10719 MVT VT = Op.getSimpleValueType();
10720 MVT EltVT = VT.getVectorElementType();
10722 if (EltVT == MVT::i1)
10723 return InsertBitToMaskVector(Op, DAG);
10726 SDValue N0 = Op.getOperand(0);
10727 SDValue N1 = Op.getOperand(1);
10728 SDValue N2 = Op.getOperand(2);
10729 if (!isa<ConstantSDNode>(N2))
10731 auto *N2C = cast<ConstantSDNode>(N2);
10732 unsigned IdxVal = N2C->getZExtValue();
10734 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10735 // into that, and then insert the subvector back into the result.
10736 if (VT.is256BitVector() || VT.is512BitVector()) {
10737 // With a 256-bit vector, we can insert into the zero element efficiently
10738 // using a blend if we have AVX or AVX2 and the right data type.
10739 if (VT.is256BitVector() && IdxVal == 0) {
10740 // TODO: It is worthwhile to cast integer to floating point and back
10741 // and incur a domain crossing penalty if that's what we'll end up
10742 // doing anyway after extracting to a 128-bit vector.
10743 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10744 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10745 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10746 N2 = DAG.getIntPtrConstant(1, dl);
10747 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10751 // Get the desired 128-bit vector chunk.
10752 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10754 // Insert the element into the desired chunk.
10755 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10756 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10758 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10759 DAG.getConstant(IdxIn128, dl, MVT::i32));
10761 // Insert the changed part back into the bigger vector
10762 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10764 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10766 if (Subtarget->hasSSE41()) {
10767 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10769 if (VT == MVT::v8i16) {
10770 Opc = X86ISD::PINSRW;
10772 assert(VT == MVT::v16i8);
10773 Opc = X86ISD::PINSRB;
10776 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10778 if (N1.getValueType() != MVT::i32)
10779 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10780 if (N2.getValueType() != MVT::i32)
10781 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10782 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10785 if (EltVT == MVT::f32) {
10786 // Bits [7:6] of the constant are the source select. This will always be
10787 // zero here. The DAG Combiner may combine an extract_elt index into
10788 // these bits. For example (insert (extract, 3), 2) could be matched by
10789 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10790 // Bits [5:4] of the constant are the destination select. This is the
10791 // value of the incoming immediate.
10792 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10793 // combine either bitwise AND or insert of float 0.0 to set these bits.
10795 const Function *F = DAG.getMachineFunction().getFunction();
10796 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10797 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10798 // If this is an insertion of 32-bits into the low 32-bits of
10799 // a vector, we prefer to generate a blend with immediate rather
10800 // than an insertps. Blends are simpler operations in hardware and so
10801 // will always have equal or better performance than insertps.
10802 // But if optimizing for size and there's a load folding opportunity,
10803 // generate insertps because blendps does not have a 32-bit memory
10805 N2 = DAG.getIntPtrConstant(1, dl);
10806 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10807 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10809 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10810 // Create this as a scalar to vector..
10811 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10812 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10815 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10816 // PINSR* works with constant index.
10821 if (EltVT == MVT::i8)
10824 if (EltVT.getSizeInBits() == 16) {
10825 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10826 // as its second argument.
10827 if (N1.getValueType() != MVT::i32)
10828 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10829 if (N2.getValueType() != MVT::i32)
10830 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10831 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10836 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10838 MVT OpVT = Op.getSimpleValueType();
10840 // If this is a 256-bit vector result, first insert into a 128-bit
10841 // vector and then insert into the 256-bit vector.
10842 if (!OpVT.is128BitVector()) {
10843 // Insert into a 128-bit vector.
10844 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10845 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10846 OpVT.getVectorNumElements() / SizeFactor);
10848 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10850 // Insert the 128-bit vector.
10851 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10854 if (OpVT == MVT::v1i64 &&
10855 Op.getOperand(0).getValueType() == MVT::i64)
10856 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10858 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10859 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10860 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10861 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10864 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10865 // a simple subregister reference or explicit instructions to grab
10866 // upper bits of a vector.
10867 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10868 SelectionDAG &DAG) {
10870 SDValue In = Op.getOperand(0);
10871 SDValue Idx = Op.getOperand(1);
10872 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10873 MVT ResVT = Op.getSimpleValueType();
10874 MVT InVT = In.getSimpleValueType();
10876 if (Subtarget->hasFp256()) {
10877 if (ResVT.is128BitVector() &&
10878 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10879 isa<ConstantSDNode>(Idx)) {
10880 return Extract128BitVector(In, IdxVal, DAG, dl);
10882 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10883 isa<ConstantSDNode>(Idx)) {
10884 return Extract256BitVector(In, IdxVal, DAG, dl);
10890 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10891 // simple superregister reference or explicit instructions to insert
10892 // the upper bits of a vector.
10893 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10894 SelectionDAG &DAG) {
10895 if (!Subtarget->hasAVX())
10899 SDValue Vec = Op.getOperand(0);
10900 SDValue SubVec = Op.getOperand(1);
10901 SDValue Idx = Op.getOperand(2);
10903 if (!isa<ConstantSDNode>(Idx))
10906 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10907 MVT OpVT = Op.getSimpleValueType();
10908 MVT SubVecVT = SubVec.getSimpleValueType();
10910 // Fold two 16-byte subvector loads into one 32-byte load:
10911 // (insert_subvector (insert_subvector undef, (load addr), 0),
10912 // (load addr + 16), Elts/2)
10914 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10915 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10916 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10917 !Subtarget->isUnalignedMem32Slow()) {
10918 SDValue SubVec2 = Vec.getOperand(1);
10919 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10920 if (Idx2->getZExtValue() == 0) {
10921 SDValue Ops[] = { SubVec2, SubVec };
10922 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10929 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10930 SubVecVT.is128BitVector())
10931 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10933 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10934 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10936 if (OpVT.getVectorElementType() == MVT::i1) {
10937 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10939 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10940 SDValue Undef = DAG.getUNDEF(OpVT);
10941 unsigned NumElems = OpVT.getVectorNumElements();
10942 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10944 if (IdxVal == OpVT.getVectorNumElements() / 2) {
10945 // Zero upper bits of the Vec
10946 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10947 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10949 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10951 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10952 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10955 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10957 // Zero upper bits of the Vec2
10958 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10959 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10960 // Zero lower bits of the Vec
10961 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10962 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10963 // Merge them together
10964 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10970 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10971 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10972 // one of the above mentioned nodes. It has to be wrapped because otherwise
10973 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10974 // be used to form addressing mode. These wrapped nodes will be selected
10977 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10978 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10980 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10981 // global base reg.
10982 unsigned char OpFlag = 0;
10983 unsigned WrapperKind = X86ISD::Wrapper;
10984 CodeModel::Model M = DAG.getTarget().getCodeModel();
10986 if (Subtarget->isPICStyleRIPRel() &&
10987 (M == CodeModel::Small || M == CodeModel::Kernel))
10988 WrapperKind = X86ISD::WrapperRIP;
10989 else if (Subtarget->isPICStyleGOT())
10990 OpFlag = X86II::MO_GOTOFF;
10991 else if (Subtarget->isPICStyleStubPIC())
10992 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10994 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10995 CP->getAlignment(),
10996 CP->getOffset(), OpFlag);
10998 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10999 // With PIC, the address is actually $g + Offset.
11001 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11002 DAG.getNode(X86ISD::GlobalBaseReg,
11003 SDLoc(), getPointerTy()),
11010 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11011 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11013 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11014 // global base reg.
11015 unsigned char OpFlag = 0;
11016 unsigned WrapperKind = X86ISD::Wrapper;
11017 CodeModel::Model M = DAG.getTarget().getCodeModel();
11019 if (Subtarget->isPICStyleRIPRel() &&
11020 (M == CodeModel::Small || M == CodeModel::Kernel))
11021 WrapperKind = X86ISD::WrapperRIP;
11022 else if (Subtarget->isPICStyleGOT())
11023 OpFlag = X86II::MO_GOTOFF;
11024 else if (Subtarget->isPICStyleStubPIC())
11025 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11027 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11030 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11032 // With PIC, the address is actually $g + Offset.
11034 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11035 DAG.getNode(X86ISD::GlobalBaseReg,
11036 SDLoc(), getPointerTy()),
11043 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11044 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11046 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11047 // global base reg.
11048 unsigned char OpFlag = 0;
11049 unsigned WrapperKind = X86ISD::Wrapper;
11050 CodeModel::Model M = DAG.getTarget().getCodeModel();
11052 if (Subtarget->isPICStyleRIPRel() &&
11053 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11054 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11055 OpFlag = X86II::MO_GOTPCREL;
11056 WrapperKind = X86ISD::WrapperRIP;
11057 } else if (Subtarget->isPICStyleGOT()) {
11058 OpFlag = X86II::MO_GOT;
11059 } else if (Subtarget->isPICStyleStubPIC()) {
11060 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11061 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11062 OpFlag = X86II::MO_DARWIN_NONLAZY;
11065 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11068 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11070 // With PIC, the address is actually $g + Offset.
11071 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11072 !Subtarget->is64Bit()) {
11073 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11074 DAG.getNode(X86ISD::GlobalBaseReg,
11075 SDLoc(), getPointerTy()),
11079 // For symbols that require a load from a stub to get the address, emit the
11081 if (isGlobalStubReference(OpFlag))
11082 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11083 MachinePointerInfo::getGOT(), false, false, false, 0);
11089 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11090 // Create the TargetBlockAddressAddress node.
11091 unsigned char OpFlags =
11092 Subtarget->ClassifyBlockAddressReference();
11093 CodeModel::Model M = DAG.getTarget().getCodeModel();
11094 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11095 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11097 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11100 if (Subtarget->isPICStyleRIPRel() &&
11101 (M == CodeModel::Small || M == CodeModel::Kernel))
11102 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11104 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11106 // With PIC, the address is actually $g + Offset.
11107 if (isGlobalRelativeToPICBase(OpFlags)) {
11108 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11109 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11117 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11118 int64_t Offset, SelectionDAG &DAG) const {
11119 // Create the TargetGlobalAddress node, folding in the constant
11120 // offset if it is legal.
11121 unsigned char OpFlags =
11122 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11123 CodeModel::Model M = DAG.getTarget().getCodeModel();
11125 if (OpFlags == X86II::MO_NO_FLAG &&
11126 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11127 // A direct static reference to a global.
11128 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11131 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11134 if (Subtarget->isPICStyleRIPRel() &&
11135 (M == CodeModel::Small || M == CodeModel::Kernel))
11136 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11138 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11140 // With PIC, the address is actually $g + Offset.
11141 if (isGlobalRelativeToPICBase(OpFlags)) {
11142 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11143 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11147 // For globals that require a load from a stub to get the address, emit the
11149 if (isGlobalStubReference(OpFlags))
11150 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11151 MachinePointerInfo::getGOT(), false, false, false, 0);
11153 // If there was a non-zero offset that we didn't fold, create an explicit
11154 // addition for it.
11156 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11157 DAG.getConstant(Offset, dl, getPointerTy()));
11163 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11164 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11165 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11166 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11170 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11171 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11172 unsigned char OperandFlags, bool LocalDynamic = false) {
11173 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11174 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11176 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11177 GA->getValueType(0),
11181 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11185 SDValue Ops[] = { Chain, TGA, *InFlag };
11186 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11188 SDValue Ops[] = { Chain, TGA };
11189 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11192 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11193 MFI->setAdjustsStack(true);
11194 MFI->setHasCalls(true);
11196 SDValue Flag = Chain.getValue(1);
11197 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11200 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11202 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11205 SDLoc dl(GA); // ? function entry point might be better
11206 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11207 DAG.getNode(X86ISD::GlobalBaseReg,
11208 SDLoc(), PtrVT), InFlag);
11209 InFlag = Chain.getValue(1);
11211 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11214 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11216 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11218 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11219 X86::RAX, X86II::MO_TLSGD);
11222 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11228 // Get the start address of the TLS block for this module.
11229 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11230 .getInfo<X86MachineFunctionInfo>();
11231 MFI->incNumLocalDynamicTLSAccesses();
11235 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11236 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11239 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11240 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11241 InFlag = Chain.getValue(1);
11242 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11243 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11246 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11250 unsigned char OperandFlags = X86II::MO_DTPOFF;
11251 unsigned WrapperKind = X86ISD::Wrapper;
11252 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11253 GA->getValueType(0),
11254 GA->getOffset(), OperandFlags);
11255 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11257 // Add x@dtpoff with the base.
11258 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11261 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11262 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11263 const EVT PtrVT, TLSModel::Model model,
11264 bool is64Bit, bool isPIC) {
11267 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11268 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11269 is64Bit ? 257 : 256));
11271 SDValue ThreadPointer =
11272 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11273 MachinePointerInfo(Ptr), false, false, false, 0);
11275 unsigned char OperandFlags = 0;
11276 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11278 unsigned WrapperKind = X86ISD::Wrapper;
11279 if (model == TLSModel::LocalExec) {
11280 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11281 } else if (model == TLSModel::InitialExec) {
11283 OperandFlags = X86II::MO_GOTTPOFF;
11284 WrapperKind = X86ISD::WrapperRIP;
11286 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11289 llvm_unreachable("Unexpected model");
11292 // emit "addl x@ntpoff,%eax" (local exec)
11293 // or "addl x@indntpoff,%eax" (initial exec)
11294 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11296 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11297 GA->getOffset(), OperandFlags);
11298 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11300 if (model == TLSModel::InitialExec) {
11301 if (isPIC && !is64Bit) {
11302 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11303 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11307 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11308 MachinePointerInfo::getGOT(), false, false, false, 0);
11311 // The address of the thread local variable is the add of the thread
11312 // pointer with the offset of the variable.
11313 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11317 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11319 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11320 const GlobalValue *GV = GA->getGlobal();
11322 if (Subtarget->isTargetELF()) {
11323 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11325 case TLSModel::GeneralDynamic:
11326 if (Subtarget->is64Bit())
11327 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11328 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11329 case TLSModel::LocalDynamic:
11330 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11331 Subtarget->is64Bit());
11332 case TLSModel::InitialExec:
11333 case TLSModel::LocalExec:
11334 return LowerToTLSExecModel(
11335 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11336 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11338 llvm_unreachable("Unknown TLS model.");
11341 if (Subtarget->isTargetDarwin()) {
11342 // Darwin only has one model of TLS. Lower to that.
11343 unsigned char OpFlag = 0;
11344 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11345 X86ISD::WrapperRIP : X86ISD::Wrapper;
11347 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11348 // global base reg.
11349 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11350 !Subtarget->is64Bit();
11352 OpFlag = X86II::MO_TLVP_PIC_BASE;
11354 OpFlag = X86II::MO_TLVP;
11356 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11357 GA->getValueType(0),
11358 GA->getOffset(), OpFlag);
11359 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11361 // With PIC32, the address is actually $g + Offset.
11363 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11364 DAG.getNode(X86ISD::GlobalBaseReg,
11365 SDLoc(), getPointerTy()),
11368 // Lowering the machine isd will make sure everything is in the right
11370 SDValue Chain = DAG.getEntryNode();
11371 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11372 SDValue Args[] = { Chain, Offset };
11373 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11375 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11376 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11377 MFI->setAdjustsStack(true);
11379 // And our return value (tls address) is in the standard call return value
11381 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11382 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11383 Chain.getValue(1));
11386 if (Subtarget->isTargetKnownWindowsMSVC() ||
11387 Subtarget->isTargetWindowsGNU()) {
11388 // Just use the implicit TLS architecture
11389 // Need to generate someting similar to:
11390 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11392 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11393 // mov rcx, qword [rdx+rcx*8]
11394 // mov eax, .tls$:tlsvar
11395 // [rax+rcx] contains the address
11396 // Windows 64bit: gs:0x58
11397 // Windows 32bit: fs:__tls_array
11400 SDValue Chain = DAG.getEntryNode();
11402 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11403 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11404 // use its literal value of 0x2C.
11405 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11406 ? Type::getInt8PtrTy(*DAG.getContext(),
11408 : Type::getInt32PtrTy(*DAG.getContext(),
11412 Subtarget->is64Bit()
11413 ? DAG.getIntPtrConstant(0x58, dl)
11414 : (Subtarget->isTargetWindowsGNU()
11415 ? DAG.getIntPtrConstant(0x2C, dl)
11416 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11418 SDValue ThreadPointer =
11419 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11420 MachinePointerInfo(Ptr), false, false, false, 0);
11423 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11424 res = ThreadPointer;
11426 // Load the _tls_index variable
11427 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11428 if (Subtarget->is64Bit())
11429 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11430 MachinePointerInfo(), MVT::i32, false, false,
11433 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11434 false, false, false, 0);
11436 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11438 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11440 res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11443 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11444 false, false, false, 0);
11446 // Get the offset of start of .tls section
11447 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11448 GA->getValueType(0),
11449 GA->getOffset(), X86II::MO_SECREL);
11450 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11452 // The address of the thread local variable is the add of the thread
11453 // pointer with the offset of the variable.
11454 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11457 llvm_unreachable("TLS not implemented for this target.");
11460 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11461 /// and take a 2 x i32 value to shift plus a shift amount.
11462 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11463 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11464 MVT VT = Op.getSimpleValueType();
11465 unsigned VTBits = VT.getSizeInBits();
11467 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11468 SDValue ShOpLo = Op.getOperand(0);
11469 SDValue ShOpHi = Op.getOperand(1);
11470 SDValue ShAmt = Op.getOperand(2);
11471 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11472 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11474 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11475 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11476 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11477 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11478 : DAG.getConstant(0, dl, VT);
11480 SDValue Tmp2, Tmp3;
11481 if (Op.getOpcode() == ISD::SHL_PARTS) {
11482 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11483 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11485 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11486 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11489 // If the shift amount is larger or equal than the width of a part we can't
11490 // rely on the results of shld/shrd. Insert a test and select the appropriate
11491 // values for large shift amounts.
11492 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11493 DAG.getConstant(VTBits, dl, MVT::i8));
11494 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11495 AndNode, DAG.getConstant(0, dl, MVT::i8));
11498 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11499 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11500 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11502 if (Op.getOpcode() == ISD::SHL_PARTS) {
11503 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11504 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11506 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11507 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11510 SDValue Ops[2] = { Lo, Hi };
11511 return DAG.getMergeValues(Ops, dl);
11514 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11515 SelectionDAG &DAG) const {
11516 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11519 if (SrcVT.isVector()) {
11520 if (SrcVT.getVectorElementType() == MVT::i1) {
11521 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11522 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11523 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11524 Op.getOperand(0)));
11529 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11530 "Unknown SINT_TO_FP to lower!");
11532 // These are really Legal; return the operand so the caller accepts it as
11534 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11536 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11537 Subtarget->is64Bit()) {
11541 unsigned Size = SrcVT.getSizeInBits()/8;
11542 MachineFunction &MF = DAG.getMachineFunction();
11543 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11544 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11545 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11547 MachinePointerInfo::getFixedStack(SSFI),
11549 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11552 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11554 SelectionDAG &DAG) const {
11558 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11560 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11562 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11564 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11566 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11567 MachineMemOperand *MMO;
11569 int SSFI = FI->getIndex();
11571 DAG.getMachineFunction()
11572 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11573 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11575 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11576 StackSlot = StackSlot.getOperand(1);
11578 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11579 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11581 Tys, Ops, SrcVT, MMO);
11584 Chain = Result.getValue(1);
11585 SDValue InFlag = Result.getValue(2);
11587 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11588 // shouldn't be necessary except that RFP cannot be live across
11589 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11590 MachineFunction &MF = DAG.getMachineFunction();
11591 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11592 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11593 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11594 Tys = DAG.getVTList(MVT::Other);
11596 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11598 MachineMemOperand *MMO =
11599 DAG.getMachineFunction()
11600 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11601 MachineMemOperand::MOStore, SSFISize, SSFISize);
11603 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11604 Ops, Op.getValueType(), MMO);
11605 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11606 MachinePointerInfo::getFixedStack(SSFI),
11607 false, false, false, 0);
11613 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11614 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11615 SelectionDAG &DAG) const {
11616 // This algorithm is not obvious. Here it is what we're trying to output:
11619 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11620 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11622 haddpd %xmm0, %xmm0
11624 pshufd $0x4e, %xmm0, %xmm1
11630 LLVMContext *Context = DAG.getContext();
11632 // Build some magic constants.
11633 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11634 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11635 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11637 SmallVector<Constant*,2> CV1;
11639 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11640 APInt(64, 0x4330000000000000ULL))));
11642 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11643 APInt(64, 0x4530000000000000ULL))));
11644 Constant *C1 = ConstantVector::get(CV1);
11645 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11647 // Load the 64-bit value into an XMM register.
11648 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11650 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11651 MachinePointerInfo::getConstantPool(),
11652 false, false, false, 16);
11653 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11654 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11657 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11658 MachinePointerInfo::getConstantPool(),
11659 false, false, false, 16);
11660 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11661 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11664 if (Subtarget->hasSSE3()) {
11665 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11666 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11668 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11669 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11671 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11672 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11676 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11677 DAG.getIntPtrConstant(0, dl));
11680 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11681 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11682 SelectionDAG &DAG) const {
11684 // FP constant to bias correct the final result.
11685 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11688 // Load the 32-bit value into an XMM register.
11689 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11692 // Zero out the upper parts of the register.
11693 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11695 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11696 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11697 DAG.getIntPtrConstant(0, dl));
11699 // Or the load with the bias.
11700 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11701 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11702 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11703 MVT::v2f64, Load)),
11704 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11705 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11706 MVT::v2f64, Bias)));
11707 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11708 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11709 DAG.getIntPtrConstant(0, dl));
11711 // Subtract the bias.
11712 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11714 // Handle final rounding.
11715 EVT DestVT = Op.getValueType();
11717 if (DestVT.bitsLT(MVT::f64))
11718 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11719 DAG.getIntPtrConstant(0, dl));
11720 if (DestVT.bitsGT(MVT::f64))
11721 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11723 // Handle final rounding.
11727 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11728 const X86Subtarget &Subtarget) {
11729 // The algorithm is the following:
11730 // #ifdef __SSE4_1__
11731 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11732 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11733 // (uint4) 0x53000000, 0xaa);
11735 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11736 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11738 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11739 // return (float4) lo + fhi;
11742 SDValue V = Op->getOperand(0);
11743 EVT VecIntVT = V.getValueType();
11744 bool Is128 = VecIntVT == MVT::v4i32;
11745 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11746 // If we convert to something else than the supported type, e.g., to v4f64,
11748 if (VecFloatVT != Op->getValueType(0))
11751 unsigned NumElts = VecIntVT.getVectorNumElements();
11752 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11753 "Unsupported custom type");
11754 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11756 // In the #idef/#else code, we have in common:
11757 // - The vector of constants:
11763 // Create the splat vector for 0x4b000000.
11764 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11765 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11766 CstLow, CstLow, CstLow, CstLow};
11767 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11768 makeArrayRef(&CstLowArray[0], NumElts));
11769 // Create the splat vector for 0x53000000.
11770 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11771 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11772 CstHigh, CstHigh, CstHigh, CstHigh};
11773 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11774 makeArrayRef(&CstHighArray[0], NumElts));
11776 // Create the right shift.
11777 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11778 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11779 CstShift, CstShift, CstShift, CstShift};
11780 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11781 makeArrayRef(&CstShiftArray[0], NumElts));
11782 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11785 if (Subtarget.hasSSE41()) {
11786 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11787 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11788 SDValue VecCstLowBitcast =
11789 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11790 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11791 // Low will be bitcasted right away, so do not bother bitcasting back to its
11793 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11794 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11795 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11796 // (uint4) 0x53000000, 0xaa);
11797 SDValue VecCstHighBitcast =
11798 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11799 SDValue VecShiftBitcast =
11800 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11801 // High will be bitcasted right away, so do not bother bitcasting back to
11802 // its original type.
11803 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11804 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11806 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11807 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11808 CstMask, CstMask, CstMask);
11809 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11810 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11811 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11813 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11814 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11817 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11818 SDValue CstFAdd = DAG.getConstantFP(
11819 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11820 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11821 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11822 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11823 makeArrayRef(&CstFAddArray[0], NumElts));
11825 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11826 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11828 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11829 // return (float4) lo + fhi;
11830 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11831 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11834 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11835 SelectionDAG &DAG) const {
11836 SDValue N0 = Op.getOperand(0);
11837 MVT SVT = N0.getSimpleValueType();
11840 switch (SVT.SimpleTy) {
11842 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11847 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11848 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11849 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11853 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11856 if (Subtarget->hasAVX512())
11857 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11858 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11860 llvm_unreachable(nullptr);
11863 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11864 SelectionDAG &DAG) const {
11865 SDValue N0 = Op.getOperand(0);
11868 if (Op.getValueType().isVector())
11869 return lowerUINT_TO_FP_vec(Op, DAG);
11871 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11872 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11873 // the optimization here.
11874 if (DAG.SignBitIsZero(N0))
11875 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11877 MVT SrcVT = N0.getSimpleValueType();
11878 MVT DstVT = Op.getSimpleValueType();
11879 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11880 return LowerUINT_TO_FP_i64(Op, DAG);
11881 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11882 return LowerUINT_TO_FP_i32(Op, DAG);
11883 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11886 // Make a 64-bit buffer, and use it to build an FILD.
11887 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11888 if (SrcVT == MVT::i32) {
11889 SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11890 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11891 getPointerTy(), StackSlot, WordOff);
11892 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11893 StackSlot, MachinePointerInfo(),
11895 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11896 OffsetSlot, MachinePointerInfo(),
11898 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11902 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11903 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11904 StackSlot, MachinePointerInfo(),
11906 // For i64 source, we need to add the appropriate power of 2 if the input
11907 // was negative. This is the same as the optimization in
11908 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11909 // we must be careful to do the computation in x87 extended precision, not
11910 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11911 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11912 MachineMemOperand *MMO =
11913 DAG.getMachineFunction()
11914 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11915 MachineMemOperand::MOLoad, 8, 8);
11917 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11918 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11919 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11922 APInt FF(32, 0x5F800000ULL);
11924 // Check whether the sign bit is set.
11925 SDValue SignSet = DAG.getSetCC(dl,
11926 getSetCCResultType(*DAG.getContext(), MVT::i64),
11928 DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11930 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11931 SDValue FudgePtr = DAG.getConstantPool(
11932 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11935 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11936 SDValue Zero = DAG.getIntPtrConstant(0, dl);
11937 SDValue Four = DAG.getIntPtrConstant(4, dl);
11938 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11940 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11942 // Load the value out, extending it from f32 to f80.
11943 // FIXME: Avoid the extend by constructing the right constant pool?
11944 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11945 FudgePtr, MachinePointerInfo::getConstantPool(),
11946 MVT::f32, false, false, false, 4);
11947 // Extend everything to 80 bits to force it to be done on x87.
11948 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11949 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11950 DAG.getIntPtrConstant(0, dl));
11953 std::pair<SDValue,SDValue>
11954 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11955 bool IsSigned, bool IsReplace) const {
11958 EVT DstTy = Op.getValueType();
11960 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11961 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11965 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11966 DstTy.getSimpleVT() >= MVT::i16 &&
11967 "Unknown FP_TO_INT to lower!");
11969 // These are really Legal.
11970 if (DstTy == MVT::i32 &&
11971 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11972 return std::make_pair(SDValue(), SDValue());
11973 if (Subtarget->is64Bit() &&
11974 DstTy == MVT::i64 &&
11975 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11976 return std::make_pair(SDValue(), SDValue());
11978 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11979 // stack slot, or into the FTOL runtime function.
11980 MachineFunction &MF = DAG.getMachineFunction();
11981 unsigned MemSize = DstTy.getSizeInBits()/8;
11982 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11983 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11986 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11987 Opc = X86ISD::WIN_FTOL;
11989 switch (DstTy.getSimpleVT().SimpleTy) {
11990 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11991 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11992 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11993 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11996 SDValue Chain = DAG.getEntryNode();
11997 SDValue Value = Op.getOperand(0);
11998 EVT TheVT = Op.getOperand(0).getValueType();
11999 // FIXME This causes a redundant load/store if the SSE-class value is already
12000 // in memory, such as if it is on the callstack.
12001 if (isScalarFPTypeInSSEReg(TheVT)) {
12002 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12003 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12004 MachinePointerInfo::getFixedStack(SSFI),
12006 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12008 Chain, StackSlot, DAG.getValueType(TheVT)
12011 MachineMemOperand *MMO =
12012 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12013 MachineMemOperand::MOLoad, MemSize, MemSize);
12014 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12015 Chain = Value.getValue(1);
12016 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12017 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12020 MachineMemOperand *MMO =
12021 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12022 MachineMemOperand::MOStore, MemSize, MemSize);
12024 if (Opc != X86ISD::WIN_FTOL) {
12025 // Build the FP_TO_INT*_IN_MEM
12026 SDValue Ops[] = { Chain, Value, StackSlot };
12027 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12029 return std::make_pair(FIST, StackSlot);
12031 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12032 DAG.getVTList(MVT::Other, MVT::Glue),
12034 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12035 MVT::i32, ftol.getValue(1));
12036 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12037 MVT::i32, eax.getValue(2));
12038 SDValue Ops[] = { eax, edx };
12039 SDValue pair = IsReplace
12040 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12041 : DAG.getMergeValues(Ops, DL);
12042 return std::make_pair(pair, SDValue());
12046 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12047 const X86Subtarget *Subtarget) {
12048 MVT VT = Op->getSimpleValueType(0);
12049 SDValue In = Op->getOperand(0);
12050 MVT InVT = In.getSimpleValueType();
12053 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12054 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12056 // Optimize vectors in AVX mode:
12059 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12060 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12061 // Concat upper and lower parts.
12064 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12065 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12066 // Concat upper and lower parts.
12069 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12070 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12071 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12074 if (Subtarget->hasInt256())
12075 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12077 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12078 SDValue Undef = DAG.getUNDEF(InVT);
12079 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12080 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12081 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12083 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12084 VT.getVectorNumElements()/2);
12086 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12087 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12089 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12092 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12093 SelectionDAG &DAG) {
12094 MVT VT = Op->getSimpleValueType(0);
12095 SDValue In = Op->getOperand(0);
12096 MVT InVT = In.getSimpleValueType();
12098 unsigned int NumElts = VT.getVectorNumElements();
12099 if (NumElts != 8 && NumElts != 16)
12102 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12103 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12105 assert(InVT.getVectorElementType() == MVT::i1);
12106 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12108 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12110 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12112 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12113 if (VT.is512BitVector())
12115 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12118 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12119 SelectionDAG &DAG) {
12120 if (Subtarget->hasFp256()) {
12121 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12129 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12130 SelectionDAG &DAG) {
12132 MVT VT = Op.getSimpleValueType();
12133 SDValue In = Op.getOperand(0);
12134 MVT SVT = In.getSimpleValueType();
12136 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12137 return LowerZERO_EXTEND_AVX512(Op, DAG);
12139 if (Subtarget->hasFp256()) {
12140 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12145 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12146 VT.getVectorNumElements() != SVT.getVectorNumElements());
12150 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12152 MVT VT = Op.getSimpleValueType();
12153 SDValue In = Op.getOperand(0);
12154 MVT InVT = In.getSimpleValueType();
12156 if (VT == MVT::i1) {
12157 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12158 "Invalid scalar TRUNCATE operation");
12159 if (InVT.getSizeInBits() >= 32)
12161 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12162 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12164 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12165 "Invalid TRUNCATE operation");
12167 // move vector to mask - truncate solution for SKX
12168 if (VT.getVectorElementType() == MVT::i1) {
12169 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12170 Subtarget->hasBWI())
12171 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12172 if ((InVT.is256BitVector() || InVT.is128BitVector())
12173 && InVT.getScalarSizeInBits() <= 16 &&
12174 Subtarget->hasBWI() && Subtarget->hasVLX())
12175 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12176 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12177 Subtarget->hasDQI())
12178 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12179 if ((InVT.is256BitVector() || InVT.is128BitVector())
12180 && InVT.getScalarSizeInBits() >= 32 &&
12181 Subtarget->hasDQI() && Subtarget->hasVLX())
12182 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12184 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12185 if (VT.getVectorElementType().getSizeInBits() >=8)
12186 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12188 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12189 unsigned NumElts = InVT.getVectorNumElements();
12190 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12191 if (InVT.getSizeInBits() < 512) {
12192 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12193 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12198 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12199 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12200 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12203 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12204 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12205 if (Subtarget->hasInt256()) {
12206 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12207 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12208 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12210 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12211 DAG.getIntPtrConstant(0, DL));
12214 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12215 DAG.getIntPtrConstant(0, DL));
12216 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12217 DAG.getIntPtrConstant(2, DL));
12218 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12219 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12220 static const int ShufMask[] = {0, 2, 4, 6};
12221 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12224 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12225 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12226 if (Subtarget->hasInt256()) {
12227 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12229 SmallVector<SDValue,32> pshufbMask;
12230 for (unsigned i = 0; i < 2; ++i) {
12231 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12232 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12233 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12234 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12235 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12236 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12237 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12238 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12239 for (unsigned j = 0; j < 8; ++j)
12240 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12242 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12243 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12244 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12246 static const int ShufMask[] = {0, 2, -1, -1};
12247 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12249 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12250 DAG.getIntPtrConstant(0, DL));
12251 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12254 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12255 DAG.getIntPtrConstant(0, DL));
12257 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12258 DAG.getIntPtrConstant(4, DL));
12260 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12261 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12263 // The PSHUFB mask:
12264 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12265 -1, -1, -1, -1, -1, -1, -1, -1};
12267 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12268 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12269 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12271 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12272 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12274 // The MOVLHPS Mask:
12275 static const int ShufMask2[] = {0, 1, 4, 5};
12276 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12277 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12280 // Handle truncation of V256 to V128 using shuffles.
12281 if (!VT.is128BitVector() || !InVT.is256BitVector())
12284 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12286 unsigned NumElems = VT.getVectorNumElements();
12287 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12289 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12290 // Prepare truncation shuffle mask
12291 for (unsigned i = 0; i != NumElems; ++i)
12292 MaskVec[i] = i * 2;
12293 SDValue V = DAG.getVectorShuffle(NVT, DL,
12294 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12295 DAG.getUNDEF(NVT), &MaskVec[0]);
12296 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12297 DAG.getIntPtrConstant(0, DL));
12300 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12301 SelectionDAG &DAG) const {
12302 assert(!Op.getSimpleValueType().isVector());
12304 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12305 /*IsSigned=*/ true, /*IsReplace=*/ false);
12306 SDValue FIST = Vals.first, StackSlot = Vals.second;
12307 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12308 if (!FIST.getNode()) return Op;
12310 if (StackSlot.getNode())
12311 // Load the result.
12312 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12313 FIST, StackSlot, MachinePointerInfo(),
12314 false, false, false, 0);
12316 // The node is the result.
12320 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12321 SelectionDAG &DAG) const {
12322 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12323 /*IsSigned=*/ false, /*IsReplace=*/ false);
12324 SDValue FIST = Vals.first, StackSlot = Vals.second;
12325 assert(FIST.getNode() && "Unexpected failure");
12327 if (StackSlot.getNode())
12328 // Load the result.
12329 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12330 FIST, StackSlot, MachinePointerInfo(),
12331 false, false, false, 0);
12333 // The node is the result.
12337 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12339 MVT VT = Op.getSimpleValueType();
12340 SDValue In = Op.getOperand(0);
12341 MVT SVT = In.getSimpleValueType();
12343 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12345 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12346 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12347 In, DAG.getUNDEF(SVT)));
12350 /// The only differences between FABS and FNEG are the mask and the logic op.
12351 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12352 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12353 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12354 "Wrong opcode for lowering FABS or FNEG.");
12356 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12358 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12359 // into an FNABS. We'll lower the FABS after that if it is still in use.
12361 for (SDNode *User : Op->uses())
12362 if (User->getOpcode() == ISD::FNEG)
12365 SDValue Op0 = Op.getOperand(0);
12366 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12369 MVT VT = Op.getSimpleValueType();
12370 // Assume scalar op for initialization; update for vector if needed.
12371 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12372 // generate a 16-byte vector constant and logic op even for the scalar case.
12373 // Using a 16-byte mask allows folding the load of the mask with
12374 // the logic op, so it can save (~4 bytes) on code size.
12376 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12377 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12378 // decide if we should generate a 16-byte constant mask when we only need 4 or
12379 // 8 bytes for the scalar case.
12380 if (VT.isVector()) {
12381 EltVT = VT.getVectorElementType();
12382 NumElts = VT.getVectorNumElements();
12385 unsigned EltBits = EltVT.getSizeInBits();
12386 LLVMContext *Context = DAG.getContext();
12387 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12389 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12390 Constant *C = ConstantInt::get(*Context, MaskElt);
12391 C = ConstantVector::getSplat(NumElts, C);
12392 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12393 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12394 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12395 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12396 MachinePointerInfo::getConstantPool(),
12397 false, false, false, Alignment);
12399 if (VT.isVector()) {
12400 // For a vector, cast operands to a vector type, perform the logic op,
12401 // and cast the result back to the original value type.
12402 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12403 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12404 SDValue Operand = IsFNABS ?
12405 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12406 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12407 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12408 return DAG.getNode(ISD::BITCAST, dl, VT,
12409 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12412 // If not vector, then scalar.
12413 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12414 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12415 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12418 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12420 LLVMContext *Context = DAG.getContext();
12421 SDValue Op0 = Op.getOperand(0);
12422 SDValue Op1 = Op.getOperand(1);
12424 MVT VT = Op.getSimpleValueType();
12425 MVT SrcVT = Op1.getSimpleValueType();
12427 // If second operand is smaller, extend it first.
12428 if (SrcVT.bitsLT(VT)) {
12429 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12432 // And if it is bigger, shrink it first.
12433 if (SrcVT.bitsGT(VT)) {
12434 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12438 // At this point the operands and the result should have the same
12439 // type, and that won't be f80 since that is not custom lowered.
12441 const fltSemantics &Sem =
12442 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12443 const unsigned SizeInBits = VT.getSizeInBits();
12445 SmallVector<Constant *, 4> CV(
12446 VT == MVT::f64 ? 2 : 4,
12447 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12449 // First, clear all bits but the sign bit from the second operand (sign).
12450 CV[0] = ConstantFP::get(*Context,
12451 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12452 Constant *C = ConstantVector::get(CV);
12453 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12454 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12455 MachinePointerInfo::getConstantPool(),
12456 false, false, false, 16);
12457 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12459 // Next, clear the sign bit from the first operand (magnitude).
12460 // If it's a constant, we can clear it here.
12461 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12462 APFloat APF = Op0CN->getValueAPF();
12463 // If the magnitude is a positive zero, the sign bit alone is enough.
12464 if (APF.isPosZero())
12467 CV[0] = ConstantFP::get(*Context, APF);
12469 CV[0] = ConstantFP::get(
12471 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12473 C = ConstantVector::get(CV);
12474 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12475 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12476 MachinePointerInfo::getConstantPool(),
12477 false, false, false, 16);
12478 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12479 if (!isa<ConstantFPSDNode>(Op0))
12480 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12482 // OR the magnitude value with the sign bit.
12483 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12486 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12487 SDValue N0 = Op.getOperand(0);
12489 MVT VT = Op.getSimpleValueType();
12491 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12492 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12493 DAG.getConstant(1, dl, VT));
12494 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12497 // Check whether an OR'd tree is PTEST-able.
12498 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12499 SelectionDAG &DAG) {
12500 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12502 if (!Subtarget->hasSSE41())
12505 if (!Op->hasOneUse())
12508 SDNode *N = Op.getNode();
12511 SmallVector<SDValue, 8> Opnds;
12512 DenseMap<SDValue, unsigned> VecInMap;
12513 SmallVector<SDValue, 8> VecIns;
12514 EVT VT = MVT::Other;
12516 // Recognize a special case where a vector is casted into wide integer to
12518 Opnds.push_back(N->getOperand(0));
12519 Opnds.push_back(N->getOperand(1));
12521 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12522 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12523 // BFS traverse all OR'd operands.
12524 if (I->getOpcode() == ISD::OR) {
12525 Opnds.push_back(I->getOperand(0));
12526 Opnds.push_back(I->getOperand(1));
12527 // Re-evaluate the number of nodes to be traversed.
12528 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12532 // Quit if a non-EXTRACT_VECTOR_ELT
12533 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12536 // Quit if without a constant index.
12537 SDValue Idx = I->getOperand(1);
12538 if (!isa<ConstantSDNode>(Idx))
12541 SDValue ExtractedFromVec = I->getOperand(0);
12542 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12543 if (M == VecInMap.end()) {
12544 VT = ExtractedFromVec.getValueType();
12545 // Quit if not 128/256-bit vector.
12546 if (!VT.is128BitVector() && !VT.is256BitVector())
12548 // Quit if not the same type.
12549 if (VecInMap.begin() != VecInMap.end() &&
12550 VT != VecInMap.begin()->first.getValueType())
12552 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12553 VecIns.push_back(ExtractedFromVec);
12555 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12558 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12559 "Not extracted from 128-/256-bit vector.");
12561 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12563 for (DenseMap<SDValue, unsigned>::const_iterator
12564 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12565 // Quit if not all elements are used.
12566 if (I->second != FullMask)
12570 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12572 // Cast all vectors into TestVT for PTEST.
12573 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12574 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12576 // If more than one full vectors are evaluated, OR them first before PTEST.
12577 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12578 // Each iteration will OR 2 nodes and append the result until there is only
12579 // 1 node left, i.e. the final OR'd value of all vectors.
12580 SDValue LHS = VecIns[Slot];
12581 SDValue RHS = VecIns[Slot + 1];
12582 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12585 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12586 VecIns.back(), VecIns.back());
12589 /// \brief return true if \c Op has a use that doesn't just read flags.
12590 static bool hasNonFlagsUse(SDValue Op) {
12591 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12593 SDNode *User = *UI;
12594 unsigned UOpNo = UI.getOperandNo();
12595 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12596 // Look pass truncate.
12597 UOpNo = User->use_begin().getOperandNo();
12598 User = *User->use_begin();
12601 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12602 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12608 /// Emit nodes that will be selected as "test Op0,Op0", or something
12610 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12611 SelectionDAG &DAG) const {
12612 if (Op.getValueType() == MVT::i1) {
12613 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12614 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12615 DAG.getConstant(0, dl, MVT::i8));
12617 // CF and OF aren't always set the way we want. Determine which
12618 // of these we need.
12619 bool NeedCF = false;
12620 bool NeedOF = false;
12623 case X86::COND_A: case X86::COND_AE:
12624 case X86::COND_B: case X86::COND_BE:
12627 case X86::COND_G: case X86::COND_GE:
12628 case X86::COND_L: case X86::COND_LE:
12629 case X86::COND_O: case X86::COND_NO: {
12630 // Check if we really need to set the
12631 // Overflow flag. If NoSignedWrap is present
12632 // that is not actually needed.
12633 switch (Op->getOpcode()) {
12638 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12639 if (BinNode->Flags.hasNoSignedWrap())
12649 // See if we can use the EFLAGS value from the operand instead of
12650 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12651 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12652 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12653 // Emit a CMP with 0, which is the TEST pattern.
12654 //if (Op.getValueType() == MVT::i1)
12655 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12656 // DAG.getConstant(0, MVT::i1));
12657 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12658 DAG.getConstant(0, dl, Op.getValueType()));
12660 unsigned Opcode = 0;
12661 unsigned NumOperands = 0;
12663 // Truncate operations may prevent the merge of the SETCC instruction
12664 // and the arithmetic instruction before it. Attempt to truncate the operands
12665 // of the arithmetic instruction and use a reduced bit-width instruction.
12666 bool NeedTruncation = false;
12667 SDValue ArithOp = Op;
12668 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12669 SDValue Arith = Op->getOperand(0);
12670 // Both the trunc and the arithmetic op need to have one user each.
12671 if (Arith->hasOneUse())
12672 switch (Arith.getOpcode()) {
12679 NeedTruncation = true;
12685 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12686 // which may be the result of a CAST. We use the variable 'Op', which is the
12687 // non-casted variable when we check for possible users.
12688 switch (ArithOp.getOpcode()) {
12690 // Due to an isel shortcoming, be conservative if this add is likely to be
12691 // selected as part of a load-modify-store instruction. When the root node
12692 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12693 // uses of other nodes in the match, such as the ADD in this case. This
12694 // leads to the ADD being left around and reselected, with the result being
12695 // two adds in the output. Alas, even if none our users are stores, that
12696 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12697 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12698 // climbing the DAG back to the root, and it doesn't seem to be worth the
12700 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12701 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12702 if (UI->getOpcode() != ISD::CopyToReg &&
12703 UI->getOpcode() != ISD::SETCC &&
12704 UI->getOpcode() != ISD::STORE)
12707 if (ConstantSDNode *C =
12708 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12709 // An add of one will be selected as an INC.
12710 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12711 Opcode = X86ISD::INC;
12716 // An add of negative one (subtract of one) will be selected as a DEC.
12717 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12718 Opcode = X86ISD::DEC;
12724 // Otherwise use a regular EFLAGS-setting add.
12725 Opcode = X86ISD::ADD;
12730 // If we have a constant logical shift that's only used in a comparison
12731 // against zero turn it into an equivalent AND. This allows turning it into
12732 // a TEST instruction later.
12733 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12734 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12735 EVT VT = Op.getValueType();
12736 unsigned BitWidth = VT.getSizeInBits();
12737 unsigned ShAmt = Op->getConstantOperandVal(1);
12738 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12740 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12741 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12742 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12743 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12745 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12746 DAG.getConstant(Mask, dl, VT));
12747 DAG.ReplaceAllUsesWith(Op, New);
12753 // If the primary and result isn't used, don't bother using X86ISD::AND,
12754 // because a TEST instruction will be better.
12755 if (!hasNonFlagsUse(Op))
12761 // Due to the ISEL shortcoming noted above, be conservative if this op is
12762 // likely to be selected as part of a load-modify-store instruction.
12763 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12764 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12765 if (UI->getOpcode() == ISD::STORE)
12768 // Otherwise use a regular EFLAGS-setting instruction.
12769 switch (ArithOp.getOpcode()) {
12770 default: llvm_unreachable("unexpected operator!");
12771 case ISD::SUB: Opcode = X86ISD::SUB; break;
12772 case ISD::XOR: Opcode = X86ISD::XOR; break;
12773 case ISD::AND: Opcode = X86ISD::AND; break;
12775 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12776 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12777 if (EFLAGS.getNode())
12780 Opcode = X86ISD::OR;
12794 return SDValue(Op.getNode(), 1);
12800 // If we found that truncation is beneficial, perform the truncation and
12802 if (NeedTruncation) {
12803 EVT VT = Op.getValueType();
12804 SDValue WideVal = Op->getOperand(0);
12805 EVT WideVT = WideVal.getValueType();
12806 unsigned ConvertedOp = 0;
12807 // Use a target machine opcode to prevent further DAGCombine
12808 // optimizations that may separate the arithmetic operations
12809 // from the setcc node.
12810 switch (WideVal.getOpcode()) {
12812 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12813 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12814 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12815 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12816 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12820 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12821 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12822 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12823 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12824 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12830 // Emit a CMP with 0, which is the TEST pattern.
12831 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12832 DAG.getConstant(0, dl, Op.getValueType()));
12834 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12835 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12837 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12838 DAG.ReplaceAllUsesWith(Op, New);
12839 return SDValue(New.getNode(), 1);
12842 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12844 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12845 SDLoc dl, SelectionDAG &DAG) const {
12846 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12847 if (C->getAPIntValue() == 0)
12848 return EmitTest(Op0, X86CC, dl, DAG);
12850 if (Op0.getValueType() == MVT::i1)
12851 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12854 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12855 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12856 // Do the comparison at i32 if it's smaller, besides the Atom case.
12857 // This avoids subregister aliasing issues. Keep the smaller reference
12858 // if we're optimizing for size, however, as that'll allow better folding
12859 // of memory operations.
12860 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12861 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12862 Attribute::MinSize) &&
12863 !Subtarget->isAtom()) {
12864 unsigned ExtendOp =
12865 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12866 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12867 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12869 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12870 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12871 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12873 return SDValue(Sub.getNode(), 1);
12875 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12878 /// Convert a comparison if required by the subtarget.
12879 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12880 SelectionDAG &DAG) const {
12881 // If the subtarget does not support the FUCOMI instruction, floating-point
12882 // comparisons have to be converted.
12883 if (Subtarget->hasCMov() ||
12884 Cmp.getOpcode() != X86ISD::CMP ||
12885 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12886 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12889 // The instruction selector will select an FUCOM instruction instead of
12890 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12891 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12892 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12894 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12895 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12896 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12897 DAG.getConstant(8, dl, MVT::i8));
12898 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12899 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12902 /// The minimum architected relative accuracy is 2^-12. We need one
12903 /// Newton-Raphson step to have a good float result (24 bits of precision).
12904 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12905 DAGCombinerInfo &DCI,
12906 unsigned &RefinementSteps,
12907 bool &UseOneConstNR) const {
12908 // FIXME: We should use instruction latency models to calculate the cost of
12909 // each potential sequence, but this is very hard to do reliably because
12910 // at least Intel's Core* chips have variable timing based on the number of
12911 // significant digits in the divisor and/or sqrt operand.
12912 if (!Subtarget->useSqrtEst())
12915 EVT VT = Op.getValueType();
12917 // SSE1 has rsqrtss and rsqrtps.
12918 // TODO: Add support for AVX512 (v16f32).
12919 // It is likely not profitable to do this for f64 because a double-precision
12920 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12921 // instructions: convert to single, rsqrtss, convert back to double, refine
12922 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12923 // along with FMA, this could be a throughput win.
12924 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12925 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12926 RefinementSteps = 1;
12927 UseOneConstNR = false;
12928 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12933 /// The minimum architected relative accuracy is 2^-12. We need one
12934 /// Newton-Raphson step to have a good float result (24 bits of precision).
12935 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12936 DAGCombinerInfo &DCI,
12937 unsigned &RefinementSteps) const {
12938 // FIXME: We should use instruction latency models to calculate the cost of
12939 // each potential sequence, but this is very hard to do reliably because
12940 // at least Intel's Core* chips have variable timing based on the number of
12941 // significant digits in the divisor.
12942 if (!Subtarget->useReciprocalEst())
12945 EVT VT = Op.getValueType();
12947 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12948 // TODO: Add support for AVX512 (v16f32).
12949 // It is likely not profitable to do this for f64 because a double-precision
12950 // reciprocal estimate with refinement on x86 prior to FMA requires
12951 // 15 instructions: convert to single, rcpss, convert back to double, refine
12952 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12953 // along with FMA, this could be a throughput win.
12954 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12955 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12956 RefinementSteps = ReciprocalEstimateRefinementSteps;
12957 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12962 /// If we have at least two divisions that use the same divisor, convert to
12963 /// multplication by a reciprocal. This may need to be adjusted for a given
12964 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12965 /// This is because we still need one division to calculate the reciprocal and
12966 /// then we need two multiplies by that reciprocal as replacements for the
12967 /// original divisions.
12968 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12969 return NumUsers > 1;
12972 static bool isAllOnes(SDValue V) {
12973 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12974 return C && C->isAllOnesValue();
12977 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12978 /// if it's possible.
12979 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12980 SDLoc dl, SelectionDAG &DAG) const {
12981 SDValue Op0 = And.getOperand(0);
12982 SDValue Op1 = And.getOperand(1);
12983 if (Op0.getOpcode() == ISD::TRUNCATE)
12984 Op0 = Op0.getOperand(0);
12985 if (Op1.getOpcode() == ISD::TRUNCATE)
12986 Op1 = Op1.getOperand(0);
12989 if (Op1.getOpcode() == ISD::SHL)
12990 std::swap(Op0, Op1);
12991 if (Op0.getOpcode() == ISD::SHL) {
12992 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12993 if (And00C->getZExtValue() == 1) {
12994 // If we looked past a truncate, check that it's only truncating away
12996 unsigned BitWidth = Op0.getValueSizeInBits();
12997 unsigned AndBitWidth = And.getValueSizeInBits();
12998 if (BitWidth > AndBitWidth) {
13000 DAG.computeKnownBits(Op0, Zeros, Ones);
13001 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13005 RHS = Op0.getOperand(1);
13007 } else if (Op1.getOpcode() == ISD::Constant) {
13008 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13009 uint64_t AndRHSVal = AndRHS->getZExtValue();
13010 SDValue AndLHS = Op0;
13012 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13013 LHS = AndLHS.getOperand(0);
13014 RHS = AndLHS.getOperand(1);
13017 // Use BT if the immediate can't be encoded in a TEST instruction.
13018 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13020 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13024 if (LHS.getNode()) {
13025 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13026 // instruction. Since the shift amount is in-range-or-undefined, we know
13027 // that doing a bittest on the i32 value is ok. We extend to i32 because
13028 // the encoding for the i16 version is larger than the i32 version.
13029 // Also promote i16 to i32 for performance / code size reason.
13030 if (LHS.getValueType() == MVT::i8 ||
13031 LHS.getValueType() == MVT::i16)
13032 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13034 // If the operand types disagree, extend the shift amount to match. Since
13035 // BT ignores high bits (like shifts) we can use anyextend.
13036 if (LHS.getValueType() != RHS.getValueType())
13037 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13039 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13040 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13041 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13042 DAG.getConstant(Cond, dl, MVT::i8), BT);
13048 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13050 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13055 // SSE Condition code mapping:
13064 switch (SetCCOpcode) {
13065 default: llvm_unreachable("Unexpected SETCC condition");
13067 case ISD::SETEQ: SSECC = 0; break;
13069 case ISD::SETGT: Swap = true; // Fallthrough
13071 case ISD::SETOLT: SSECC = 1; break;
13073 case ISD::SETGE: Swap = true; // Fallthrough
13075 case ISD::SETOLE: SSECC = 2; break;
13076 case ISD::SETUO: SSECC = 3; break;
13078 case ISD::SETNE: SSECC = 4; break;
13079 case ISD::SETULE: Swap = true; // Fallthrough
13080 case ISD::SETUGE: SSECC = 5; break;
13081 case ISD::SETULT: Swap = true; // Fallthrough
13082 case ISD::SETUGT: SSECC = 6; break;
13083 case ISD::SETO: SSECC = 7; break;
13085 case ISD::SETONE: SSECC = 8; break;
13088 std::swap(Op0, Op1);
13093 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13094 // ones, and then concatenate the result back.
13095 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13096 MVT VT = Op.getSimpleValueType();
13098 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13099 "Unsupported value type for operation");
13101 unsigned NumElems = VT.getVectorNumElements();
13103 SDValue CC = Op.getOperand(2);
13105 // Extract the LHS vectors
13106 SDValue LHS = Op.getOperand(0);
13107 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13108 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13110 // Extract the RHS vectors
13111 SDValue RHS = Op.getOperand(1);
13112 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13113 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13115 // Issue the operation on the smaller types and concatenate the result back
13116 MVT EltVT = VT.getVectorElementType();
13117 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13118 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13119 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13120 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13123 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13124 SDValue Op0 = Op.getOperand(0);
13125 SDValue Op1 = Op.getOperand(1);
13126 SDValue CC = Op.getOperand(2);
13127 MVT VT = Op.getSimpleValueType();
13130 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13131 "Unexpected type for boolean compare operation");
13132 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13133 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13134 DAG.getConstant(-1, dl, VT));
13135 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13136 DAG.getConstant(-1, dl, VT));
13137 switch (SetCCOpcode) {
13138 default: llvm_unreachable("Unexpected SETCC condition");
13140 // (x != y) -> ~(x ^ y)
13141 return DAG.getNode(ISD::XOR, dl, VT,
13142 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13143 DAG.getConstant(-1, dl, VT));
13145 // (x == y) -> (x ^ y)
13146 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13149 // (x > y) -> (x & ~y)
13150 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13153 // (x < y) -> (~x & y)
13154 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13157 // (x <= y) -> (~x | y)
13158 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13161 // (x >=y) -> (x | ~y)
13162 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13166 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13167 const X86Subtarget *Subtarget) {
13168 SDValue Op0 = Op.getOperand(0);
13169 SDValue Op1 = Op.getOperand(1);
13170 SDValue CC = Op.getOperand(2);
13171 MVT VT = Op.getSimpleValueType();
13174 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13175 Op.getValueType().getScalarType() == MVT::i1 &&
13176 "Cannot set masked compare for this operation");
13178 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13180 bool Unsigned = false;
13183 switch (SetCCOpcode) {
13184 default: llvm_unreachable("Unexpected SETCC condition");
13185 case ISD::SETNE: SSECC = 4; break;
13186 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13187 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13188 case ISD::SETLT: Swap = true; //fall-through
13189 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13190 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13191 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13192 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13193 case ISD::SETULE: Unsigned = true; //fall-through
13194 case ISD::SETLE: SSECC = 2; break;
13198 std::swap(Op0, Op1);
13200 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13201 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13202 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13203 DAG.getConstant(SSECC, dl, MVT::i8));
13206 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13207 /// operand \p Op1. If non-trivial (for example because it's not constant)
13208 /// return an empty value.
13209 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13211 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13215 MVT VT = Op1.getSimpleValueType();
13216 MVT EVT = VT.getVectorElementType();
13217 unsigned n = VT.getVectorNumElements();
13218 SmallVector<SDValue, 8> ULTOp1;
13220 for (unsigned i = 0; i < n; ++i) {
13221 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13222 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13225 // Avoid underflow.
13226 APInt Val = Elt->getAPIntValue();
13230 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13233 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13236 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13237 SelectionDAG &DAG) {
13238 SDValue Op0 = Op.getOperand(0);
13239 SDValue Op1 = Op.getOperand(1);
13240 SDValue CC = Op.getOperand(2);
13241 MVT VT = Op.getSimpleValueType();
13242 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13243 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13248 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13249 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13252 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13253 unsigned Opc = X86ISD::CMPP;
13254 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13255 assert(VT.getVectorNumElements() <= 16);
13256 Opc = X86ISD::CMPM;
13258 // In the two special cases we can't handle, emit two comparisons.
13261 unsigned CombineOpc;
13262 if (SetCCOpcode == ISD::SETUEQ) {
13263 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13265 assert(SetCCOpcode == ISD::SETONE);
13266 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13269 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13270 DAG.getConstant(CC0, dl, MVT::i8));
13271 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13272 DAG.getConstant(CC1, dl, MVT::i8));
13273 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13275 // Handle all other FP comparisons here.
13276 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13277 DAG.getConstant(SSECC, dl, MVT::i8));
13280 // Break 256-bit integer vector compare into smaller ones.
13281 if (VT.is256BitVector() && !Subtarget->hasInt256())
13282 return Lower256IntVSETCC(Op, DAG);
13284 EVT OpVT = Op1.getValueType();
13285 if (OpVT.getVectorElementType() == MVT::i1)
13286 return LowerBoolVSETCC_AVX512(Op, DAG);
13288 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13289 if (Subtarget->hasAVX512()) {
13290 if (Op1.getValueType().is512BitVector() ||
13291 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13292 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13293 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13295 // In AVX-512 architecture setcc returns mask with i1 elements,
13296 // But there is no compare instruction for i8 and i16 elements in KNL.
13297 // We are not talking about 512-bit operands in this case, these
13298 // types are illegal.
13300 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13301 OpVT.getVectorElementType().getSizeInBits() >= 8))
13302 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13303 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13306 // We are handling one of the integer comparisons here. Since SSE only has
13307 // GT and EQ comparisons for integer, swapping operands and multiple
13308 // operations may be required for some comparisons.
13310 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13311 bool Subus = false;
13313 switch (SetCCOpcode) {
13314 default: llvm_unreachable("Unexpected SETCC condition");
13315 case ISD::SETNE: Invert = true;
13316 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13317 case ISD::SETLT: Swap = true;
13318 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13319 case ISD::SETGE: Swap = true;
13320 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13321 Invert = true; break;
13322 case ISD::SETULT: Swap = true;
13323 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13324 FlipSigns = true; break;
13325 case ISD::SETUGE: Swap = true;
13326 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13327 FlipSigns = true; Invert = true; break;
13330 // Special case: Use min/max operations for SETULE/SETUGE
13331 MVT VET = VT.getVectorElementType();
13333 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13334 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13337 switch (SetCCOpcode) {
13339 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13340 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13343 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13346 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13347 if (!MinMax && hasSubus) {
13348 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13350 // t = psubus Op0, Op1
13351 // pcmpeq t, <0..0>
13352 switch (SetCCOpcode) {
13354 case ISD::SETULT: {
13355 // If the comparison is against a constant we can turn this into a
13356 // setule. With psubus, setule does not require a swap. This is
13357 // beneficial because the constant in the register is no longer
13358 // destructed as the destination so it can be hoisted out of a loop.
13359 // Only do this pre-AVX since vpcmp* is no longer destructive.
13360 if (Subtarget->hasAVX())
13362 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13363 if (ULEOp1.getNode()) {
13365 Subus = true; Invert = false; Swap = false;
13369 // Psubus is better than flip-sign because it requires no inversion.
13370 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13371 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13375 Opc = X86ISD::SUBUS;
13381 std::swap(Op0, Op1);
13383 // Check that the operation in question is available (most are plain SSE2,
13384 // but PCMPGTQ and PCMPEQQ have different requirements).
13385 if (VT == MVT::v2i64) {
13386 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13387 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13389 // First cast everything to the right type.
13390 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13391 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13393 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13394 // bits of the inputs before performing those operations. The lower
13395 // compare is always unsigned.
13398 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13400 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13401 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13402 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13403 Sign, Zero, Sign, Zero);
13405 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13406 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13408 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13409 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13410 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13412 // Create masks for only the low parts/high parts of the 64 bit integers.
13413 static const int MaskHi[] = { 1, 1, 3, 3 };
13414 static const int MaskLo[] = { 0, 0, 2, 2 };
13415 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13416 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13417 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13419 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13420 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13423 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13425 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13428 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13429 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13430 // pcmpeqd + pshufd + pand.
13431 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13433 // First cast everything to the right type.
13434 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13435 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13438 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13440 // Make sure the lower and upper halves are both all-ones.
13441 static const int Mask[] = { 1, 0, 3, 2 };
13442 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13443 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13446 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13448 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13452 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13453 // bits of the inputs before performing those operations.
13455 EVT EltVT = VT.getVectorElementType();
13456 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13458 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13459 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13462 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13464 // If the logical-not of the result is required, perform that now.
13466 Result = DAG.getNOT(dl, Result, VT);
13469 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13472 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13473 getZeroVector(VT, Subtarget, DAG, dl));
13478 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13480 MVT VT = Op.getSimpleValueType();
13482 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13484 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13485 && "SetCC type must be 8-bit or 1-bit integer");
13486 SDValue Op0 = Op.getOperand(0);
13487 SDValue Op1 = Op.getOperand(1);
13489 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13491 // Optimize to BT if possible.
13492 // Lower (X & (1 << N)) == 0 to BT(X, N).
13493 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13494 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13495 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13496 Op1.getOpcode() == ISD::Constant &&
13497 cast<ConstantSDNode>(Op1)->isNullValue() &&
13498 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13499 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13500 if (NewSetCC.getNode()) {
13502 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13507 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13509 if (Op1.getOpcode() == ISD::Constant &&
13510 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13511 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13512 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13514 // If the input is a setcc, then reuse the input setcc or use a new one with
13515 // the inverted condition.
13516 if (Op0.getOpcode() == X86ISD::SETCC) {
13517 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13518 bool Invert = (CC == ISD::SETNE) ^
13519 cast<ConstantSDNode>(Op1)->isNullValue();
13523 CCode = X86::GetOppositeBranchCondition(CCode);
13524 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13525 DAG.getConstant(CCode, dl, MVT::i8),
13526 Op0.getOperand(1));
13528 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13532 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13533 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13534 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13536 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13537 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13540 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13541 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13542 if (X86CC == X86::COND_INVALID)
13545 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13546 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13547 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13548 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13550 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13554 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13555 static bool isX86LogicalCmp(SDValue Op) {
13556 unsigned Opc = Op.getNode()->getOpcode();
13557 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13558 Opc == X86ISD::SAHF)
13560 if (Op.getResNo() == 1 &&
13561 (Opc == X86ISD::ADD ||
13562 Opc == X86ISD::SUB ||
13563 Opc == X86ISD::ADC ||
13564 Opc == X86ISD::SBB ||
13565 Opc == X86ISD::SMUL ||
13566 Opc == X86ISD::UMUL ||
13567 Opc == X86ISD::INC ||
13568 Opc == X86ISD::DEC ||
13569 Opc == X86ISD::OR ||
13570 Opc == X86ISD::XOR ||
13571 Opc == X86ISD::AND))
13574 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13580 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13581 if (V.getOpcode() != ISD::TRUNCATE)
13584 SDValue VOp0 = V.getOperand(0);
13585 unsigned InBits = VOp0.getValueSizeInBits();
13586 unsigned Bits = V.getValueSizeInBits();
13587 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13590 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13591 bool addTest = true;
13592 SDValue Cond = Op.getOperand(0);
13593 SDValue Op1 = Op.getOperand(1);
13594 SDValue Op2 = Op.getOperand(2);
13596 EVT VT = Op1.getValueType();
13599 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13600 // are available or VBLENDV if AVX is available.
13601 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13602 if (Cond.getOpcode() == ISD::SETCC &&
13603 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13604 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13605 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13606 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13607 int SSECC = translateX86FSETCC(
13608 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13611 if (Subtarget->hasAVX512()) {
13612 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13613 DAG.getConstant(SSECC, DL, MVT::i8));
13614 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13617 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13618 DAG.getConstant(SSECC, DL, MVT::i8));
13620 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13621 // of 3 logic instructions for size savings and potentially speed.
13622 // Unfortunately, there is no scalar form of VBLENDV.
13624 // If either operand is a constant, don't try this. We can expect to
13625 // optimize away at least one of the logic instructions later in that
13626 // case, so that sequence would be faster than a variable blend.
13628 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13629 // uses XMM0 as the selection register. That may need just as many
13630 // instructions as the AND/ANDN/OR sequence due to register moves, so
13633 if (Subtarget->hasAVX() &&
13634 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13636 // Convert to vectors, do a VSELECT, and convert back to scalar.
13637 // All of the conversions should be optimized away.
13639 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13640 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13641 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13642 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13644 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13645 VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13647 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13649 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13650 VSel, DAG.getIntPtrConstant(0, DL));
13652 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13653 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13654 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13658 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13660 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13661 Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13662 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13663 Op1Scalar = Op1.getOperand(0);
13665 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13666 Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13667 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13668 Op2Scalar = Op2.getOperand(0);
13669 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13670 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13671 Op1Scalar.getValueType(),
13672 Cond, Op1Scalar, Op2Scalar);
13673 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13674 return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13675 SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13676 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13677 DAG.getIntPtrConstant(0, DL));
13681 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13682 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13683 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13684 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13685 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13686 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13687 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13689 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13692 if (Cond.getOpcode() == ISD::SETCC) {
13693 SDValue NewCond = LowerSETCC(Cond, DAG);
13694 if (NewCond.getNode())
13698 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13699 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13700 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13701 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13702 if (Cond.getOpcode() == X86ISD::SETCC &&
13703 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13704 isZero(Cond.getOperand(1).getOperand(1))) {
13705 SDValue Cmp = Cond.getOperand(1);
13707 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13709 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13710 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13711 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13713 SDValue CmpOp0 = Cmp.getOperand(0);
13714 // Apply further optimizations for special cases
13715 // (select (x != 0), -1, 0) -> neg & sbb
13716 // (select (x == 0), 0, -1) -> neg & sbb
13717 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13718 if (YC->isNullValue() &&
13719 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13720 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13721 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13722 DAG.getConstant(0, DL,
13723 CmpOp0.getValueType()),
13725 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13726 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13727 SDValue(Neg.getNode(), 1));
13731 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13732 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13733 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13735 SDValue Res = // Res = 0 or -1.
13736 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13737 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13739 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13740 Res = DAG.getNOT(DL, Res, Res.getValueType());
13742 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13743 if (!N2C || !N2C->isNullValue())
13744 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13749 // Look past (and (setcc_carry (cmp ...)), 1).
13750 if (Cond.getOpcode() == ISD::AND &&
13751 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13752 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13753 if (C && C->getAPIntValue() == 1)
13754 Cond = Cond.getOperand(0);
13757 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13758 // setting operand in place of the X86ISD::SETCC.
13759 unsigned CondOpcode = Cond.getOpcode();
13760 if (CondOpcode == X86ISD::SETCC ||
13761 CondOpcode == X86ISD::SETCC_CARRY) {
13762 CC = Cond.getOperand(0);
13764 SDValue Cmp = Cond.getOperand(1);
13765 unsigned Opc = Cmp.getOpcode();
13766 MVT VT = Op.getSimpleValueType();
13768 bool IllegalFPCMov = false;
13769 if (VT.isFloatingPoint() && !VT.isVector() &&
13770 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13771 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13773 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13774 Opc == X86ISD::BT) { // FIXME
13778 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13779 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13780 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13781 Cond.getOperand(0).getValueType() != MVT::i8)) {
13782 SDValue LHS = Cond.getOperand(0);
13783 SDValue RHS = Cond.getOperand(1);
13784 unsigned X86Opcode;
13787 switch (CondOpcode) {
13788 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13789 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13790 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13791 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13792 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13793 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13794 default: llvm_unreachable("unexpected overflowing operator");
13796 if (CondOpcode == ISD::UMULO)
13797 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13800 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13802 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13804 if (CondOpcode == ISD::UMULO)
13805 Cond = X86Op.getValue(2);
13807 Cond = X86Op.getValue(1);
13809 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13814 // Look pass the truncate if the high bits are known zero.
13815 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13816 Cond = Cond.getOperand(0);
13818 // We know the result of AND is compared against zero. Try to match
13820 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13821 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13822 if (NewSetCC.getNode()) {
13823 CC = NewSetCC.getOperand(0);
13824 Cond = NewSetCC.getOperand(1);
13831 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13832 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13835 // a < b ? -1 : 0 -> RES = ~setcc_carry
13836 // a < b ? 0 : -1 -> RES = setcc_carry
13837 // a >= b ? -1 : 0 -> RES = setcc_carry
13838 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13839 if (Cond.getOpcode() == X86ISD::SUB) {
13840 Cond = ConvertCmpIfNecessary(Cond, DAG);
13841 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13843 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13844 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13845 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13846 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13848 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13849 return DAG.getNOT(DL, Res, Res.getValueType());
13854 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13855 // widen the cmov and push the truncate through. This avoids introducing a new
13856 // branch during isel and doesn't add any extensions.
13857 if (Op.getValueType() == MVT::i8 &&
13858 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13859 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13860 if (T1.getValueType() == T2.getValueType() &&
13861 // Blacklist CopyFromReg to avoid partial register stalls.
13862 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13863 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13864 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13865 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13869 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13870 // condition is true.
13871 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13872 SDValue Ops[] = { Op2, Op1, CC, Cond };
13873 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13876 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13877 SelectionDAG &DAG) {
13878 MVT VT = Op->getSimpleValueType(0);
13879 SDValue In = Op->getOperand(0);
13880 MVT InVT = In.getSimpleValueType();
13881 MVT VTElt = VT.getVectorElementType();
13882 MVT InVTElt = InVT.getVectorElementType();
13886 if ((InVTElt == MVT::i1) &&
13887 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13888 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13890 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13891 VTElt.getSizeInBits() <= 16)) ||
13893 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13894 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13896 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13897 VTElt.getSizeInBits() >= 32))))
13898 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13900 unsigned int NumElts = VT.getVectorNumElements();
13902 if (NumElts != 8 && NumElts != 16)
13905 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13906 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13907 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13908 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13911 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13912 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13914 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13917 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13919 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13920 if (VT.is512BitVector())
13922 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13925 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
13926 const X86Subtarget *Subtarget,
13927 SelectionDAG &DAG) {
13928 SDValue In = Op->getOperand(0);
13929 MVT VT = Op->getSimpleValueType(0);
13930 MVT InVT = In.getSimpleValueType();
13931 assert(VT.getSizeInBits() == InVT.getSizeInBits());
13933 MVT InSVT = InVT.getScalarType();
13934 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
13936 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13938 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
13943 // SSE41 targets can use the pmovsx* instructions directly.
13944 if (Subtarget->hasSSE41())
13945 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13947 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
13951 // As SRAI is only available on i16/i32 types, we expand only up to i32
13952 // and handle i64 separately.
13953 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
13954 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
13955 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
13956 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
13957 Curr = DAG.getNode(ISD::BITCAST, dl, CurrVT, Curr);
13960 SDValue SignExt = Curr;
13961 if (CurrVT != InVT) {
13962 unsigned SignExtShift =
13963 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
13964 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13965 DAG.getConstant(SignExtShift, dl, MVT::i8));
13971 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
13972 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13973 DAG.getConstant(31, dl, MVT::i8));
13974 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
13975 return DAG.getNode(ISD::BITCAST, dl, VT, Ext);
13981 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13982 SelectionDAG &DAG) {
13983 MVT VT = Op->getSimpleValueType(0);
13984 SDValue In = Op->getOperand(0);
13985 MVT InVT = In.getSimpleValueType();
13988 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13989 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13991 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13992 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13993 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13996 if (Subtarget->hasInt256())
13997 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13999 // Optimize vectors in AVX mode
14000 // Sign extend v8i16 to v8i32 and
14003 // Divide input vector into two parts
14004 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14005 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14006 // concat the vectors to original VT
14008 unsigned NumElems = InVT.getVectorNumElements();
14009 SDValue Undef = DAG.getUNDEF(InVT);
14011 SmallVector<int,8> ShufMask1(NumElems, -1);
14012 for (unsigned i = 0; i != NumElems/2; ++i)
14015 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14017 SmallVector<int,8> ShufMask2(NumElems, -1);
14018 for (unsigned i = 0; i != NumElems/2; ++i)
14019 ShufMask2[i] = i + NumElems/2;
14021 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14023 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14024 VT.getVectorNumElements()/2);
14026 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14027 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14029 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14032 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14033 // may emit an illegal shuffle but the expansion is still better than scalar
14034 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14035 // we'll emit a shuffle and a arithmetic shift.
14036 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14037 // TODO: It is possible to support ZExt by zeroing the undef values during
14038 // the shuffle phase or after the shuffle.
14039 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14040 SelectionDAG &DAG) {
14041 MVT RegVT = Op.getSimpleValueType();
14042 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14043 assert(RegVT.isInteger() &&
14044 "We only custom lower integer vector sext loads.");
14046 // Nothing useful we can do without SSE2 shuffles.
14047 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14049 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14051 EVT MemVT = Ld->getMemoryVT();
14052 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14053 unsigned RegSz = RegVT.getSizeInBits();
14055 ISD::LoadExtType Ext = Ld->getExtensionType();
14057 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14058 && "Only anyext and sext are currently implemented.");
14059 assert(MemVT != RegVT && "Cannot extend to the same type");
14060 assert(MemVT.isVector() && "Must load a vector from memory");
14062 unsigned NumElems = RegVT.getVectorNumElements();
14063 unsigned MemSz = MemVT.getSizeInBits();
14064 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14066 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14067 // The only way in which we have a legal 256-bit vector result but not the
14068 // integer 256-bit operations needed to directly lower a sextload is if we
14069 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14070 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14071 // correctly legalized. We do this late to allow the canonical form of
14072 // sextload to persist throughout the rest of the DAG combiner -- it wants
14073 // to fold together any extensions it can, and so will fuse a sign_extend
14074 // of an sextload into a sextload targeting a wider value.
14076 if (MemSz == 128) {
14077 // Just switch this to a normal load.
14078 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14079 "it must be a legal 128-bit vector "
14081 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14082 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14083 Ld->isInvariant(), Ld->getAlignment());
14085 assert(MemSz < 128 &&
14086 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14087 // Do an sext load to a 128-bit vector type. We want to use the same
14088 // number of elements, but elements half as wide. This will end up being
14089 // recursively lowered by this routine, but will succeed as we definitely
14090 // have all the necessary features if we're using AVX1.
14092 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14093 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14095 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14096 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14097 Ld->isNonTemporal(), Ld->isInvariant(),
14098 Ld->getAlignment());
14101 // Replace chain users with the new chain.
14102 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14103 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14105 // Finally, do a normal sign-extend to the desired register.
14106 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14109 // All sizes must be a power of two.
14110 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14111 "Non-power-of-two elements are not custom lowered!");
14113 // Attempt to load the original value using scalar loads.
14114 // Find the largest scalar type that divides the total loaded size.
14115 MVT SclrLoadTy = MVT::i8;
14116 for (MVT Tp : MVT::integer_valuetypes()) {
14117 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14122 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14123 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14125 SclrLoadTy = MVT::f64;
14127 // Calculate the number of scalar loads that we need to perform
14128 // in order to load our vector from memory.
14129 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14131 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14132 "Can only lower sext loads with a single scalar load!");
14134 unsigned loadRegZize = RegSz;
14135 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14138 // Represent our vector as a sequence of elements which are the
14139 // largest scalar that we can load.
14140 EVT LoadUnitVecVT = EVT::getVectorVT(
14141 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14143 // Represent the data using the same element type that is stored in
14144 // memory. In practice, we ''widen'' MemVT.
14146 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14147 loadRegZize / MemVT.getScalarType().getSizeInBits());
14149 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14150 "Invalid vector type");
14152 // We can't shuffle using an illegal type.
14153 assert(TLI.isTypeLegal(WideVecVT) &&
14154 "We only lower types that form legal widened vector types");
14156 SmallVector<SDValue, 8> Chains;
14157 SDValue Ptr = Ld->getBasePtr();
14158 SDValue Increment =
14159 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14160 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14162 for (unsigned i = 0; i < NumLoads; ++i) {
14163 // Perform a single load.
14164 SDValue ScalarLoad =
14165 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14166 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14167 Ld->getAlignment());
14168 Chains.push_back(ScalarLoad.getValue(1));
14169 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14170 // another round of DAGCombining.
14172 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14174 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14175 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14177 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14180 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14182 // Bitcast the loaded value to a vector of the original element type, in
14183 // the size of the target vector type.
14184 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14185 unsigned SizeRatio = RegSz / MemSz;
14187 if (Ext == ISD::SEXTLOAD) {
14188 // If we have SSE4.1, we can directly emit a VSEXT node.
14189 if (Subtarget->hasSSE41()) {
14190 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14191 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14195 // Otherwise we'll shuffle the small elements in the high bits of the
14196 // larger type and perform an arithmetic shift. If the shift is not legal
14197 // it's better to scalarize.
14198 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14199 "We can't implement a sext load without an arithmetic right shift!");
14201 // Redistribute the loaded elements into the different locations.
14202 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14203 for (unsigned i = 0; i != NumElems; ++i)
14204 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14206 SDValue Shuff = DAG.getVectorShuffle(
14207 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14209 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14211 // Build the arithmetic shift.
14212 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14213 MemVT.getVectorElementType().getSizeInBits();
14215 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14216 DAG.getConstant(Amt, dl, RegVT));
14218 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14222 // Redistribute the loaded elements into the different locations.
14223 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14224 for (unsigned i = 0; i != NumElems; ++i)
14225 ShuffleVec[i * SizeRatio] = i;
14227 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14228 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14230 // Bitcast to the requested type.
14231 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14232 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14236 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14237 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14238 // from the AND / OR.
14239 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14240 Opc = Op.getOpcode();
14241 if (Opc != ISD::OR && Opc != ISD::AND)
14243 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14244 Op.getOperand(0).hasOneUse() &&
14245 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14246 Op.getOperand(1).hasOneUse());
14249 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14250 // 1 and that the SETCC node has a single use.
14251 static bool isXor1OfSetCC(SDValue Op) {
14252 if (Op.getOpcode() != ISD::XOR)
14254 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14255 if (N1C && N1C->getAPIntValue() == 1) {
14256 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14257 Op.getOperand(0).hasOneUse();
14262 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14263 bool addTest = true;
14264 SDValue Chain = Op.getOperand(0);
14265 SDValue Cond = Op.getOperand(1);
14266 SDValue Dest = Op.getOperand(2);
14269 bool Inverted = false;
14271 if (Cond.getOpcode() == ISD::SETCC) {
14272 // Check for setcc([su]{add,sub,mul}o == 0).
14273 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14274 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14275 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14276 Cond.getOperand(0).getResNo() == 1 &&
14277 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14278 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14279 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14280 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14281 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14282 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14284 Cond = Cond.getOperand(0);
14286 SDValue NewCond = LowerSETCC(Cond, DAG);
14287 if (NewCond.getNode())
14292 // FIXME: LowerXALUO doesn't handle these!!
14293 else if (Cond.getOpcode() == X86ISD::ADD ||
14294 Cond.getOpcode() == X86ISD::SUB ||
14295 Cond.getOpcode() == X86ISD::SMUL ||
14296 Cond.getOpcode() == X86ISD::UMUL)
14297 Cond = LowerXALUO(Cond, DAG);
14300 // Look pass (and (setcc_carry (cmp ...)), 1).
14301 if (Cond.getOpcode() == ISD::AND &&
14302 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14303 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14304 if (C && C->getAPIntValue() == 1)
14305 Cond = Cond.getOperand(0);
14308 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14309 // setting operand in place of the X86ISD::SETCC.
14310 unsigned CondOpcode = Cond.getOpcode();
14311 if (CondOpcode == X86ISD::SETCC ||
14312 CondOpcode == X86ISD::SETCC_CARRY) {
14313 CC = Cond.getOperand(0);
14315 SDValue Cmp = Cond.getOperand(1);
14316 unsigned Opc = Cmp.getOpcode();
14317 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14318 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14322 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14326 // These can only come from an arithmetic instruction with overflow,
14327 // e.g. SADDO, UADDO.
14328 Cond = Cond.getNode()->getOperand(1);
14334 CondOpcode = Cond.getOpcode();
14335 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14336 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14337 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14338 Cond.getOperand(0).getValueType() != MVT::i8)) {
14339 SDValue LHS = Cond.getOperand(0);
14340 SDValue RHS = Cond.getOperand(1);
14341 unsigned X86Opcode;
14344 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14345 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14347 switch (CondOpcode) {
14348 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14350 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14352 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14355 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14356 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14358 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14360 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14363 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14364 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14365 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14366 default: llvm_unreachable("unexpected overflowing operator");
14369 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14370 if (CondOpcode == ISD::UMULO)
14371 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14374 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14376 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14378 if (CondOpcode == ISD::UMULO)
14379 Cond = X86Op.getValue(2);
14381 Cond = X86Op.getValue(1);
14383 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14387 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14388 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14389 if (CondOpc == ISD::OR) {
14390 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14391 // two branches instead of an explicit OR instruction with a
14393 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14394 isX86LogicalCmp(Cmp)) {
14395 CC = Cond.getOperand(0).getOperand(0);
14396 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14397 Chain, Dest, CC, Cmp);
14398 CC = Cond.getOperand(1).getOperand(0);
14402 } else { // ISD::AND
14403 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14404 // two branches instead of an explicit AND instruction with a
14405 // separate test. However, we only do this if this block doesn't
14406 // have a fall-through edge, because this requires an explicit
14407 // jmp when the condition is false.
14408 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14409 isX86LogicalCmp(Cmp) &&
14410 Op.getNode()->hasOneUse()) {
14411 X86::CondCode CCode =
14412 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14413 CCode = X86::GetOppositeBranchCondition(CCode);
14414 CC = DAG.getConstant(CCode, dl, MVT::i8);
14415 SDNode *User = *Op.getNode()->use_begin();
14416 // Look for an unconditional branch following this conditional branch.
14417 // We need this because we need to reverse the successors in order
14418 // to implement FCMP_OEQ.
14419 if (User->getOpcode() == ISD::BR) {
14420 SDValue FalseBB = User->getOperand(1);
14422 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14423 assert(NewBR == User);
14427 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14428 Chain, Dest, CC, Cmp);
14429 X86::CondCode CCode =
14430 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14431 CCode = X86::GetOppositeBranchCondition(CCode);
14432 CC = DAG.getConstant(CCode, dl, MVT::i8);
14438 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14439 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14440 // It should be transformed during dag combiner except when the condition
14441 // is set by a arithmetics with overflow node.
14442 X86::CondCode CCode =
14443 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14444 CCode = X86::GetOppositeBranchCondition(CCode);
14445 CC = DAG.getConstant(CCode, dl, MVT::i8);
14446 Cond = Cond.getOperand(0).getOperand(1);
14448 } else if (Cond.getOpcode() == ISD::SETCC &&
14449 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14450 // For FCMP_OEQ, we can emit
14451 // two branches instead of an explicit AND instruction with a
14452 // separate test. However, we only do this if this block doesn't
14453 // have a fall-through edge, because this requires an explicit
14454 // jmp when the condition is false.
14455 if (Op.getNode()->hasOneUse()) {
14456 SDNode *User = *Op.getNode()->use_begin();
14457 // Look for an unconditional branch following this conditional branch.
14458 // We need this because we need to reverse the successors in order
14459 // to implement FCMP_OEQ.
14460 if (User->getOpcode() == ISD::BR) {
14461 SDValue FalseBB = User->getOperand(1);
14463 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14464 assert(NewBR == User);
14468 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14469 Cond.getOperand(0), Cond.getOperand(1));
14470 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14471 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14472 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14473 Chain, Dest, CC, Cmp);
14474 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14479 } else if (Cond.getOpcode() == ISD::SETCC &&
14480 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14481 // For FCMP_UNE, we can emit
14482 // two branches instead of an explicit AND instruction with a
14483 // separate test. However, we only do this if this block doesn't
14484 // have a fall-through edge, because this requires an explicit
14485 // jmp when the condition is false.
14486 if (Op.getNode()->hasOneUse()) {
14487 SDNode *User = *Op.getNode()->use_begin();
14488 // Look for an unconditional branch following this conditional branch.
14489 // We need this because we need to reverse the successors in order
14490 // to implement FCMP_UNE.
14491 if (User->getOpcode() == ISD::BR) {
14492 SDValue FalseBB = User->getOperand(1);
14494 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14495 assert(NewBR == User);
14498 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14499 Cond.getOperand(0), Cond.getOperand(1));
14500 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14501 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14502 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14503 Chain, Dest, CC, Cmp);
14504 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14514 // Look pass the truncate if the high bits are known zero.
14515 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14516 Cond = Cond.getOperand(0);
14518 // We know the result of AND is compared against zero. Try to match
14520 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14521 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14522 if (NewSetCC.getNode()) {
14523 CC = NewSetCC.getOperand(0);
14524 Cond = NewSetCC.getOperand(1);
14531 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14532 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14533 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14535 Cond = ConvertCmpIfNecessary(Cond, DAG);
14536 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14537 Chain, Dest, CC, Cond);
14540 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14541 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14542 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14543 // that the guard pages used by the OS virtual memory manager are allocated in
14544 // correct sequence.
14546 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14547 SelectionDAG &DAG) const {
14548 MachineFunction &MF = DAG.getMachineFunction();
14549 bool SplitStack = MF.shouldSplitStack();
14550 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14555 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14556 SDNode* Node = Op.getNode();
14558 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14559 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14560 " not tell us which reg is the stack pointer!");
14561 EVT VT = Node->getValueType(0);
14562 SDValue Tmp1 = SDValue(Node, 0);
14563 SDValue Tmp2 = SDValue(Node, 1);
14564 SDValue Tmp3 = Node->getOperand(2);
14565 SDValue Chain = Tmp1.getOperand(0);
14567 // Chain the dynamic stack allocation so that it doesn't modify the stack
14568 // pointer when other instructions are using the stack.
14569 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14572 SDValue Size = Tmp2.getOperand(1);
14573 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14574 Chain = SP.getValue(1);
14575 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14576 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14577 unsigned StackAlign = TFI.getStackAlignment();
14578 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14579 if (Align > StackAlign)
14580 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14581 DAG.getConstant(-(uint64_t)Align, dl, VT));
14582 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14584 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14585 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14588 SDValue Ops[2] = { Tmp1, Tmp2 };
14589 return DAG.getMergeValues(Ops, dl);
14593 SDValue Chain = Op.getOperand(0);
14594 SDValue Size = Op.getOperand(1);
14595 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14596 EVT VT = Op.getNode()->getValueType(0);
14598 bool Is64Bit = Subtarget->is64Bit();
14599 EVT SPTy = getPointerTy();
14602 MachineRegisterInfo &MRI = MF.getRegInfo();
14605 // The 64 bit implementation of segmented stacks needs to clobber both r10
14606 // r11. This makes it impossible to use it along with nested parameters.
14607 const Function *F = MF.getFunction();
14609 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14611 if (I->hasNestAttr())
14612 report_fatal_error("Cannot use segmented stacks with functions that "
14613 "have nested arguments.");
14616 const TargetRegisterClass *AddrRegClass =
14617 getRegClassFor(getPointerTy());
14618 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14619 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14620 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14621 DAG.getRegister(Vreg, SPTy));
14622 SDValue Ops1[2] = { Value, Chain };
14623 return DAG.getMergeValues(Ops1, dl);
14626 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14628 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14629 Flag = Chain.getValue(1);
14630 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14632 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14634 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14635 unsigned SPReg = RegInfo->getStackRegister();
14636 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14637 Chain = SP.getValue(1);
14640 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14641 DAG.getConstant(-(uint64_t)Align, dl, VT));
14642 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14645 SDValue Ops1[2] = { SP, Chain };
14646 return DAG.getMergeValues(Ops1, dl);
14650 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14651 MachineFunction &MF = DAG.getMachineFunction();
14652 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14654 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14657 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14658 // vastart just stores the address of the VarArgsFrameIndex slot into the
14659 // memory location argument.
14660 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14662 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14663 MachinePointerInfo(SV), false, false, 0);
14667 // gp_offset (0 - 6 * 8)
14668 // fp_offset (48 - 48 + 8 * 16)
14669 // overflow_arg_area (point to parameters coming in memory).
14671 SmallVector<SDValue, 8> MemOps;
14672 SDValue FIN = Op.getOperand(1);
14674 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14675 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14677 FIN, MachinePointerInfo(SV), false, false, 0);
14678 MemOps.push_back(Store);
14681 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14682 FIN, DAG.getIntPtrConstant(4, DL));
14683 Store = DAG.getStore(Op.getOperand(0), DL,
14684 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14686 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14687 MemOps.push_back(Store);
14689 // Store ptr to overflow_arg_area
14690 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14691 FIN, DAG.getIntPtrConstant(4, DL));
14692 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14694 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14695 MachinePointerInfo(SV, 8),
14697 MemOps.push_back(Store);
14699 // Store ptr to reg_save_area.
14700 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14701 FIN, DAG.getIntPtrConstant(8, DL));
14702 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14704 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14705 MachinePointerInfo(SV, 16), false, false, 0);
14706 MemOps.push_back(Store);
14707 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14710 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14711 assert(Subtarget->is64Bit() &&
14712 "LowerVAARG only handles 64-bit va_arg!");
14713 assert((Subtarget->isTargetLinux() ||
14714 Subtarget->isTargetDarwin()) &&
14715 "Unhandled target in LowerVAARG");
14716 assert(Op.getNode()->getNumOperands() == 4);
14717 SDValue Chain = Op.getOperand(0);
14718 SDValue SrcPtr = Op.getOperand(1);
14719 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14720 unsigned Align = Op.getConstantOperandVal(3);
14723 EVT ArgVT = Op.getNode()->getValueType(0);
14724 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14725 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14728 // Decide which area this value should be read from.
14729 // TODO: Implement the AMD64 ABI in its entirety. This simple
14730 // selection mechanism works only for the basic types.
14731 if (ArgVT == MVT::f80) {
14732 llvm_unreachable("va_arg for f80 not yet implemented");
14733 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14734 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14735 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14736 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14738 llvm_unreachable("Unhandled argument type in LowerVAARG");
14741 if (ArgMode == 2) {
14742 // Sanity Check: Make sure using fp_offset makes sense.
14743 assert(!Subtarget->useSoftFloat() &&
14744 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14745 Attribute::NoImplicitFloat)) &&
14746 Subtarget->hasSSE1());
14749 // Insert VAARG_64 node into the DAG
14750 // VAARG_64 returns two values: Variable Argument Address, Chain
14751 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14752 DAG.getConstant(ArgMode, dl, MVT::i8),
14753 DAG.getConstant(Align, dl, MVT::i32)};
14754 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14755 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14756 VTs, InstOps, MVT::i64,
14757 MachinePointerInfo(SV),
14759 /*Volatile=*/false,
14761 /*WriteMem=*/true);
14762 Chain = VAARG.getValue(1);
14764 // Load the next argument and return it
14765 return DAG.getLoad(ArgVT, dl,
14768 MachinePointerInfo(),
14769 false, false, false, 0);
14772 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14773 SelectionDAG &DAG) {
14774 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14775 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14776 SDValue Chain = Op.getOperand(0);
14777 SDValue DstPtr = Op.getOperand(1);
14778 SDValue SrcPtr = Op.getOperand(2);
14779 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14780 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14783 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14784 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14786 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14789 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14790 // amount is a constant. Takes immediate version of shift as input.
14791 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14792 SDValue SrcOp, uint64_t ShiftAmt,
14793 SelectionDAG &DAG) {
14794 MVT ElementType = VT.getVectorElementType();
14796 // Fold this packed shift into its first operand if ShiftAmt is 0.
14800 // Check for ShiftAmt >= element width
14801 if (ShiftAmt >= ElementType.getSizeInBits()) {
14802 if (Opc == X86ISD::VSRAI)
14803 ShiftAmt = ElementType.getSizeInBits() - 1;
14805 return DAG.getConstant(0, dl, VT);
14808 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14809 && "Unknown target vector shift-by-constant node");
14811 // Fold this packed vector shift into a build vector if SrcOp is a
14812 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14813 if (VT == SrcOp.getSimpleValueType() &&
14814 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14815 SmallVector<SDValue, 8> Elts;
14816 unsigned NumElts = SrcOp->getNumOperands();
14817 ConstantSDNode *ND;
14820 default: llvm_unreachable(nullptr);
14821 case X86ISD::VSHLI:
14822 for (unsigned i=0; i!=NumElts; ++i) {
14823 SDValue CurrentOp = SrcOp->getOperand(i);
14824 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14825 Elts.push_back(CurrentOp);
14828 ND = cast<ConstantSDNode>(CurrentOp);
14829 const APInt &C = ND->getAPIntValue();
14830 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14833 case X86ISD::VSRLI:
14834 for (unsigned i=0; i!=NumElts; ++i) {
14835 SDValue CurrentOp = SrcOp->getOperand(i);
14836 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14837 Elts.push_back(CurrentOp);
14840 ND = cast<ConstantSDNode>(CurrentOp);
14841 const APInt &C = ND->getAPIntValue();
14842 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14845 case X86ISD::VSRAI:
14846 for (unsigned i=0; i!=NumElts; ++i) {
14847 SDValue CurrentOp = SrcOp->getOperand(i);
14848 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14849 Elts.push_back(CurrentOp);
14852 ND = cast<ConstantSDNode>(CurrentOp);
14853 const APInt &C = ND->getAPIntValue();
14854 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14859 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14862 return DAG.getNode(Opc, dl, VT, SrcOp,
14863 DAG.getConstant(ShiftAmt, dl, MVT::i8));
14866 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14867 // may or may not be a constant. Takes immediate version of shift as input.
14868 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14869 SDValue SrcOp, SDValue ShAmt,
14870 SelectionDAG &DAG) {
14871 MVT SVT = ShAmt.getSimpleValueType();
14872 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14874 // Catch shift-by-constant.
14875 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14876 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14877 CShAmt->getZExtValue(), DAG);
14879 // Change opcode to non-immediate version
14881 default: llvm_unreachable("Unknown target vector shift node");
14882 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14883 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14884 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14887 const X86Subtarget &Subtarget =
14888 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14889 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14890 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14891 // Let the shuffle legalizer expand this shift amount node.
14892 SDValue Op0 = ShAmt.getOperand(0);
14893 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14894 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14896 // Need to build a vector containing shift amount.
14897 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14898 SmallVector<SDValue, 4> ShOps;
14899 ShOps.push_back(ShAmt);
14900 if (SVT == MVT::i32) {
14901 ShOps.push_back(DAG.getConstant(0, dl, SVT));
14902 ShOps.push_back(DAG.getUNDEF(SVT));
14904 ShOps.push_back(DAG.getUNDEF(SVT));
14906 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14907 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14910 // The return type has to be a 128-bit type with the same element
14911 // type as the input type.
14912 MVT EltVT = VT.getVectorElementType();
14913 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14915 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14916 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14919 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14920 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14921 /// necessary casting for \p Mask when lowering masking intrinsics.
14922 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14923 SDValue PreservedSrc,
14924 const X86Subtarget *Subtarget,
14925 SelectionDAG &DAG) {
14926 EVT VT = Op.getValueType();
14927 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14928 MVT::i1, VT.getVectorNumElements());
14929 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14930 Mask.getValueType().getSizeInBits());
14933 assert(MaskVT.isSimple() && "invalid mask type");
14935 if (isAllOnes(Mask))
14938 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14939 // are extracted by EXTRACT_SUBVECTOR.
14940 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14941 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14942 DAG.getIntPtrConstant(0, dl));
14944 switch (Op.getOpcode()) {
14946 case X86ISD::PCMPEQM:
14947 case X86ISD::PCMPGTM:
14949 case X86ISD::CMPMU:
14950 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14952 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14953 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14954 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14957 /// \brief Creates an SDNode for a predicated scalar operation.
14958 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14959 /// The mask is comming as MVT::i8 and it should be truncated
14960 /// to MVT::i1 while lowering masking intrinsics.
14961 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14962 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14963 /// a scalar instruction.
14964 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14965 SDValue PreservedSrc,
14966 const X86Subtarget *Subtarget,
14967 SelectionDAG &DAG) {
14968 if (isAllOnes(Mask))
14971 EVT VT = Op.getValueType();
14973 // The mask should be of type MVT::i1
14974 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14976 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14977 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14978 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14981 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14982 SelectionDAG &DAG) {
14984 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14985 EVT VT = Op.getValueType();
14986 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14988 switch(IntrData->Type) {
14989 case INTR_TYPE_1OP:
14990 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14991 case INTR_TYPE_2OP:
14992 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14994 case INTR_TYPE_3OP:
14995 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14996 Op.getOperand(2), Op.getOperand(3));
14997 case INTR_TYPE_1OP_MASK_RM: {
14998 SDValue Src = Op.getOperand(1);
14999 SDValue Src0 = Op.getOperand(2);
15000 SDValue Mask = Op.getOperand(3);
15001 SDValue RoundingMode = Op.getOperand(4);
15002 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15004 Mask, Src0, Subtarget, DAG);
15006 case INTR_TYPE_SCALAR_MASK_RM: {
15007 SDValue Src1 = Op.getOperand(1);
15008 SDValue Src2 = Op.getOperand(2);
15009 SDValue Src0 = Op.getOperand(3);
15010 SDValue Mask = Op.getOperand(4);
15011 // There are 2 kinds of intrinsics in this group:
15012 // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15013 // (2) With rounding mode and sae - 7 operands.
15014 if (Op.getNumOperands() == 6) {
15015 SDValue Sae = Op.getOperand(5);
15016 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15017 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15019 Mask, Src0, Subtarget, DAG);
15021 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15022 SDValue RoundingMode = Op.getOperand(5);
15023 SDValue Sae = Op.getOperand(6);
15024 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15025 RoundingMode, Sae),
15026 Mask, Src0, Subtarget, DAG);
15028 case INTR_TYPE_2OP_MASK: {
15029 SDValue Src1 = Op.getOperand(1);
15030 SDValue Src2 = Op.getOperand(2);
15031 SDValue PassThru = Op.getOperand(3);
15032 SDValue Mask = Op.getOperand(4);
15033 // We specify 2 possible opcodes for intrinsics with rounding modes.
15034 // First, we check if the intrinsic may have non-default rounding mode,
15035 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15036 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15037 if (IntrWithRoundingModeOpcode != 0) {
15038 SDValue Rnd = Op.getOperand(5);
15039 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15040 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15041 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15042 dl, Op.getValueType(),
15044 Mask, PassThru, Subtarget, DAG);
15047 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15049 Mask, PassThru, Subtarget, DAG);
15051 case FMA_OP_MASK: {
15052 SDValue Src1 = Op.getOperand(1);
15053 SDValue Src2 = Op.getOperand(2);
15054 SDValue Src3 = Op.getOperand(3);
15055 SDValue Mask = Op.getOperand(4);
15056 // We specify 2 possible opcodes for intrinsics with rounding modes.
15057 // First, we check if the intrinsic may have non-default rounding mode,
15058 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15059 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15060 if (IntrWithRoundingModeOpcode != 0) {
15061 SDValue Rnd = Op.getOperand(5);
15062 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15063 X86::STATIC_ROUNDING::CUR_DIRECTION)
15064 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15065 dl, Op.getValueType(),
15066 Src1, Src2, Src3, Rnd),
15067 Mask, Src1, Subtarget, DAG);
15069 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15070 dl, Op.getValueType(),
15072 Mask, Src1, Subtarget, DAG);
15075 case CMP_MASK_CC: {
15076 // Comparison intrinsics with masks.
15077 // Example of transformation:
15078 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15079 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15081 // (v8i1 (insert_subvector undef,
15082 // (v2i1 (and (PCMPEQM %a, %b),
15083 // (extract_subvector
15084 // (v8i1 (bitcast %mask)), 0))), 0))))
15085 EVT VT = Op.getOperand(1).getValueType();
15086 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15087 VT.getVectorNumElements());
15088 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15089 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15090 Mask.getValueType().getSizeInBits());
15092 if (IntrData->Type == CMP_MASK_CC) {
15093 SDValue CC = Op.getOperand(3);
15094 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15095 // We specify 2 possible opcodes for intrinsics with rounding modes.
15096 // First, we check if the intrinsic may have non-default rounding mode,
15097 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15098 if (IntrData->Opc1 != 0) {
15099 SDValue Rnd = Op.getOperand(5);
15100 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15101 X86::STATIC_ROUNDING::CUR_DIRECTION)
15102 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15103 Op.getOperand(2), CC, Rnd);
15105 //default rounding mode
15107 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15108 Op.getOperand(2), CC);
15111 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15112 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15115 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15116 DAG.getTargetConstant(0, dl,
15119 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15120 DAG.getUNDEF(BitcastVT), CmpMask,
15121 DAG.getIntPtrConstant(0, dl));
15122 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15124 case COMI: { // Comparison intrinsics
15125 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15126 SDValue LHS = Op.getOperand(1);
15127 SDValue RHS = Op.getOperand(2);
15128 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15129 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15130 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15131 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15132 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15133 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15136 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15137 Op.getOperand(1), Op.getOperand(2), DAG);
15139 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15140 Op.getSimpleValueType(),
15142 Op.getOperand(2), DAG),
15143 Op.getOperand(4), Op.getOperand(3), Subtarget,
15145 case COMPRESS_EXPAND_IN_REG: {
15146 SDValue Mask = Op.getOperand(3);
15147 SDValue DataToCompress = Op.getOperand(1);
15148 SDValue PassThru = Op.getOperand(2);
15149 if (isAllOnes(Mask)) // return data as is
15150 return Op.getOperand(1);
15151 EVT VT = Op.getValueType();
15152 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15153 VT.getVectorNumElements());
15154 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15155 Mask.getValueType().getSizeInBits());
15157 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15158 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15159 DAG.getIntPtrConstant(0, dl));
15161 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15165 SDValue Mask = Op.getOperand(3);
15166 EVT VT = Op.getValueType();
15167 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15168 VT.getVectorNumElements());
15169 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15170 Mask.getValueType().getSizeInBits());
15172 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15173 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15174 DAG.getIntPtrConstant(0, dl));
15175 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15184 default: return SDValue(); // Don't custom lower most intrinsics.
15186 case Intrinsic::x86_avx2_permd:
15187 case Intrinsic::x86_avx2_permps:
15188 // Operands intentionally swapped. Mask is last operand to intrinsic,
15189 // but second operand for node/instruction.
15190 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15191 Op.getOperand(2), Op.getOperand(1));
15193 case Intrinsic::x86_avx512_mask_valign_q_512:
15194 case Intrinsic::x86_avx512_mask_valign_d_512:
15195 // Vector source operands are swapped.
15196 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15197 Op.getValueType(), Op.getOperand(2),
15200 Op.getOperand(5), Op.getOperand(4),
15203 // ptest and testp intrinsics. The intrinsic these come from are designed to
15204 // return an integer value, not just an instruction so lower it to the ptest
15205 // or testp pattern and a setcc for the result.
15206 case Intrinsic::x86_sse41_ptestz:
15207 case Intrinsic::x86_sse41_ptestc:
15208 case Intrinsic::x86_sse41_ptestnzc:
15209 case Intrinsic::x86_avx_ptestz_256:
15210 case Intrinsic::x86_avx_ptestc_256:
15211 case Intrinsic::x86_avx_ptestnzc_256:
15212 case Intrinsic::x86_avx_vtestz_ps:
15213 case Intrinsic::x86_avx_vtestc_ps:
15214 case Intrinsic::x86_avx_vtestnzc_ps:
15215 case Intrinsic::x86_avx_vtestz_pd:
15216 case Intrinsic::x86_avx_vtestc_pd:
15217 case Intrinsic::x86_avx_vtestnzc_pd:
15218 case Intrinsic::x86_avx_vtestz_ps_256:
15219 case Intrinsic::x86_avx_vtestc_ps_256:
15220 case Intrinsic::x86_avx_vtestnzc_ps_256:
15221 case Intrinsic::x86_avx_vtestz_pd_256:
15222 case Intrinsic::x86_avx_vtestc_pd_256:
15223 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15224 bool IsTestPacked = false;
15227 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15228 case Intrinsic::x86_avx_vtestz_ps:
15229 case Intrinsic::x86_avx_vtestz_pd:
15230 case Intrinsic::x86_avx_vtestz_ps_256:
15231 case Intrinsic::x86_avx_vtestz_pd_256:
15232 IsTestPacked = true; // Fallthrough
15233 case Intrinsic::x86_sse41_ptestz:
15234 case Intrinsic::x86_avx_ptestz_256:
15236 X86CC = X86::COND_E;
15238 case Intrinsic::x86_avx_vtestc_ps:
15239 case Intrinsic::x86_avx_vtestc_pd:
15240 case Intrinsic::x86_avx_vtestc_ps_256:
15241 case Intrinsic::x86_avx_vtestc_pd_256:
15242 IsTestPacked = true; // Fallthrough
15243 case Intrinsic::x86_sse41_ptestc:
15244 case Intrinsic::x86_avx_ptestc_256:
15246 X86CC = X86::COND_B;
15248 case Intrinsic::x86_avx_vtestnzc_ps:
15249 case Intrinsic::x86_avx_vtestnzc_pd:
15250 case Intrinsic::x86_avx_vtestnzc_ps_256:
15251 case Intrinsic::x86_avx_vtestnzc_pd_256:
15252 IsTestPacked = true; // Fallthrough
15253 case Intrinsic::x86_sse41_ptestnzc:
15254 case Intrinsic::x86_avx_ptestnzc_256:
15256 X86CC = X86::COND_A;
15260 SDValue LHS = Op.getOperand(1);
15261 SDValue RHS = Op.getOperand(2);
15262 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15263 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15264 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15265 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15266 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15268 case Intrinsic::x86_avx512_kortestz_w:
15269 case Intrinsic::x86_avx512_kortestc_w: {
15270 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15271 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15272 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15273 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15274 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15275 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15276 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15279 case Intrinsic::x86_sse42_pcmpistria128:
15280 case Intrinsic::x86_sse42_pcmpestria128:
15281 case Intrinsic::x86_sse42_pcmpistric128:
15282 case Intrinsic::x86_sse42_pcmpestric128:
15283 case Intrinsic::x86_sse42_pcmpistrio128:
15284 case Intrinsic::x86_sse42_pcmpestrio128:
15285 case Intrinsic::x86_sse42_pcmpistris128:
15286 case Intrinsic::x86_sse42_pcmpestris128:
15287 case Intrinsic::x86_sse42_pcmpistriz128:
15288 case Intrinsic::x86_sse42_pcmpestriz128: {
15292 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15293 case Intrinsic::x86_sse42_pcmpistria128:
15294 Opcode = X86ISD::PCMPISTRI;
15295 X86CC = X86::COND_A;
15297 case Intrinsic::x86_sse42_pcmpestria128:
15298 Opcode = X86ISD::PCMPESTRI;
15299 X86CC = X86::COND_A;
15301 case Intrinsic::x86_sse42_pcmpistric128:
15302 Opcode = X86ISD::PCMPISTRI;
15303 X86CC = X86::COND_B;
15305 case Intrinsic::x86_sse42_pcmpestric128:
15306 Opcode = X86ISD::PCMPESTRI;
15307 X86CC = X86::COND_B;
15309 case Intrinsic::x86_sse42_pcmpistrio128:
15310 Opcode = X86ISD::PCMPISTRI;
15311 X86CC = X86::COND_O;
15313 case Intrinsic::x86_sse42_pcmpestrio128:
15314 Opcode = X86ISD::PCMPESTRI;
15315 X86CC = X86::COND_O;
15317 case Intrinsic::x86_sse42_pcmpistris128:
15318 Opcode = X86ISD::PCMPISTRI;
15319 X86CC = X86::COND_S;
15321 case Intrinsic::x86_sse42_pcmpestris128:
15322 Opcode = X86ISD::PCMPESTRI;
15323 X86CC = X86::COND_S;
15325 case Intrinsic::x86_sse42_pcmpistriz128:
15326 Opcode = X86ISD::PCMPISTRI;
15327 X86CC = X86::COND_E;
15329 case Intrinsic::x86_sse42_pcmpestriz128:
15330 Opcode = X86ISD::PCMPESTRI;
15331 X86CC = X86::COND_E;
15334 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15335 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15336 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15337 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15338 DAG.getConstant(X86CC, dl, MVT::i8),
15339 SDValue(PCMP.getNode(), 1));
15340 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15343 case Intrinsic::x86_sse42_pcmpistri128:
15344 case Intrinsic::x86_sse42_pcmpestri128: {
15346 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15347 Opcode = X86ISD::PCMPISTRI;
15349 Opcode = X86ISD::PCMPESTRI;
15351 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15352 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15353 return DAG.getNode(Opcode, dl, VTs, NewOps);
15356 case Intrinsic::x86_seh_lsda: {
15357 // Compute the symbol for the LSDA. We know it'll get emitted later.
15358 MachineFunction &MF = DAG.getMachineFunction();
15359 SDValue Op1 = Op.getOperand(1);
15361 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15362 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15363 GlobalValue::getRealLinkageName(Fn->getName()));
15364 StringRef Name = LSDASym->getName();
15365 assert(Name.data()[Name.size()] == '\0' && "not null terminated");
15367 // Generate a simple absolute symbol reference. This intrinsic is only
15368 // supported on 32-bit Windows, which isn't PIC.
15370 DAG.getTargetExternalSymbol(Name.data(), VT, X86II::MO_NOPREFIX);
15371 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15376 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15377 SDValue Src, SDValue Mask, SDValue Base,
15378 SDValue Index, SDValue ScaleOp, SDValue Chain,
15379 const X86Subtarget * Subtarget) {
15381 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15382 assert(C && "Invalid scale type");
15383 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15384 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15385 Index.getSimpleValueType().getVectorNumElements());
15387 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15389 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15391 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15392 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15393 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15394 SDValue Segment = DAG.getRegister(0, MVT::i32);
15395 if (Src.getOpcode() == ISD::UNDEF)
15396 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15397 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15398 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15399 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15400 return DAG.getMergeValues(RetOps, dl);
15403 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15404 SDValue Src, SDValue Mask, SDValue Base,
15405 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15407 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15408 assert(C && "Invalid scale type");
15409 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15410 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15411 SDValue Segment = DAG.getRegister(0, MVT::i32);
15412 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15413 Index.getSimpleValueType().getVectorNumElements());
15415 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15417 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15419 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15420 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15421 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15422 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15423 return SDValue(Res, 1);
15426 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15427 SDValue Mask, SDValue Base, SDValue Index,
15428 SDValue ScaleOp, SDValue Chain) {
15430 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15431 assert(C && "Invalid scale type");
15432 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15433 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15434 SDValue Segment = DAG.getRegister(0, MVT::i32);
15436 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15438 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15440 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15442 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15443 //SDVTList VTs = DAG.getVTList(MVT::Other);
15444 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15445 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15446 return SDValue(Res, 0);
15449 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15450 // read performance monitor counters (x86_rdpmc).
15451 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15452 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15453 SmallVectorImpl<SDValue> &Results) {
15454 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15455 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15458 // The ECX register is used to select the index of the performance counter
15460 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15462 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15464 // Reads the content of a 64-bit performance counter and returns it in the
15465 // registers EDX:EAX.
15466 if (Subtarget->is64Bit()) {
15467 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15468 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15471 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15472 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15475 Chain = HI.getValue(1);
15477 if (Subtarget->is64Bit()) {
15478 // The EAX register is loaded with the low-order 32 bits. The EDX register
15479 // is loaded with the supported high-order bits of the counter.
15480 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15481 DAG.getConstant(32, DL, MVT::i8));
15482 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15483 Results.push_back(Chain);
15487 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15488 SDValue Ops[] = { LO, HI };
15489 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15490 Results.push_back(Pair);
15491 Results.push_back(Chain);
15494 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15495 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15496 // also used to custom lower READCYCLECOUNTER nodes.
15497 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15498 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15499 SmallVectorImpl<SDValue> &Results) {
15500 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15501 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15504 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15505 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15506 // and the EAX register is loaded with the low-order 32 bits.
15507 if (Subtarget->is64Bit()) {
15508 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15509 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15512 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15513 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15516 SDValue Chain = HI.getValue(1);
15518 if (Opcode == X86ISD::RDTSCP_DAG) {
15519 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15521 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15522 // the ECX register. Add 'ecx' explicitly to the chain.
15523 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15525 // Explicitly store the content of ECX at the location passed in input
15526 // to the 'rdtscp' intrinsic.
15527 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15528 MachinePointerInfo(), false, false, 0);
15531 if (Subtarget->is64Bit()) {
15532 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15533 // the EAX register is loaded with the low-order 32 bits.
15534 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15535 DAG.getConstant(32, DL, MVT::i8));
15536 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15537 Results.push_back(Chain);
15541 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15542 SDValue Ops[] = { LO, HI };
15543 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15544 Results.push_back(Pair);
15545 Results.push_back(Chain);
15548 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15549 SelectionDAG &DAG) {
15550 SmallVector<SDValue, 2> Results;
15552 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15554 return DAG.getMergeValues(Results, DL);
15558 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15559 SelectionDAG &DAG) {
15560 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15562 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15567 switch(IntrData->Type) {
15569 llvm_unreachable("Unknown Intrinsic Type");
15573 // Emit the node with the right value type.
15574 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15575 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15577 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15578 // Otherwise return the value from Rand, which is always 0, casted to i32.
15579 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15580 DAG.getConstant(1, dl, Op->getValueType(1)),
15581 DAG.getConstant(X86::COND_B, dl, MVT::i32),
15582 SDValue(Result.getNode(), 1) };
15583 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15584 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15587 // Return { result, isValid, chain }.
15588 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15589 SDValue(Result.getNode(), 2));
15592 //gather(v1, mask, index, base, scale);
15593 SDValue Chain = Op.getOperand(0);
15594 SDValue Src = Op.getOperand(2);
15595 SDValue Base = Op.getOperand(3);
15596 SDValue Index = Op.getOperand(4);
15597 SDValue Mask = Op.getOperand(5);
15598 SDValue Scale = Op.getOperand(6);
15599 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15603 //scatter(base, mask, index, v1, scale);
15604 SDValue Chain = Op.getOperand(0);
15605 SDValue Base = Op.getOperand(2);
15606 SDValue Mask = Op.getOperand(3);
15607 SDValue Index = Op.getOperand(4);
15608 SDValue Src = Op.getOperand(5);
15609 SDValue Scale = Op.getOperand(6);
15610 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15614 SDValue Hint = Op.getOperand(6);
15615 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15616 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15617 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15618 SDValue Chain = Op.getOperand(0);
15619 SDValue Mask = Op.getOperand(2);
15620 SDValue Index = Op.getOperand(3);
15621 SDValue Base = Op.getOperand(4);
15622 SDValue Scale = Op.getOperand(5);
15623 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15625 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15627 SmallVector<SDValue, 2> Results;
15628 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15630 return DAG.getMergeValues(Results, dl);
15632 // Read Performance Monitoring Counters.
15634 SmallVector<SDValue, 2> Results;
15635 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15636 return DAG.getMergeValues(Results, dl);
15638 // XTEST intrinsics.
15640 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15641 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15642 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15643 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15645 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15646 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15647 Ret, SDValue(InTrans.getNode(), 1));
15651 SmallVector<SDValue, 2> Results;
15652 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15653 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15654 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15655 DAG.getConstant(-1, dl, MVT::i8));
15656 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15657 Op.getOperand(4), GenCF.getValue(1));
15658 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15659 Op.getOperand(5), MachinePointerInfo(),
15661 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15662 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15664 Results.push_back(SetCC);
15665 Results.push_back(Store);
15666 return DAG.getMergeValues(Results, dl);
15668 case COMPRESS_TO_MEM: {
15670 SDValue Mask = Op.getOperand(4);
15671 SDValue DataToCompress = Op.getOperand(3);
15672 SDValue Addr = Op.getOperand(2);
15673 SDValue Chain = Op.getOperand(0);
15675 if (isAllOnes(Mask)) // return just a store
15676 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15677 MachinePointerInfo(), false, false, 0);
15679 EVT VT = DataToCompress.getValueType();
15680 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15681 VT.getVectorNumElements());
15682 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15683 Mask.getValueType().getSizeInBits());
15684 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15685 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15686 DAG.getIntPtrConstant(0, dl));
15688 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15689 DataToCompress, DAG.getUNDEF(VT));
15690 return DAG.getStore(Chain, dl, Compressed, Addr,
15691 MachinePointerInfo(), false, false, 0);
15693 case EXPAND_FROM_MEM: {
15695 SDValue Mask = Op.getOperand(4);
15696 SDValue PathThru = Op.getOperand(3);
15697 SDValue Addr = Op.getOperand(2);
15698 SDValue Chain = Op.getOperand(0);
15699 EVT VT = Op.getValueType();
15701 if (isAllOnes(Mask)) // return just a load
15702 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15704 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15705 VT.getVectorNumElements());
15706 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15707 Mask.getValueType().getSizeInBits());
15708 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15709 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15710 DAG.getIntPtrConstant(0, dl));
15712 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15713 false, false, false, 0);
15715 SDValue Results[] = {
15716 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15718 return DAG.getMergeValues(Results, dl);
15723 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15724 SelectionDAG &DAG) const {
15725 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15726 MFI->setReturnAddressIsTaken(true);
15728 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15731 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15733 EVT PtrVT = getPointerTy();
15736 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15737 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15738 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15739 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15740 DAG.getNode(ISD::ADD, dl, PtrVT,
15741 FrameAddr, Offset),
15742 MachinePointerInfo(), false, false, false, 0);
15745 // Just load the return address.
15746 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15747 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15748 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15751 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15752 MachineFunction &MF = DAG.getMachineFunction();
15753 MachineFrameInfo *MFI = MF.getFrameInfo();
15754 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15755 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15756 EVT VT = Op.getValueType();
15758 MFI->setFrameAddressIsTaken(true);
15760 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15761 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15762 // is not possible to crawl up the stack without looking at the unwind codes
15764 int FrameAddrIndex = FuncInfo->getFAIndex();
15765 if (!FrameAddrIndex) {
15766 // Set up a frame object for the return address.
15767 unsigned SlotSize = RegInfo->getSlotSize();
15768 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15769 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15770 FuncInfo->setFAIndex(FrameAddrIndex);
15772 return DAG.getFrameIndex(FrameAddrIndex, VT);
15775 unsigned FrameReg =
15776 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15777 SDLoc dl(Op); // FIXME probably not meaningful
15778 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15779 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15780 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15781 "Invalid Frame Register!");
15782 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15784 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15785 MachinePointerInfo(),
15786 false, false, false, 0);
15790 // FIXME? Maybe this could be a TableGen attribute on some registers and
15791 // this table could be generated automatically from RegInfo.
15792 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15794 unsigned Reg = StringSwitch<unsigned>(RegName)
15795 .Case("esp", X86::ESP)
15796 .Case("rsp", X86::RSP)
15800 report_fatal_error("Invalid register name global variable");
15803 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15804 SelectionDAG &DAG) const {
15805 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15806 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15809 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15810 SDValue Chain = Op.getOperand(0);
15811 SDValue Offset = Op.getOperand(1);
15812 SDValue Handler = Op.getOperand(2);
15815 EVT PtrVT = getPointerTy();
15816 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15817 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15818 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15819 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15820 "Invalid Frame Register!");
15821 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15822 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15824 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15825 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15827 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15828 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15830 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15832 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15833 DAG.getRegister(StoreAddrReg, PtrVT));
15836 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15837 SelectionDAG &DAG) const {
15839 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15840 DAG.getVTList(MVT::i32, MVT::Other),
15841 Op.getOperand(0), Op.getOperand(1));
15844 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15845 SelectionDAG &DAG) const {
15847 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15848 Op.getOperand(0), Op.getOperand(1));
15851 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15852 return Op.getOperand(0);
15855 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15856 SelectionDAG &DAG) const {
15857 SDValue Root = Op.getOperand(0);
15858 SDValue Trmp = Op.getOperand(1); // trampoline
15859 SDValue FPtr = Op.getOperand(2); // nested function
15860 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15863 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15864 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15866 if (Subtarget->is64Bit()) {
15867 SDValue OutChains[6];
15869 // Large code-model.
15870 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15871 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15873 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15874 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15876 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15878 // Load the pointer to the nested function into R11.
15879 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15880 SDValue Addr = Trmp;
15881 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15882 Addr, MachinePointerInfo(TrmpAddr),
15885 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15886 DAG.getConstant(2, dl, MVT::i64));
15887 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15888 MachinePointerInfo(TrmpAddr, 2),
15891 // Load the 'nest' parameter value into R10.
15892 // R10 is specified in X86CallingConv.td
15893 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15894 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15895 DAG.getConstant(10, dl, MVT::i64));
15896 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15897 Addr, MachinePointerInfo(TrmpAddr, 10),
15900 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15901 DAG.getConstant(12, dl, MVT::i64));
15902 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15903 MachinePointerInfo(TrmpAddr, 12),
15906 // Jump to the nested function.
15907 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15908 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15909 DAG.getConstant(20, dl, MVT::i64));
15910 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15911 Addr, MachinePointerInfo(TrmpAddr, 20),
15914 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15915 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15916 DAG.getConstant(22, dl, MVT::i64));
15917 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15918 Addr, MachinePointerInfo(TrmpAddr, 22),
15921 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15923 const Function *Func =
15924 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15925 CallingConv::ID CC = Func->getCallingConv();
15930 llvm_unreachable("Unsupported calling convention");
15931 case CallingConv::C:
15932 case CallingConv::X86_StdCall: {
15933 // Pass 'nest' parameter in ECX.
15934 // Must be kept in sync with X86CallingConv.td
15935 NestReg = X86::ECX;
15937 // Check that ECX wasn't needed by an 'inreg' parameter.
15938 FunctionType *FTy = Func->getFunctionType();
15939 const AttributeSet &Attrs = Func->getAttributes();
15941 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15942 unsigned InRegCount = 0;
15945 for (FunctionType::param_iterator I = FTy->param_begin(),
15946 E = FTy->param_end(); I != E; ++I, ++Idx)
15947 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15948 // FIXME: should only count parameters that are lowered to integers.
15949 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15951 if (InRegCount > 2) {
15952 report_fatal_error("Nest register in use - reduce number of inreg"
15958 case CallingConv::X86_FastCall:
15959 case CallingConv::X86_ThisCall:
15960 case CallingConv::Fast:
15961 // Pass 'nest' parameter in EAX.
15962 // Must be kept in sync with X86CallingConv.td
15963 NestReg = X86::EAX;
15967 SDValue OutChains[4];
15968 SDValue Addr, Disp;
15970 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15971 DAG.getConstant(10, dl, MVT::i32));
15972 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15974 // This is storing the opcode for MOV32ri.
15975 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15976 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15977 OutChains[0] = DAG.getStore(Root, dl,
15978 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15979 Trmp, MachinePointerInfo(TrmpAddr),
15982 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15983 DAG.getConstant(1, dl, MVT::i32));
15984 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15985 MachinePointerInfo(TrmpAddr, 1),
15988 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15989 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15990 DAG.getConstant(5, dl, MVT::i32));
15991 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15992 Addr, MachinePointerInfo(TrmpAddr, 5),
15995 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15996 DAG.getConstant(6, dl, MVT::i32));
15997 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15998 MachinePointerInfo(TrmpAddr, 6),
16001 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16005 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16006 SelectionDAG &DAG) const {
16008 The rounding mode is in bits 11:10 of FPSR, and has the following
16010 00 Round to nearest
16015 FLT_ROUNDS, on the other hand, expects the following:
16022 To perform the conversion, we do:
16023 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16026 MachineFunction &MF = DAG.getMachineFunction();
16027 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16028 unsigned StackAlignment = TFI.getStackAlignment();
16029 MVT VT = Op.getSimpleValueType();
16032 // Save FP Control Word to stack slot
16033 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16034 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16036 MachineMemOperand *MMO =
16037 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16038 MachineMemOperand::MOStore, 2, 2);
16040 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16041 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16042 DAG.getVTList(MVT::Other),
16043 Ops, MVT::i16, MMO);
16045 // Load FP Control Word from stack slot
16046 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16047 MachinePointerInfo(), false, false, false, 0);
16049 // Transform as necessary
16051 DAG.getNode(ISD::SRL, DL, MVT::i16,
16052 DAG.getNode(ISD::AND, DL, MVT::i16,
16053 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16054 DAG.getConstant(11, DL, MVT::i8));
16056 DAG.getNode(ISD::SRL, DL, MVT::i16,
16057 DAG.getNode(ISD::AND, DL, MVT::i16,
16058 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16059 DAG.getConstant(9, DL, MVT::i8));
16062 DAG.getNode(ISD::AND, DL, MVT::i16,
16063 DAG.getNode(ISD::ADD, DL, MVT::i16,
16064 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16065 DAG.getConstant(1, DL, MVT::i16)),
16066 DAG.getConstant(3, DL, MVT::i16));
16068 return DAG.getNode((VT.getSizeInBits() < 16 ?
16069 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16072 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16073 MVT VT = Op.getSimpleValueType();
16075 unsigned NumBits = VT.getSizeInBits();
16078 Op = Op.getOperand(0);
16079 if (VT == MVT::i8) {
16080 // Zero extend to i32 since there is not an i8 bsr.
16082 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16085 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16086 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16087 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16089 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16092 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16093 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16096 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16098 // Finally xor with NumBits-1.
16099 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16100 DAG.getConstant(NumBits - 1, dl, OpVT));
16103 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16107 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16108 MVT VT = Op.getSimpleValueType();
16110 unsigned NumBits = VT.getSizeInBits();
16113 Op = Op.getOperand(0);
16114 if (VT == MVT::i8) {
16115 // Zero extend to i32 since there is not an i8 bsr.
16117 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16120 // Issue a bsr (scan bits in reverse).
16121 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16122 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16124 // And xor with NumBits-1.
16125 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16126 DAG.getConstant(NumBits - 1, dl, OpVT));
16129 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16133 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16134 MVT VT = Op.getSimpleValueType();
16135 unsigned NumBits = VT.getSizeInBits();
16137 Op = Op.getOperand(0);
16139 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16140 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16141 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16143 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16146 DAG.getConstant(NumBits, dl, VT),
16147 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16150 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16153 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16154 // ones, and then concatenate the result back.
16155 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16156 MVT VT = Op.getSimpleValueType();
16158 assert(VT.is256BitVector() && VT.isInteger() &&
16159 "Unsupported value type for operation");
16161 unsigned NumElems = VT.getVectorNumElements();
16164 // Extract the LHS vectors
16165 SDValue LHS = Op.getOperand(0);
16166 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16167 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16169 // Extract the RHS vectors
16170 SDValue RHS = Op.getOperand(1);
16171 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16172 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16174 MVT EltVT = VT.getVectorElementType();
16175 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16177 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16178 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16179 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16182 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16183 assert(Op.getSimpleValueType().is256BitVector() &&
16184 Op.getSimpleValueType().isInteger() &&
16185 "Only handle AVX 256-bit vector integer operation");
16186 return Lower256IntArith(Op, DAG);
16189 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16190 assert(Op.getSimpleValueType().is256BitVector() &&
16191 Op.getSimpleValueType().isInteger() &&
16192 "Only handle AVX 256-bit vector integer operation");
16193 return Lower256IntArith(Op, DAG);
16196 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16197 SelectionDAG &DAG) {
16199 MVT VT = Op.getSimpleValueType();
16201 // Decompose 256-bit ops into smaller 128-bit ops.
16202 if (VT.is256BitVector() && !Subtarget->hasInt256())
16203 return Lower256IntArith(Op, DAG);
16205 SDValue A = Op.getOperand(0);
16206 SDValue B = Op.getOperand(1);
16208 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16209 // pairs, multiply and truncate.
16210 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16211 if (Subtarget->hasInt256()) {
16212 if (VT == MVT::v32i8) {
16213 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16214 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16215 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16216 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16217 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16218 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16219 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16220 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16221 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16222 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16225 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16226 return DAG.getNode(
16227 ISD::TRUNCATE, dl, VT,
16228 DAG.getNode(ISD::MUL, dl, ExVT,
16229 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16230 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16233 assert(VT == MVT::v16i8 &&
16234 "Pre-AVX2 support only supports v16i8 multiplication");
16235 MVT ExVT = MVT::v8i16;
16237 // Extract the lo parts and sign extend to i16
16239 if (Subtarget->hasSSE41()) {
16240 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16241 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16243 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16244 -1, 4, -1, 5, -1, 6, -1, 7};
16245 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16246 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16247 ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16248 BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16249 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16250 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16253 // Extract the hi parts and sign extend to i16
16255 if (Subtarget->hasSSE41()) {
16256 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16257 -1, -1, -1, -1, -1, -1, -1, -1};
16258 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16259 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16260 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16261 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16263 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16264 -1, 12, -1, 13, -1, 14, -1, 15};
16265 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16266 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16267 AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16268 BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16269 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16270 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16273 // Multiply, mask the lower 8bits of the lo/hi results and pack
16274 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16275 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16276 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16277 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16278 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16281 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16282 if (VT == MVT::v4i32) {
16283 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16284 "Should not custom lower when pmuldq is available!");
16286 // Extract the odd parts.
16287 static const int UnpackMask[] = { 1, -1, 3, -1 };
16288 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16289 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16291 // Multiply the even parts.
16292 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16293 // Now multiply odd parts.
16294 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16296 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16297 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16299 // Merge the two vectors back together with a shuffle. This expands into 2
16301 static const int ShufMask[] = { 0, 4, 2, 6 };
16302 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16305 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16306 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16308 // Ahi = psrlqi(a, 32);
16309 // Bhi = psrlqi(b, 32);
16311 // AloBlo = pmuludq(a, b);
16312 // AloBhi = pmuludq(a, Bhi);
16313 // AhiBlo = pmuludq(Ahi, b);
16315 // AloBhi = psllqi(AloBhi, 32);
16316 // AhiBlo = psllqi(AhiBlo, 32);
16317 // return AloBlo + AloBhi + AhiBlo;
16319 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16320 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16322 // Bit cast to 32-bit vectors for MULUDQ
16323 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16324 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16325 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16326 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16327 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16328 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16330 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16331 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16332 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16334 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16335 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16337 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16338 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16341 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16342 assert(Subtarget->isTargetWin64() && "Unexpected target");
16343 EVT VT = Op.getValueType();
16344 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16345 "Unexpected return type for lowering");
16349 switch (Op->getOpcode()) {
16350 default: llvm_unreachable("Unexpected request for libcall!");
16351 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
16352 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
16353 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
16354 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
16355 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
16356 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16360 SDValue InChain = DAG.getEntryNode();
16362 TargetLowering::ArgListTy Args;
16363 TargetLowering::ArgListEntry Entry;
16364 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16365 EVT ArgVT = Op->getOperand(i).getValueType();
16366 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16367 "Unexpected argument type for lowering");
16368 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16369 Entry.Node = StackPtr;
16370 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16372 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16373 Entry.Ty = PointerType::get(ArgTy,0);
16374 Entry.isSExt = false;
16375 Entry.isZExt = false;
16376 Args.push_back(Entry);
16379 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16382 TargetLowering::CallLoweringInfo CLI(DAG);
16383 CLI.setDebugLoc(dl).setChain(InChain)
16384 .setCallee(getLibcallCallingConv(LC),
16385 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16386 Callee, std::move(Args), 0)
16387 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16389 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16390 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16393 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16394 SelectionDAG &DAG) {
16395 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16396 EVT VT = Op0.getValueType();
16399 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16400 (VT == MVT::v8i32 && Subtarget->hasInt256()));
16402 // PMULxD operations multiply each even value (starting at 0) of LHS with
16403 // the related value of RHS and produce a widen result.
16404 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16405 // => <2 x i64> <ae|cg>
16407 // In other word, to have all the results, we need to perform two PMULxD:
16408 // 1. one with the even values.
16409 // 2. one with the odd values.
16410 // To achieve #2, with need to place the odd values at an even position.
16412 // Place the odd value at an even position (basically, shift all values 1
16413 // step to the left):
16414 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16415 // <a|b|c|d> => <b|undef|d|undef>
16416 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16417 // <e|f|g|h> => <f|undef|h|undef>
16418 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16420 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16422 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16423 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16425 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16426 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16427 // => <2 x i64> <ae|cg>
16428 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16429 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16430 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16431 // => <2 x i64> <bf|dh>
16432 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16433 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16435 // Shuffle it back into the right order.
16436 SDValue Highs, Lows;
16437 if (VT == MVT::v8i32) {
16438 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16439 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16440 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16441 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16443 const int HighMask[] = {1, 5, 3, 7};
16444 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16445 const int LowMask[] = {0, 4, 2, 6};
16446 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16449 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16450 // unsigned multiply.
16451 if (IsSigned && !Subtarget->hasSSE41()) {
16453 DAG.getConstant(31, dl,
16454 DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16455 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16456 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16457 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16458 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16460 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16461 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16464 // The first result of MUL_LOHI is actually the low value, followed by the
16466 SDValue Ops[] = {Lows, Highs};
16467 return DAG.getMergeValues(Ops, dl);
16470 // Return true if the requred (according to Opcode) shift-imm form is natively
16471 // supported by the Subtarget
16472 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16474 if (VT.getScalarSizeInBits() < 16)
16477 if (VT.is512BitVector() &&
16478 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16481 bool LShift = VT.is128BitVector() ||
16482 (VT.is256BitVector() && Subtarget->hasInt256());
16484 bool AShift = LShift && (Subtarget->hasVLX() ||
16485 (VT != MVT::v2i64 && VT != MVT::v4i64));
16486 return (Opcode == ISD::SRA) ? AShift : LShift;
16489 // The shift amount is a variable, but it is the same for all vector lanes.
16490 // These instrcutions are defined together with shift-immediate.
16492 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
16494 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16497 // Return true if the requred (according to Opcode) variable-shift form is
16498 // natively supported by the Subtarget
16499 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
16502 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16505 // vXi16 supported only on AVX-512, BWI
16506 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16509 if (VT.is512BitVector() || Subtarget->hasVLX())
16512 bool LShift = VT.is128BitVector() || VT.is256BitVector();
16513 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
16514 return (Opcode == ISD::SRA) ? AShift : LShift;
16517 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16518 const X86Subtarget *Subtarget) {
16519 MVT VT = Op.getSimpleValueType();
16521 SDValue R = Op.getOperand(0);
16522 SDValue Amt = Op.getOperand(1);
16524 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16525 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16527 // Optimize shl/srl/sra with constant shift amount.
16528 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16529 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16530 uint64_t ShiftAmt = ShiftConst->getZExtValue();
16532 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16533 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16535 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16536 unsigned NumElts = VT.getVectorNumElements();
16537 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16539 if (Op.getOpcode() == ISD::SHL) {
16540 // Simple i8 add case
16542 return DAG.getNode(ISD::ADD, dl, VT, R, R);
16544 // Make a large shift.
16545 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16547 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16548 // Zero out the rightmost bits.
16549 SmallVector<SDValue, 32> V(
16550 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16551 return DAG.getNode(ISD::AND, dl, VT, SHL,
16552 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16554 if (Op.getOpcode() == ISD::SRL) {
16555 // Make a large shift.
16556 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16558 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16559 // Zero out the leftmost bits.
16560 SmallVector<SDValue, 32> V(
16561 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16562 return DAG.getNode(ISD::AND, dl, VT, SRL,
16563 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16565 if (Op.getOpcode() == ISD::SRA) {
16566 if (ShiftAmt == 7) {
16567 // R s>> 7 === R s< 0
16568 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16569 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16572 // R s>> a === ((R u>> a) ^ m) - m
16573 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16574 SmallVector<SDValue, 32> V(NumElts,
16575 DAG.getConstant(128 >> ShiftAmt, dl,
16577 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16578 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16579 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16582 llvm_unreachable("Unknown shift opcode.");
16587 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16588 if (!Subtarget->is64Bit() &&
16589 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16590 Amt.getOpcode() == ISD::BITCAST &&
16591 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16592 Amt = Amt.getOperand(0);
16593 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16594 VT.getVectorNumElements();
16595 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16596 uint64_t ShiftAmt = 0;
16597 for (unsigned i = 0; i != Ratio; ++i) {
16598 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16602 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16604 // Check remaining shift amounts.
16605 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16606 uint64_t ShAmt = 0;
16607 for (unsigned j = 0; j != Ratio; ++j) {
16608 ConstantSDNode *C =
16609 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16613 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16615 if (ShAmt != ShiftAmt)
16618 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16624 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16625 const X86Subtarget* Subtarget) {
16626 MVT VT = Op.getSimpleValueType();
16628 SDValue R = Op.getOperand(0);
16629 SDValue Amt = Op.getOperand(1);
16631 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16632 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16634 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16635 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16637 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16639 EVT EltVT = VT.getVectorElementType();
16641 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16642 // Check if this build_vector node is doing a splat.
16643 // If so, then set BaseShAmt equal to the splat value.
16644 BaseShAmt = BV->getSplatValue();
16645 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16646 BaseShAmt = SDValue();
16648 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16649 Amt = Amt.getOperand(0);
16651 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16652 if (SVN && SVN->isSplat()) {
16653 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16654 SDValue InVec = Amt.getOperand(0);
16655 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16656 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16657 "Unexpected shuffle index found!");
16658 BaseShAmt = InVec.getOperand(SplatIdx);
16659 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16660 if (ConstantSDNode *C =
16661 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16662 if (C->getZExtValue() == SplatIdx)
16663 BaseShAmt = InVec.getOperand(1);
16668 // Avoid introducing an extract element from a shuffle.
16669 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16670 DAG.getIntPtrConstant(SplatIdx, dl));
16674 if (BaseShAmt.getNode()) {
16675 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16676 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16677 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16678 else if (EltVT.bitsLT(MVT::i32))
16679 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16681 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16685 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16686 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
16687 Amt.getOpcode() == ISD::BITCAST &&
16688 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16689 Amt = Amt.getOperand(0);
16690 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16691 VT.getVectorNumElements();
16692 std::vector<SDValue> Vals(Ratio);
16693 for (unsigned i = 0; i != Ratio; ++i)
16694 Vals[i] = Amt.getOperand(i);
16695 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16696 for (unsigned j = 0; j != Ratio; ++j)
16697 if (Vals[j] != Amt.getOperand(i + j))
16700 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16705 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16706 SelectionDAG &DAG) {
16707 MVT VT = Op.getSimpleValueType();
16709 SDValue R = Op.getOperand(0);
16710 SDValue Amt = Op.getOperand(1);
16712 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16713 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16715 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16718 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16721 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16724 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16725 // shifts per-lane and then shuffle the partial results back together.
16726 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16727 // Splat the shift amounts so the scalar shifts above will catch it.
16728 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16729 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16730 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16731 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16732 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16735 // If possible, lower this packed shift into a vector multiply instead of
16736 // expanding it into a sequence of scalar shifts.
16737 // Do this only if the vector shift count is a constant build_vector.
16738 if (Op.getOpcode() == ISD::SHL &&
16739 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16740 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16741 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16742 SmallVector<SDValue, 8> Elts;
16743 EVT SVT = VT.getScalarType();
16744 unsigned SVTBits = SVT.getSizeInBits();
16745 const APInt &One = APInt(SVTBits, 1);
16746 unsigned NumElems = VT.getVectorNumElements();
16748 for (unsigned i=0; i !=NumElems; ++i) {
16749 SDValue Op = Amt->getOperand(i);
16750 if (Op->getOpcode() == ISD::UNDEF) {
16751 Elts.push_back(Op);
16755 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16756 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16757 uint64_t ShAmt = C.getZExtValue();
16758 if (ShAmt >= SVTBits) {
16759 Elts.push_back(DAG.getUNDEF(SVT));
16762 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16764 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16765 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16768 // Lower SHL with variable shift amount.
16769 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16770 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16772 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16773 DAG.getConstant(0x3f800000U, dl, VT));
16774 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16775 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16776 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16779 // If possible, lower this shift as a sequence of two shifts by
16780 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16782 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16784 // Could be rewritten as:
16785 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16787 // The advantage is that the two shifts from the example would be
16788 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16789 // the vector shift into four scalar shifts plus four pairs of vector
16791 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16792 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16793 unsigned TargetOpcode = X86ISD::MOVSS;
16794 bool CanBeSimplified;
16795 // The splat value for the first packed shift (the 'X' from the example).
16796 SDValue Amt1 = Amt->getOperand(0);
16797 // The splat value for the second packed shift (the 'Y' from the example).
16798 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16799 Amt->getOperand(2);
16801 // See if it is possible to replace this node with a sequence of
16802 // two shifts followed by a MOVSS/MOVSD
16803 if (VT == MVT::v4i32) {
16804 // Check if it is legal to use a MOVSS.
16805 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16806 Amt2 == Amt->getOperand(3);
16807 if (!CanBeSimplified) {
16808 // Otherwise, check if we can still simplify this node using a MOVSD.
16809 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16810 Amt->getOperand(2) == Amt->getOperand(3);
16811 TargetOpcode = X86ISD::MOVSD;
16812 Amt2 = Amt->getOperand(2);
16815 // Do similar checks for the case where the machine value type
16817 CanBeSimplified = Amt1 == Amt->getOperand(1);
16818 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16819 CanBeSimplified = Amt2 == Amt->getOperand(i);
16821 if (!CanBeSimplified) {
16822 TargetOpcode = X86ISD::MOVSD;
16823 CanBeSimplified = true;
16824 Amt2 = Amt->getOperand(4);
16825 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16826 CanBeSimplified = Amt1 == Amt->getOperand(i);
16827 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16828 CanBeSimplified = Amt2 == Amt->getOperand(j);
16832 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16833 isa<ConstantSDNode>(Amt2)) {
16834 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16835 EVT CastVT = MVT::v4i32;
16837 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16838 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16840 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16841 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16842 if (TargetOpcode == X86ISD::MOVSD)
16843 CastVT = MVT::v2i64;
16844 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16845 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16846 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16848 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16852 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16853 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16854 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16856 SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16857 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16858 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16860 // r = VSELECT(r, shl(r, 4), a);
16861 SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16862 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16865 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16866 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16867 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16869 // r = VSELECT(r, shl(r, 2), a);
16870 M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16871 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16874 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16875 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16876 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16878 // return VSELECT(r, r+r, a);
16879 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16880 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16884 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16885 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16886 // solution better.
16887 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16888 MVT ExtVT = MVT::v8i32;
16890 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16891 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
16892 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
16893 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16894 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
16897 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
16898 MVT ExtVT = MVT::v8i32;
16899 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
16900 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
16901 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
16902 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
16903 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
16904 ALo = DAG.getNode(ISD::BITCAST, dl, ExtVT, ALo);
16905 AHi = DAG.getNode(ISD::BITCAST, dl, ExtVT, AHi);
16906 RLo = DAG.getNode(ISD::BITCAST, dl, ExtVT, RLo);
16907 RHi = DAG.getNode(ISD::BITCAST, dl, ExtVT, RHi);
16908 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
16909 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
16910 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
16911 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
16912 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
16915 // Decompose 256-bit shifts into smaller 128-bit shifts.
16916 if (VT.is256BitVector()) {
16917 unsigned NumElems = VT.getVectorNumElements();
16918 MVT EltVT = VT.getVectorElementType();
16919 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16921 // Extract the two vectors
16922 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16923 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16925 // Recreate the shift amount vectors
16926 SDValue Amt1, Amt2;
16927 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16928 // Constant shift amount
16929 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16930 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16931 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16933 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16934 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16936 // Variable shift amount
16937 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16938 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16941 // Issue new vector shifts for the smaller types
16942 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16943 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16945 // Concatenate the result back
16946 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16952 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16953 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16954 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16955 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16956 // has only one use.
16957 SDNode *N = Op.getNode();
16958 SDValue LHS = N->getOperand(0);
16959 SDValue RHS = N->getOperand(1);
16960 unsigned BaseOp = 0;
16963 switch (Op.getOpcode()) {
16964 default: llvm_unreachable("Unknown ovf instruction!");
16966 // A subtract of one will be selected as a INC. Note that INC doesn't
16967 // set CF, so we can't do this for UADDO.
16968 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16970 BaseOp = X86ISD::INC;
16971 Cond = X86::COND_O;
16974 BaseOp = X86ISD::ADD;
16975 Cond = X86::COND_O;
16978 BaseOp = X86ISD::ADD;
16979 Cond = X86::COND_B;
16982 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16983 // set CF, so we can't do this for USUBO.
16984 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16986 BaseOp = X86ISD::DEC;
16987 Cond = X86::COND_O;
16990 BaseOp = X86ISD::SUB;
16991 Cond = X86::COND_O;
16994 BaseOp = X86ISD::SUB;
16995 Cond = X86::COND_B;
16998 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16999 Cond = X86::COND_O;
17001 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17002 if (N->getValueType(0) == MVT::i8) {
17003 BaseOp = X86ISD::UMUL8;
17004 Cond = X86::COND_O;
17007 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17009 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17012 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17013 DAG.getConstant(X86::COND_O, DL, MVT::i32),
17014 SDValue(Sum.getNode(), 2));
17016 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17020 // Also sets EFLAGS.
17021 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17022 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17025 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17026 DAG.getConstant(Cond, DL, MVT::i32),
17027 SDValue(Sum.getNode(), 1));
17029 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17032 /// Returns true if the operand type is exactly twice the native width, and
17033 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17034 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17035 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17036 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17037 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17040 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17041 else if (OpWidth == 128)
17042 return Subtarget->hasCmpxchg16b();
17047 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17048 return needsCmpXchgNb(SI->getValueOperand()->getType());
17051 // Note: this turns large loads into lock cmpxchg8b/16b.
17052 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17053 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17054 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17055 return needsCmpXchgNb(PTy->getElementType());
17058 TargetLoweringBase::AtomicRMWExpansionKind
17059 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17060 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17061 const Type *MemType = AI->getType();
17063 // If the operand is too big, we must see if cmpxchg8/16b is available
17064 // and default to library calls otherwise.
17065 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17066 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17067 : AtomicRMWExpansionKind::None;
17070 AtomicRMWInst::BinOp Op = AI->getOperation();
17073 llvm_unreachable("Unknown atomic operation");
17074 case AtomicRMWInst::Xchg:
17075 case AtomicRMWInst::Add:
17076 case AtomicRMWInst::Sub:
17077 // It's better to use xadd, xsub or xchg for these in all cases.
17078 return AtomicRMWExpansionKind::None;
17079 case AtomicRMWInst::Or:
17080 case AtomicRMWInst::And:
17081 case AtomicRMWInst::Xor:
17082 // If the atomicrmw's result isn't actually used, we can just add a "lock"
17083 // prefix to a normal instruction for these operations.
17084 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17085 : AtomicRMWExpansionKind::None;
17086 case AtomicRMWInst::Nand:
17087 case AtomicRMWInst::Max:
17088 case AtomicRMWInst::Min:
17089 case AtomicRMWInst::UMax:
17090 case AtomicRMWInst::UMin:
17091 // These always require a non-trivial set of data operations on x86. We must
17092 // use a cmpxchg loop.
17093 return AtomicRMWExpansionKind::CmpXChg;
17097 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17098 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17099 // no-sse2). There isn't any reason to disable it if the target processor
17101 return Subtarget.hasSSE2() || Subtarget.is64Bit();
17105 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17106 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17107 const Type *MemType = AI->getType();
17108 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17109 // there is no benefit in turning such RMWs into loads, and it is actually
17110 // harmful as it introduces a mfence.
17111 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17114 auto Builder = IRBuilder<>(AI);
17115 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17116 auto SynchScope = AI->getSynchScope();
17117 // We must restrict the ordering to avoid generating loads with Release or
17118 // ReleaseAcquire orderings.
17119 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17120 auto Ptr = AI->getPointerOperand();
17122 // Before the load we need a fence. Here is an example lifted from
17123 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17126 // x.store(1, relaxed);
17127 // r1 = y.fetch_add(0, release);
17129 // y.fetch_add(42, acquire);
17130 // r2 = x.load(relaxed);
17131 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17132 // lowered to just a load without a fence. A mfence flushes the store buffer,
17133 // making the optimization clearly correct.
17134 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17135 // otherwise, we might be able to be more agressive on relaxed idempotent
17136 // rmw. In practice, they do not look useful, so we don't try to be
17137 // especially clever.
17138 if (SynchScope == SingleThread)
17139 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17140 // the IR level, so we must wrap it in an intrinsic.
17143 if (!hasMFENCE(*Subtarget))
17144 // FIXME: it might make sense to use a locked operation here but on a
17145 // different cache-line to prevent cache-line bouncing. In practice it
17146 // is probably a small win, and x86 processors without mfence are rare
17147 // enough that we do not bother.
17151 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17152 Builder.CreateCall(MFence, {});
17154 // Finally we can emit the atomic load.
17155 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17156 AI->getType()->getPrimitiveSizeInBits());
17157 Loaded->setAtomic(Order, SynchScope);
17158 AI->replaceAllUsesWith(Loaded);
17159 AI->eraseFromParent();
17163 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17164 SelectionDAG &DAG) {
17166 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17167 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17168 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17169 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17171 // The only fence that needs an instruction is a sequentially-consistent
17172 // cross-thread fence.
17173 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17174 if (hasMFENCE(*Subtarget))
17175 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17177 SDValue Chain = Op.getOperand(0);
17178 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17180 DAG.getRegister(X86::ESP, MVT::i32), // Base
17181 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
17182 DAG.getRegister(0, MVT::i32), // Index
17183 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
17184 DAG.getRegister(0, MVT::i32), // Segment.
17188 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17189 return SDValue(Res, 0);
17192 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17193 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17196 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17197 SelectionDAG &DAG) {
17198 MVT T = Op.getSimpleValueType();
17202 switch(T.SimpleTy) {
17203 default: llvm_unreachable("Invalid value type!");
17204 case MVT::i8: Reg = X86::AL; size = 1; break;
17205 case MVT::i16: Reg = X86::AX; size = 2; break;
17206 case MVT::i32: Reg = X86::EAX; size = 4; break;
17208 assert(Subtarget->is64Bit() && "Node not type legal!");
17209 Reg = X86::RAX; size = 8;
17212 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17213 Op.getOperand(2), SDValue());
17214 SDValue Ops[] = { cpIn.getValue(0),
17217 DAG.getTargetConstant(size, DL, MVT::i8),
17218 cpIn.getValue(1) };
17219 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17220 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17221 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17225 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17226 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17227 MVT::i32, cpOut.getValue(2));
17228 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17229 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17232 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17233 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17234 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17238 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17239 SelectionDAG &DAG) {
17240 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17241 MVT DstVT = Op.getSimpleValueType();
17243 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17244 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17245 if (DstVT != MVT::f64)
17246 // This conversion needs to be expanded.
17249 SDValue InVec = Op->getOperand(0);
17251 unsigned NumElts = SrcVT.getVectorNumElements();
17252 EVT SVT = SrcVT.getVectorElementType();
17254 // Widen the vector in input in the case of MVT::v2i32.
17255 // Example: from MVT::v2i32 to MVT::v4i32.
17256 SmallVector<SDValue, 16> Elts;
17257 for (unsigned i = 0, e = NumElts; i != e; ++i)
17258 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17259 DAG.getIntPtrConstant(i, dl)));
17261 // Explicitly mark the extra elements as Undef.
17262 Elts.append(NumElts, DAG.getUNDEF(SVT));
17264 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17265 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17266 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17267 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17268 DAG.getIntPtrConstant(0, dl));
17271 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17272 Subtarget->hasMMX() && "Unexpected custom BITCAST");
17273 assert((DstVT == MVT::i64 ||
17274 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17275 "Unexpected custom BITCAST");
17276 // i64 <=> MMX conversions are Legal.
17277 if (SrcVT==MVT::i64 && DstVT.isVector())
17279 if (DstVT==MVT::i64 && SrcVT.isVector())
17281 // MMX <=> MMX conversions are Legal.
17282 if (SrcVT.isVector() && DstVT.isVector())
17284 // All other conversions need to be expanded.
17288 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17289 SelectionDAG &DAG) {
17290 SDNode *Node = Op.getNode();
17293 Op = Op.getOperand(0);
17294 EVT VT = Op.getValueType();
17295 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17296 "CTPOP lowering only implemented for 128/256-bit wide vector types");
17298 unsigned NumElts = VT.getVectorNumElements();
17299 EVT EltVT = VT.getVectorElementType();
17300 unsigned Len = EltVT.getSizeInBits();
17302 // This is the vectorized version of the "best" algorithm from
17303 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17304 // with a minor tweak to use a series of adds + shifts instead of vector
17305 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17307 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17308 // v8i32 => Always profitable
17310 // FIXME: There a couple of possible improvements:
17312 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17313 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17315 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17316 "CTPOP not implemented for this vector element type.");
17318 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17319 // extra legalization.
17320 bool NeedsBitcast = EltVT == MVT::i32;
17321 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17323 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17325 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17327 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17330 // v = v - ((v >> 1) & 0x55555555...)
17331 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17332 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17333 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17335 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17337 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17338 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17340 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17342 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17343 if (VT != And.getValueType())
17344 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17345 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17347 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17348 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17349 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17350 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17351 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17353 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17354 if (NeedsBitcast) {
17355 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17356 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17357 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17360 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17361 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17362 if (VT != AndRHS.getValueType()) {
17363 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17364 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17366 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17368 // v = (v + (v >> 4)) & 0x0F0F0F0F...
17369 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17370 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17371 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17372 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17374 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17375 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17376 if (NeedsBitcast) {
17377 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17378 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17380 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17381 if (VT != And.getValueType())
17382 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17384 // The algorithm mentioned above uses:
17385 // v = (v * 0x01010101...) >> (Len - 8)
17387 // Change it to use vector adds + vector shifts which yield faster results on
17388 // Haswell than using vector integer multiplication.
17390 // For i32 elements:
17391 // v = v + (v >> 8)
17392 // v = v + (v >> 16)
17394 // For i64 elements:
17395 // v = v + (v >> 8)
17396 // v = v + (v >> 16)
17397 // v = v + (v >> 32)
17400 SmallVector<SDValue, 8> Csts;
17401 for (unsigned i = 8; i <= Len/2; i *= 2) {
17402 Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17403 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17404 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17405 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17409 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17410 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17412 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17413 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17414 if (NeedsBitcast) {
17415 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17416 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17418 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17419 if (VT != And.getValueType())
17420 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17425 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17426 SDNode *Node = Op.getNode();
17428 EVT T = Node->getValueType(0);
17429 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17430 DAG.getConstant(0, dl, T), Node->getOperand(2));
17431 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17432 cast<AtomicSDNode>(Node)->getMemoryVT(),
17433 Node->getOperand(0),
17434 Node->getOperand(1), negOp,
17435 cast<AtomicSDNode>(Node)->getMemOperand(),
17436 cast<AtomicSDNode>(Node)->getOrdering(),
17437 cast<AtomicSDNode>(Node)->getSynchScope());
17440 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17441 SDNode *Node = Op.getNode();
17443 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17445 // Convert seq_cst store -> xchg
17446 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17447 // FIXME: On 32-bit, store -> fist or movq would be more efficient
17448 // (The only way to get a 16-byte store is cmpxchg16b)
17449 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17450 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17451 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17452 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17453 cast<AtomicSDNode>(Node)->getMemoryVT(),
17454 Node->getOperand(0),
17455 Node->getOperand(1), Node->getOperand(2),
17456 cast<AtomicSDNode>(Node)->getMemOperand(),
17457 cast<AtomicSDNode>(Node)->getOrdering(),
17458 cast<AtomicSDNode>(Node)->getSynchScope());
17459 return Swap.getValue(1);
17461 // Other atomic stores have a simple pattern.
17465 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17466 EVT VT = Op.getNode()->getSimpleValueType(0);
17468 // Let legalize expand this if it isn't a legal type yet.
17469 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17472 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17475 bool ExtraOp = false;
17476 switch (Op.getOpcode()) {
17477 default: llvm_unreachable("Invalid code");
17478 case ISD::ADDC: Opc = X86ISD::ADD; break;
17479 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17480 case ISD::SUBC: Opc = X86ISD::SUB; break;
17481 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17485 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17487 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17488 Op.getOperand(1), Op.getOperand(2));
17491 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17492 SelectionDAG &DAG) {
17493 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17495 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17496 // which returns the values as { float, float } (in XMM0) or
17497 // { double, double } (which is returned in XMM0, XMM1).
17499 SDValue Arg = Op.getOperand(0);
17500 EVT ArgVT = Arg.getValueType();
17501 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17503 TargetLowering::ArgListTy Args;
17504 TargetLowering::ArgListEntry Entry;
17508 Entry.isSExt = false;
17509 Entry.isZExt = false;
17510 Args.push_back(Entry);
17512 bool isF64 = ArgVT == MVT::f64;
17513 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17514 // the small struct {f32, f32} is returned in (eax, edx). For f64,
17515 // the results are returned via SRet in memory.
17516 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
17517 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17518 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17520 Type *RetTy = isF64
17521 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17522 : (Type*)VectorType::get(ArgTy, 4);
17524 TargetLowering::CallLoweringInfo CLI(DAG);
17525 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17526 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17528 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17531 // Returned in xmm0 and xmm1.
17532 return CallResult.first;
17534 // Returned in bits 0:31 and 32:64 xmm0.
17535 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17536 CallResult.first, DAG.getIntPtrConstant(0, dl));
17537 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17538 CallResult.first, DAG.getIntPtrConstant(1, dl));
17539 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17540 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17543 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17544 SelectionDAG &DAG) {
17545 assert(Subtarget->hasAVX512() &&
17546 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17548 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17549 EVT VT = N->getValue().getValueType();
17550 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17553 // X86 scatter kills mask register, so its type should be added to
17554 // the list of return values
17555 if (N->getNumValues() == 1) {
17556 SDValue Index = N->getIndex();
17557 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17558 !Index.getValueType().is512BitVector())
17559 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17561 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17562 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17563 N->getOperand(3), Index };
17565 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17566 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17567 return SDValue(NewScatter.getNode(), 0);
17572 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17573 SelectionDAG &DAG) {
17574 assert(Subtarget->hasAVX512() &&
17575 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17577 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17578 EVT VT = Op.getValueType();
17579 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17582 SDValue Index = N->getIndex();
17583 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17584 !Index.getValueType().is512BitVector()) {
17585 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17586 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17587 N->getOperand(3), Index };
17588 DAG.UpdateNodeOperands(N, Ops);
17593 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17594 SelectionDAG &DAG) const {
17595 // TODO: Eventually, the lowering of these nodes should be informed by or
17596 // deferred to the GC strategy for the function in which they appear. For
17597 // now, however, they must be lowered to something. Since they are logically
17598 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17599 // require special handling for these nodes), lower them as literal NOOPs for
17601 SmallVector<SDValue, 2> Ops;
17603 Ops.push_back(Op.getOperand(0));
17604 if (Op->getGluedNode())
17605 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17608 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17609 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17614 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17615 SelectionDAG &DAG) const {
17616 // TODO: Eventually, the lowering of these nodes should be informed by or
17617 // deferred to the GC strategy for the function in which they appear. For
17618 // now, however, they must be lowered to something. Since they are logically
17619 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17620 // require special handling for these nodes), lower them as literal NOOPs for
17622 SmallVector<SDValue, 2> Ops;
17624 Ops.push_back(Op.getOperand(0));
17625 if (Op->getGluedNode())
17626 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17629 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17630 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17635 /// LowerOperation - Provide custom lowering hooks for some operations.
17637 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17638 switch (Op.getOpcode()) {
17639 default: llvm_unreachable("Should not custom lower this!");
17640 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17641 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17642 return LowerCMP_SWAP(Op, Subtarget, DAG);
17643 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
17644 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
17645 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
17646 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
17647 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17648 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
17649 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17650 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17651 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17652 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17653 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17654 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17655 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17656 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17657 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17658 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17659 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17660 case ISD::SHL_PARTS:
17661 case ISD::SRA_PARTS:
17662 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17663 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17664 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17665 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17666 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17667 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17668 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17669 case ISD::SIGN_EXTEND_VECTOR_INREG:
17670 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
17671 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17672 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17673 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17674 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17676 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17677 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17678 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17679 case ISD::SETCC: return LowerSETCC(Op, DAG);
17680 case ISD::SELECT: return LowerSELECT(Op, DAG);
17681 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17682 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17683 case ISD::VASTART: return LowerVASTART(Op, DAG);
17684 case ISD::VAARG: return LowerVAARG(Op, DAG);
17685 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17686 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17687 case ISD::INTRINSIC_VOID:
17688 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17689 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17690 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17691 case ISD::FRAME_TO_ARGS_OFFSET:
17692 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17693 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17694 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17695 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17696 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17697 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17698 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17699 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17700 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17701 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17702 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17703 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17704 case ISD::UMUL_LOHI:
17705 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17708 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17714 case ISD::UMULO: return LowerXALUO(Op, DAG);
17715 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17716 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17720 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17721 case ISD::ADD: return LowerADD(Op, DAG);
17722 case ISD::SUB: return LowerSUB(Op, DAG);
17723 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17724 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
17725 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
17726 case ISD::GC_TRANSITION_START:
17727 return LowerGC_TRANSITION_START(Op, DAG);
17728 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
17732 /// ReplaceNodeResults - Replace a node with an illegal result type
17733 /// with a new node built out of custom code.
17734 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17735 SmallVectorImpl<SDValue>&Results,
17736 SelectionDAG &DAG) const {
17738 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17739 switch (N->getOpcode()) {
17741 llvm_unreachable("Do not know how to custom type legalize this operation!");
17742 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17743 case X86ISD::FMINC:
17745 case X86ISD::FMAXC:
17746 case X86ISD::FMAX: {
17747 EVT VT = N->getValueType(0);
17748 if (VT != MVT::v2f32)
17749 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17750 SDValue UNDEF = DAG.getUNDEF(VT);
17751 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17752 N->getOperand(0), UNDEF);
17753 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17754 N->getOperand(1), UNDEF);
17755 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17758 case ISD::SIGN_EXTEND_INREG:
17763 // We don't want to expand or promote these.
17770 case ISD::UDIVREM: {
17771 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17772 Results.push_back(V);
17775 case ISD::FP_TO_SINT:
17776 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
17777 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17778 if (N->getOperand(0).getValueType() == MVT::f16)
17781 case ISD::FP_TO_UINT: {
17782 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17784 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17787 std::pair<SDValue,SDValue> Vals =
17788 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17789 SDValue FIST = Vals.first, StackSlot = Vals.second;
17790 if (FIST.getNode()) {
17791 EVT VT = N->getValueType(0);
17792 // Return a load from the stack slot.
17793 if (StackSlot.getNode())
17794 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17795 MachinePointerInfo(),
17796 false, false, false, 0));
17798 Results.push_back(FIST);
17802 case ISD::UINT_TO_FP: {
17803 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17804 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17805 N->getValueType(0) != MVT::v2f32)
17807 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17809 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17811 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17812 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17813 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17814 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17815 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17816 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17819 case ISD::FP_ROUND: {
17820 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17822 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17823 Results.push_back(V);
17826 case ISD::FP_EXTEND: {
17827 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17828 // No other ValueType for FP_EXTEND should reach this point.
17829 assert(N->getValueType(0) == MVT::v2f32 &&
17830 "Do not know how to legalize this Node");
17833 case ISD::INTRINSIC_W_CHAIN: {
17834 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17836 default : llvm_unreachable("Do not know how to custom type "
17837 "legalize this intrinsic operation!");
17838 case Intrinsic::x86_rdtsc:
17839 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17841 case Intrinsic::x86_rdtscp:
17842 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17844 case Intrinsic::x86_rdpmc:
17845 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17848 case ISD::READCYCLECOUNTER: {
17849 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17852 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17853 EVT T = N->getValueType(0);
17854 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17855 bool Regs64bit = T == MVT::i128;
17856 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17857 SDValue cpInL, cpInH;
17858 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17859 DAG.getConstant(0, dl, HalfT));
17860 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17861 DAG.getConstant(1, dl, HalfT));
17862 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17863 Regs64bit ? X86::RAX : X86::EAX,
17865 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17866 Regs64bit ? X86::RDX : X86::EDX,
17867 cpInH, cpInL.getValue(1));
17868 SDValue swapInL, swapInH;
17869 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17870 DAG.getConstant(0, dl, HalfT));
17871 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17872 DAG.getConstant(1, dl, HalfT));
17873 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17874 Regs64bit ? X86::RBX : X86::EBX,
17875 swapInL, cpInH.getValue(1));
17876 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17877 Regs64bit ? X86::RCX : X86::ECX,
17878 swapInH, swapInL.getValue(1));
17879 SDValue Ops[] = { swapInH.getValue(0),
17881 swapInH.getValue(1) };
17882 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17883 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17884 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17885 X86ISD::LCMPXCHG8_DAG;
17886 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17887 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17888 Regs64bit ? X86::RAX : X86::EAX,
17889 HalfT, Result.getValue(1));
17890 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17891 Regs64bit ? X86::RDX : X86::EDX,
17892 HalfT, cpOutL.getValue(2));
17893 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17895 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17896 MVT::i32, cpOutH.getValue(2));
17898 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17899 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17900 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17902 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17903 Results.push_back(Success);
17904 Results.push_back(EFLAGS.getValue(1));
17907 case ISD::ATOMIC_SWAP:
17908 case ISD::ATOMIC_LOAD_ADD:
17909 case ISD::ATOMIC_LOAD_SUB:
17910 case ISD::ATOMIC_LOAD_AND:
17911 case ISD::ATOMIC_LOAD_OR:
17912 case ISD::ATOMIC_LOAD_XOR:
17913 case ISD::ATOMIC_LOAD_NAND:
17914 case ISD::ATOMIC_LOAD_MIN:
17915 case ISD::ATOMIC_LOAD_MAX:
17916 case ISD::ATOMIC_LOAD_UMIN:
17917 case ISD::ATOMIC_LOAD_UMAX:
17918 case ISD::ATOMIC_LOAD: {
17919 // Delegate to generic TypeLegalization. Situations we can really handle
17920 // should have already been dealt with by AtomicExpandPass.cpp.
17923 case ISD::BITCAST: {
17924 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17925 EVT DstVT = N->getValueType(0);
17926 EVT SrcVT = N->getOperand(0)->getValueType(0);
17928 if (SrcVT != MVT::f64 ||
17929 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17932 unsigned NumElts = DstVT.getVectorNumElements();
17933 EVT SVT = DstVT.getVectorElementType();
17934 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17935 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17936 MVT::v2f64, N->getOperand(0));
17937 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17939 if (ExperimentalVectorWideningLegalization) {
17940 // If we are legalizing vectors by widening, we already have the desired
17941 // legal vector type, just return it.
17942 Results.push_back(ToVecInt);
17946 SmallVector<SDValue, 8> Elts;
17947 for (unsigned i = 0, e = NumElts; i != e; ++i)
17948 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17949 ToVecInt, DAG.getIntPtrConstant(i, dl)));
17951 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17956 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17957 switch ((X86ISD::NodeType)Opcode) {
17958 case X86ISD::FIRST_NUMBER: break;
17959 case X86ISD::BSF: return "X86ISD::BSF";
17960 case X86ISD::BSR: return "X86ISD::BSR";
17961 case X86ISD::SHLD: return "X86ISD::SHLD";
17962 case X86ISD::SHRD: return "X86ISD::SHRD";
17963 case X86ISD::FAND: return "X86ISD::FAND";
17964 case X86ISD::FANDN: return "X86ISD::FANDN";
17965 case X86ISD::FOR: return "X86ISD::FOR";
17966 case X86ISD::FXOR: return "X86ISD::FXOR";
17967 case X86ISD::FSRL: return "X86ISD::FSRL";
17968 case X86ISD::FILD: return "X86ISD::FILD";
17969 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17970 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17971 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17972 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17973 case X86ISD::FLD: return "X86ISD::FLD";
17974 case X86ISD::FST: return "X86ISD::FST";
17975 case X86ISD::CALL: return "X86ISD::CALL";
17976 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17977 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17978 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17979 case X86ISD::BT: return "X86ISD::BT";
17980 case X86ISD::CMP: return "X86ISD::CMP";
17981 case X86ISD::COMI: return "X86ISD::COMI";
17982 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17983 case X86ISD::CMPM: return "X86ISD::CMPM";
17984 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17985 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
17986 case X86ISD::SETCC: return "X86ISD::SETCC";
17987 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17988 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17989 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
17990 case X86ISD::CMOV: return "X86ISD::CMOV";
17991 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17992 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17993 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17994 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17995 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17996 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17997 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17998 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
17999 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
18000 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
18001 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
18002 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
18003 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
18004 case X86ISD::PINSRB: return "X86ISD::PINSRB";
18005 case X86ISD::PINSRW: return "X86ISD::PINSRW";
18006 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
18007 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
18008 case X86ISD::ANDNP: return "X86ISD::ANDNP";
18009 case X86ISD::PSIGN: return "X86ISD::PSIGN";
18010 case X86ISD::BLENDI: return "X86ISD::BLENDI";
18011 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
18012 case X86ISD::ADDUS: return "X86ISD::ADDUS";
18013 case X86ISD::SUBUS: return "X86ISD::SUBUS";
18014 case X86ISD::HADD: return "X86ISD::HADD";
18015 case X86ISD::HSUB: return "X86ISD::HSUB";
18016 case X86ISD::FHADD: return "X86ISD::FHADD";
18017 case X86ISD::FHSUB: return "X86ISD::FHSUB";
18018 case X86ISD::UMAX: return "X86ISD::UMAX";
18019 case X86ISD::UMIN: return "X86ISD::UMIN";
18020 case X86ISD::SMAX: return "X86ISD::SMAX";
18021 case X86ISD::SMIN: return "X86ISD::SMIN";
18022 case X86ISD::FMAX: return "X86ISD::FMAX";
18023 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
18024 case X86ISD::FMIN: return "X86ISD::FMIN";
18025 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
18026 case X86ISD::FMAXC: return "X86ISD::FMAXC";
18027 case X86ISD::FMINC: return "X86ISD::FMINC";
18028 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
18029 case X86ISD::FRCP: return "X86ISD::FRCP";
18030 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
18031 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
18032 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
18033 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
18034 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
18035 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
18036 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
18037 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
18038 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
18039 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
18040 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
18041 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
18042 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
18043 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
18044 case X86ISD::VZEXT: return "X86ISD::VZEXT";
18045 case X86ISD::VSEXT: return "X86ISD::VSEXT";
18046 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
18047 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
18048 case X86ISD::VINSERT: return "X86ISD::VINSERT";
18049 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
18050 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
18051 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
18052 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
18053 case X86ISD::VSHL: return "X86ISD::VSHL";
18054 case X86ISD::VSRL: return "X86ISD::VSRL";
18055 case X86ISD::VSRA: return "X86ISD::VSRA";
18056 case X86ISD::VSHLI: return "X86ISD::VSHLI";
18057 case X86ISD::VSRLI: return "X86ISD::VSRLI";
18058 case X86ISD::VSRAI: return "X86ISD::VSRAI";
18059 case X86ISD::CMPP: return "X86ISD::CMPP";
18060 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
18061 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
18062 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
18063 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
18064 case X86ISD::ADD: return "X86ISD::ADD";
18065 case X86ISD::SUB: return "X86ISD::SUB";
18066 case X86ISD::ADC: return "X86ISD::ADC";
18067 case X86ISD::SBB: return "X86ISD::SBB";
18068 case X86ISD::SMUL: return "X86ISD::SMUL";
18069 case X86ISD::UMUL: return "X86ISD::UMUL";
18070 case X86ISD::SMUL8: return "X86ISD::SMUL8";
18071 case X86ISD::UMUL8: return "X86ISD::UMUL8";
18072 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18073 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18074 case X86ISD::INC: return "X86ISD::INC";
18075 case X86ISD::DEC: return "X86ISD::DEC";
18076 case X86ISD::OR: return "X86ISD::OR";
18077 case X86ISD::XOR: return "X86ISD::XOR";
18078 case X86ISD::AND: return "X86ISD::AND";
18079 case X86ISD::BEXTR: return "X86ISD::BEXTR";
18080 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
18081 case X86ISD::PTEST: return "X86ISD::PTEST";
18082 case X86ISD::TESTP: return "X86ISD::TESTP";
18083 case X86ISD::TESTM: return "X86ISD::TESTM";
18084 case X86ISD::TESTNM: return "X86ISD::TESTNM";
18085 case X86ISD::KORTEST: return "X86ISD::KORTEST";
18086 case X86ISD::PACKSS: return "X86ISD::PACKSS";
18087 case X86ISD::PACKUS: return "X86ISD::PACKUS";
18088 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
18089 case X86ISD::VALIGN: return "X86ISD::VALIGN";
18090 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
18091 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
18092 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
18093 case X86ISD::SHUFP: return "X86ISD::SHUFP";
18094 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
18095 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
18096 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
18097 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
18098 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
18099 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
18100 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
18101 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
18102 case X86ISD::MOVSD: return "X86ISD::MOVSD";
18103 case X86ISD::MOVSS: return "X86ISD::MOVSS";
18104 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
18105 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
18106 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
18107 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
18108 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
18109 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
18110 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
18111 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
18112 case X86ISD::VPERMV: return "X86ISD::VPERMV";
18113 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
18114 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
18115 case X86ISD::VPERMI: return "X86ISD::VPERMI";
18116 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
18117 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
18118 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18119 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
18120 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
18121 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
18122 case X86ISD::MFENCE: return "X86ISD::MFENCE";
18123 case X86ISD::SFENCE: return "X86ISD::SFENCE";
18124 case X86ISD::LFENCE: return "X86ISD::LFENCE";
18125 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
18126 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
18127 case X86ISD::SAHF: return "X86ISD::SAHF";
18128 case X86ISD::RDRAND: return "X86ISD::RDRAND";
18129 case X86ISD::RDSEED: return "X86ISD::RDSEED";
18130 case X86ISD::FMADD: return "X86ISD::FMADD";
18131 case X86ISD::FMSUB: return "X86ISD::FMSUB";
18132 case X86ISD::FNMADD: return "X86ISD::FNMADD";
18133 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
18134 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
18135 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
18136 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
18137 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
18138 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
18139 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
18140 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
18141 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
18142 case X86ISD::RNDSCALE: return "X86ISD::RNDSCALE";
18143 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
18144 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
18145 case X86ISD::XTEST: return "X86ISD::XTEST";
18146 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
18147 case X86ISD::EXPAND: return "X86ISD::EXPAND";
18148 case X86ISD::SELECT: return "X86ISD::SELECT";
18149 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
18150 case X86ISD::RCP28: return "X86ISD::RCP28";
18151 case X86ISD::EXP2: return "X86ISD::EXP2";
18152 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
18153 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
18154 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
18155 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
18156 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
18157 case X86ISD::ADDS: return "X86ISD::ADDS";
18158 case X86ISD::SUBS: return "X86ISD::SUBS";
18163 // isLegalAddressingMode - Return true if the addressing mode represented
18164 // by AM is legal for this target, for a load/store of the specified type.
18165 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18167 // X86 supports extremely general addressing modes.
18168 CodeModel::Model M = getTargetMachine().getCodeModel();
18169 Reloc::Model R = getTargetMachine().getRelocationModel();
18171 // X86 allows a sign-extended 32-bit immediate field as a displacement.
18172 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18177 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18179 // If a reference to this global requires an extra load, we can't fold it.
18180 if (isGlobalStubReference(GVFlags))
18183 // If BaseGV requires a register for the PIC base, we cannot also have a
18184 // BaseReg specified.
18185 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18188 // If lower 4G is not available, then we must use rip-relative addressing.
18189 if ((M != CodeModel::Small || R != Reloc::Static) &&
18190 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18194 switch (AM.Scale) {
18200 // These scales always work.
18205 // These scales are formed with basereg+scalereg. Only accept if there is
18210 default: // Other stuff never works.
18217 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18218 unsigned Bits = Ty->getScalarSizeInBits();
18220 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18221 // particularly cheaper than those without.
18225 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18226 // variable shifts just as cheap as scalar ones.
18227 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18230 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18231 // fully general vector.
18235 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18236 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18238 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18239 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18240 return NumBits1 > NumBits2;
18243 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18244 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18247 if (!isTypeLegal(EVT::getEVT(Ty1)))
18250 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18252 // Assuming the caller doesn't have a zeroext or signext return parameter,
18253 // truncation all the way down to i1 is valid.
18257 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18258 return isInt<32>(Imm);
18261 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18262 // Can also use sub to handle negated immediates.
18263 return isInt<32>(Imm);
18266 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18267 if (!VT1.isInteger() || !VT2.isInteger())
18269 unsigned NumBits1 = VT1.getSizeInBits();
18270 unsigned NumBits2 = VT2.getSizeInBits();
18271 return NumBits1 > NumBits2;
18274 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18275 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18276 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18279 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18280 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18281 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18284 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18285 EVT VT1 = Val.getValueType();
18286 if (isZExtFree(VT1, VT2))
18289 if (Val.getOpcode() != ISD::LOAD)
18292 if (!VT1.isSimple() || !VT1.isInteger() ||
18293 !VT2.isSimple() || !VT2.isInteger())
18296 switch (VT1.getSimpleVT().SimpleTy) {
18301 // X86 has 8, 16, and 32-bit zero-extending loads.
18308 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18311 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18312 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18315 VT = VT.getScalarType();
18317 if (!VT.isSimple())
18320 switch (VT.getSimpleVT().SimpleTy) {
18331 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18332 // i16 instructions are longer (0x66 prefix) and potentially slower.
18333 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18336 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18337 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18338 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18339 /// are assumed to be legal.
18341 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18343 if (!VT.isSimple())
18346 // Not for i1 vectors
18347 if (VT.getScalarType() == MVT::i1)
18350 // Very little shuffling can be done for 64-bit vectors right now.
18351 if (VT.getSizeInBits() == 64)
18354 // We only care that the types being shuffled are legal. The lowering can
18355 // handle any possible shuffle mask that results.
18356 return isTypeLegal(VT.getSimpleVT());
18360 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18362 // Just delegate to the generic legality, clear masks aren't special.
18363 return isShuffleMaskLegal(Mask, VT);
18366 //===----------------------------------------------------------------------===//
18367 // X86 Scheduler Hooks
18368 //===----------------------------------------------------------------------===//
18370 /// Utility function to emit xbegin specifying the start of an RTM region.
18371 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18372 const TargetInstrInfo *TII) {
18373 DebugLoc DL = MI->getDebugLoc();
18375 const BasicBlock *BB = MBB->getBasicBlock();
18376 MachineFunction::iterator I = MBB;
18379 // For the v = xbegin(), we generate
18390 MachineBasicBlock *thisMBB = MBB;
18391 MachineFunction *MF = MBB->getParent();
18392 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18393 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18394 MF->insert(I, mainMBB);
18395 MF->insert(I, sinkMBB);
18397 // Transfer the remainder of BB and its successor edges to sinkMBB.
18398 sinkMBB->splice(sinkMBB->begin(), MBB,
18399 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18400 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18404 // # fallthrough to mainMBB
18405 // # abortion to sinkMBB
18406 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18407 thisMBB->addSuccessor(mainMBB);
18408 thisMBB->addSuccessor(sinkMBB);
18412 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18413 mainMBB->addSuccessor(sinkMBB);
18416 // EAX is live into the sinkMBB
18417 sinkMBB->addLiveIn(X86::EAX);
18418 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18419 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18422 MI->eraseFromParent();
18426 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18427 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18428 // in the .td file.
18429 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18430 const TargetInstrInfo *TII) {
18432 switch (MI->getOpcode()) {
18433 default: llvm_unreachable("illegal opcode!");
18434 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
18435 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18436 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
18437 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18438 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
18439 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18440 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
18441 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18444 DebugLoc dl = MI->getDebugLoc();
18445 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18447 unsigned NumArgs = MI->getNumOperands();
18448 for (unsigned i = 1; i < NumArgs; ++i) {
18449 MachineOperand &Op = MI->getOperand(i);
18450 if (!(Op.isReg() && Op.isImplicit()))
18451 MIB.addOperand(Op);
18453 if (MI->hasOneMemOperand())
18454 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18456 BuildMI(*BB, MI, dl,
18457 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18458 .addReg(X86::XMM0);
18460 MI->eraseFromParent();
18464 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18465 // defs in an instruction pattern
18466 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18467 const TargetInstrInfo *TII) {
18469 switch (MI->getOpcode()) {
18470 default: llvm_unreachable("illegal opcode!");
18471 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
18472 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18473 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
18474 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18475 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
18476 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18477 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
18478 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18481 DebugLoc dl = MI->getDebugLoc();
18482 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18484 unsigned NumArgs = MI->getNumOperands(); // remove the results
18485 for (unsigned i = 1; i < NumArgs; ++i) {
18486 MachineOperand &Op = MI->getOperand(i);
18487 if (!(Op.isReg() && Op.isImplicit()))
18488 MIB.addOperand(Op);
18490 if (MI->hasOneMemOperand())
18491 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18493 BuildMI(*BB, MI, dl,
18494 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18497 MI->eraseFromParent();
18501 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18502 const X86Subtarget *Subtarget) {
18503 DebugLoc dl = MI->getDebugLoc();
18504 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18505 // Address into RAX/EAX, other two args into ECX, EDX.
18506 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18507 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18508 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18509 for (int i = 0; i < X86::AddrNumOperands; ++i)
18510 MIB.addOperand(MI->getOperand(i));
18512 unsigned ValOps = X86::AddrNumOperands;
18513 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18514 .addReg(MI->getOperand(ValOps).getReg());
18515 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18516 .addReg(MI->getOperand(ValOps+1).getReg());
18518 // The instruction doesn't actually take any operands though.
18519 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18521 MI->eraseFromParent(); // The pseudo is gone now.
18525 MachineBasicBlock *
18526 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18527 MachineBasicBlock *MBB) const {
18528 // Emit va_arg instruction on X86-64.
18530 // Operands to this pseudo-instruction:
18531 // 0 ) Output : destination address (reg)
18532 // 1-5) Input : va_list address (addr, i64mem)
18533 // 6 ) ArgSize : Size (in bytes) of vararg type
18534 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18535 // 8 ) Align : Alignment of type
18536 // 9 ) EFLAGS (implicit-def)
18538 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18539 static_assert(X86::AddrNumOperands == 5,
18540 "VAARG_64 assumes 5 address operands");
18542 unsigned DestReg = MI->getOperand(0).getReg();
18543 MachineOperand &Base = MI->getOperand(1);
18544 MachineOperand &Scale = MI->getOperand(2);
18545 MachineOperand &Index = MI->getOperand(3);
18546 MachineOperand &Disp = MI->getOperand(4);
18547 MachineOperand &Segment = MI->getOperand(5);
18548 unsigned ArgSize = MI->getOperand(6).getImm();
18549 unsigned ArgMode = MI->getOperand(7).getImm();
18550 unsigned Align = MI->getOperand(8).getImm();
18552 // Memory Reference
18553 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18554 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18555 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18557 // Machine Information
18558 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18559 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18560 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18561 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18562 DebugLoc DL = MI->getDebugLoc();
18564 // struct va_list {
18567 // i64 overflow_area (address)
18568 // i64 reg_save_area (address)
18570 // sizeof(va_list) = 24
18571 // alignment(va_list) = 8
18573 unsigned TotalNumIntRegs = 6;
18574 unsigned TotalNumXMMRegs = 8;
18575 bool UseGPOffset = (ArgMode == 1);
18576 bool UseFPOffset = (ArgMode == 2);
18577 unsigned MaxOffset = TotalNumIntRegs * 8 +
18578 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18580 /* Align ArgSize to a multiple of 8 */
18581 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18582 bool NeedsAlign = (Align > 8);
18584 MachineBasicBlock *thisMBB = MBB;
18585 MachineBasicBlock *overflowMBB;
18586 MachineBasicBlock *offsetMBB;
18587 MachineBasicBlock *endMBB;
18589 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
18590 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
18591 unsigned OffsetReg = 0;
18593 if (!UseGPOffset && !UseFPOffset) {
18594 // If we only pull from the overflow region, we don't create a branch.
18595 // We don't need to alter control flow.
18596 OffsetDestReg = 0; // unused
18597 OverflowDestReg = DestReg;
18599 offsetMBB = nullptr;
18600 overflowMBB = thisMBB;
18603 // First emit code to check if gp_offset (or fp_offset) is below the bound.
18604 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18605 // If not, pull from overflow_area. (branch to overflowMBB)
18610 // offsetMBB overflowMBB
18615 // Registers for the PHI in endMBB
18616 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18617 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18619 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18620 MachineFunction *MF = MBB->getParent();
18621 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18622 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18623 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18625 MachineFunction::iterator MBBIter = MBB;
18628 // Insert the new basic blocks
18629 MF->insert(MBBIter, offsetMBB);
18630 MF->insert(MBBIter, overflowMBB);
18631 MF->insert(MBBIter, endMBB);
18633 // Transfer the remainder of MBB and its successor edges to endMBB.
18634 endMBB->splice(endMBB->begin(), thisMBB,
18635 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18636 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18638 // Make offsetMBB and overflowMBB successors of thisMBB
18639 thisMBB->addSuccessor(offsetMBB);
18640 thisMBB->addSuccessor(overflowMBB);
18642 // endMBB is a successor of both offsetMBB and overflowMBB
18643 offsetMBB->addSuccessor(endMBB);
18644 overflowMBB->addSuccessor(endMBB);
18646 // Load the offset value into a register
18647 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18648 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18652 .addDisp(Disp, UseFPOffset ? 4 : 0)
18653 .addOperand(Segment)
18654 .setMemRefs(MMOBegin, MMOEnd);
18656 // Check if there is enough room left to pull this argument.
18657 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18659 .addImm(MaxOffset + 8 - ArgSizeA8);
18661 // Branch to "overflowMBB" if offset >= max
18662 // Fall through to "offsetMBB" otherwise
18663 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18664 .addMBB(overflowMBB);
18667 // In offsetMBB, emit code to use the reg_save_area.
18669 assert(OffsetReg != 0);
18671 // Read the reg_save_area address.
18672 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18673 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18678 .addOperand(Segment)
18679 .setMemRefs(MMOBegin, MMOEnd);
18681 // Zero-extend the offset
18682 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18683 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18686 .addImm(X86::sub_32bit);
18688 // Add the offset to the reg_save_area to get the final address.
18689 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18690 .addReg(OffsetReg64)
18691 .addReg(RegSaveReg);
18693 // Compute the offset for the next argument
18694 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18695 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18697 .addImm(UseFPOffset ? 16 : 8);
18699 // Store it back into the va_list.
18700 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18704 .addDisp(Disp, UseFPOffset ? 4 : 0)
18705 .addOperand(Segment)
18706 .addReg(NextOffsetReg)
18707 .setMemRefs(MMOBegin, MMOEnd);
18710 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18715 // Emit code to use overflow area
18718 // Load the overflow_area address into a register.
18719 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18720 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18725 .addOperand(Segment)
18726 .setMemRefs(MMOBegin, MMOEnd);
18728 // If we need to align it, do so. Otherwise, just copy the address
18729 // to OverflowDestReg.
18731 // Align the overflow address
18732 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18733 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18735 // aligned_addr = (addr + (align-1)) & ~(align-1)
18736 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18737 .addReg(OverflowAddrReg)
18740 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18742 .addImm(~(uint64_t)(Align-1));
18744 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18745 .addReg(OverflowAddrReg);
18748 // Compute the next overflow address after this argument.
18749 // (the overflow address should be kept 8-byte aligned)
18750 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18751 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18752 .addReg(OverflowDestReg)
18753 .addImm(ArgSizeA8);
18755 // Store the new overflow address.
18756 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18761 .addOperand(Segment)
18762 .addReg(NextAddrReg)
18763 .setMemRefs(MMOBegin, MMOEnd);
18765 // If we branched, emit the PHI to the front of endMBB.
18767 BuildMI(*endMBB, endMBB->begin(), DL,
18768 TII->get(X86::PHI), DestReg)
18769 .addReg(OffsetDestReg).addMBB(offsetMBB)
18770 .addReg(OverflowDestReg).addMBB(overflowMBB);
18773 // Erase the pseudo instruction
18774 MI->eraseFromParent();
18779 MachineBasicBlock *
18780 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18782 MachineBasicBlock *MBB) const {
18783 // Emit code to save XMM registers to the stack. The ABI says that the
18784 // number of registers to save is given in %al, so it's theoretically
18785 // possible to do an indirect jump trick to avoid saving all of them,
18786 // however this code takes a simpler approach and just executes all
18787 // of the stores if %al is non-zero. It's less code, and it's probably
18788 // easier on the hardware branch predictor, and stores aren't all that
18789 // expensive anyway.
18791 // Create the new basic blocks. One block contains all the XMM stores,
18792 // and one block is the final destination regardless of whether any
18793 // stores were performed.
18794 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18795 MachineFunction *F = MBB->getParent();
18796 MachineFunction::iterator MBBIter = MBB;
18798 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18799 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18800 F->insert(MBBIter, XMMSaveMBB);
18801 F->insert(MBBIter, EndMBB);
18803 // Transfer the remainder of MBB and its successor edges to EndMBB.
18804 EndMBB->splice(EndMBB->begin(), MBB,
18805 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18806 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18808 // The original block will now fall through to the XMM save block.
18809 MBB->addSuccessor(XMMSaveMBB);
18810 // The XMMSaveMBB will fall through to the end block.
18811 XMMSaveMBB->addSuccessor(EndMBB);
18813 // Now add the instructions.
18814 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18815 DebugLoc DL = MI->getDebugLoc();
18817 unsigned CountReg = MI->getOperand(0).getReg();
18818 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18819 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18821 if (!Subtarget->isTargetWin64()) {
18822 // If %al is 0, branch around the XMM save block.
18823 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18824 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18825 MBB->addSuccessor(EndMBB);
18828 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18829 // that was just emitted, but clearly shouldn't be "saved".
18830 assert((MI->getNumOperands() <= 3 ||
18831 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18832 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18833 && "Expected last argument to be EFLAGS");
18834 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18835 // In the XMM save block, save all the XMM argument registers.
18836 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18837 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18838 MachineMemOperand *MMO =
18839 F->getMachineMemOperand(
18840 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18841 MachineMemOperand::MOStore,
18842 /*Size=*/16, /*Align=*/16);
18843 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18844 .addFrameIndex(RegSaveFrameIndex)
18845 .addImm(/*Scale=*/1)
18846 .addReg(/*IndexReg=*/0)
18847 .addImm(/*Disp=*/Offset)
18848 .addReg(/*Segment=*/0)
18849 .addReg(MI->getOperand(i).getReg())
18850 .addMemOperand(MMO);
18853 MI->eraseFromParent(); // The pseudo instruction is gone now.
18858 // The EFLAGS operand of SelectItr might be missing a kill marker
18859 // because there were multiple uses of EFLAGS, and ISel didn't know
18860 // which to mark. Figure out whether SelectItr should have had a
18861 // kill marker, and set it if it should. Returns the correct kill
18863 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18864 MachineBasicBlock* BB,
18865 const TargetRegisterInfo* TRI) {
18866 // Scan forward through BB for a use/def of EFLAGS.
18867 MachineBasicBlock::iterator miI(std::next(SelectItr));
18868 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18869 const MachineInstr& mi = *miI;
18870 if (mi.readsRegister(X86::EFLAGS))
18872 if (mi.definesRegister(X86::EFLAGS))
18873 break; // Should have kill-flag - update below.
18876 // If we hit the end of the block, check whether EFLAGS is live into a
18878 if (miI == BB->end()) {
18879 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18880 sEnd = BB->succ_end();
18881 sItr != sEnd; ++sItr) {
18882 MachineBasicBlock* succ = *sItr;
18883 if (succ->isLiveIn(X86::EFLAGS))
18888 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18889 // out. SelectMI should have a kill flag on EFLAGS.
18890 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18894 MachineBasicBlock *
18895 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18896 MachineBasicBlock *BB) const {
18897 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18898 DebugLoc DL = MI->getDebugLoc();
18900 // To "insert" a SELECT_CC instruction, we actually have to insert the
18901 // diamond control-flow pattern. The incoming instruction knows the
18902 // destination vreg to set, the condition code register to branch on, the
18903 // true/false values to select between, and a branch opcode to use.
18904 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18905 MachineFunction::iterator It = BB;
18911 // cmpTY ccX, r1, r2
18913 // fallthrough --> copy0MBB
18914 MachineBasicBlock *thisMBB = BB;
18915 MachineFunction *F = BB->getParent();
18917 // We also lower double CMOVs:
18918 // (CMOV (CMOV F, T, cc1), T, cc2)
18919 // to two successives branches. For that, we look for another CMOV as the
18920 // following instruction.
18922 // Without this, we would add a PHI between the two jumps, which ends up
18923 // creating a few copies all around. For instance, for
18925 // (sitofp (zext (fcmp une)))
18927 // we would generate:
18929 // ucomiss %xmm1, %xmm0
18930 // movss <1.0f>, %xmm0
18931 // movaps %xmm0, %xmm1
18933 // xorps %xmm1, %xmm1
18936 // movaps %xmm1, %xmm0
18940 // because this custom-inserter would have generated:
18952 // A: X = ...; Y = ...
18954 // C: Z = PHI [X, A], [Y, B]
18956 // E: PHI [X, C], [Z, D]
18958 // If we lower both CMOVs in a single step, we can instead generate:
18970 // A: X = ...; Y = ...
18972 // E: PHI [X, A], [X, C], [Y, D]
18974 // Which, in our sitofp/fcmp example, gives us something like:
18976 // ucomiss %xmm1, %xmm0
18977 // movss <1.0f>, %xmm0
18980 // xorps %xmm0, %xmm0
18984 MachineInstr *NextCMOV = nullptr;
18985 MachineBasicBlock::iterator NextMIIt =
18986 std::next(MachineBasicBlock::iterator(MI));
18987 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18988 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18989 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18990 NextCMOV = &*NextMIIt;
18992 MachineBasicBlock *jcc1MBB = nullptr;
18994 // If we have a double CMOV, we lower it to two successive branches to
18995 // the same block. EFLAGS is used by both, so mark it as live in the second.
18997 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18998 F->insert(It, jcc1MBB);
18999 jcc1MBB->addLiveIn(X86::EFLAGS);
19002 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19003 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19004 F->insert(It, copy0MBB);
19005 F->insert(It, sinkMBB);
19007 // If the EFLAGS register isn't dead in the terminator, then claim that it's
19008 // live into the sink and copy blocks.
19009 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19011 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19012 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19013 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19014 copy0MBB->addLiveIn(X86::EFLAGS);
19015 sinkMBB->addLiveIn(X86::EFLAGS);
19018 // Transfer the remainder of BB and its successor edges to sinkMBB.
19019 sinkMBB->splice(sinkMBB->begin(), BB,
19020 std::next(MachineBasicBlock::iterator(MI)), BB->end());
19021 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19023 // Add the true and fallthrough blocks as its successors.
19025 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19026 BB->addSuccessor(jcc1MBB);
19028 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19029 // jump to the sinkMBB.
19030 jcc1MBB->addSuccessor(copy0MBB);
19031 jcc1MBB->addSuccessor(sinkMBB);
19033 BB->addSuccessor(copy0MBB);
19036 // The true block target of the first (or only) branch is always sinkMBB.
19037 BB->addSuccessor(sinkMBB);
19039 // Create the conditional branch instruction.
19041 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19042 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19045 unsigned Opc2 = X86::GetCondBranchFromCond(
19046 (X86::CondCode)NextCMOV->getOperand(3).getImm());
19047 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19051 // %FalseValue = ...
19052 // # fallthrough to sinkMBB
19053 copy0MBB->addSuccessor(sinkMBB);
19056 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19058 MachineInstrBuilder MIB =
19059 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19060 MI->getOperand(0).getReg())
19061 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19062 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19064 // If we have a double CMOV, the second Jcc provides the same incoming
19065 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19067 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19068 // Copy the PHI result to the register defined by the second CMOV.
19069 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19070 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19071 .addReg(MI->getOperand(0).getReg());
19072 NextCMOV->eraseFromParent();
19075 MI->eraseFromParent(); // The pseudo instruction is gone now.
19079 MachineBasicBlock *
19080 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19081 MachineBasicBlock *BB) const {
19082 MachineFunction *MF = BB->getParent();
19083 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19084 DebugLoc DL = MI->getDebugLoc();
19085 const BasicBlock *LLVM_BB = BB->getBasicBlock();
19087 assert(MF->shouldSplitStack());
19089 const bool Is64Bit = Subtarget->is64Bit();
19090 const bool IsLP64 = Subtarget->isTarget64BitLP64();
19092 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19093 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19096 // ... [Till the alloca]
19097 // If stacklet is not large enough, jump to mallocMBB
19100 // Allocate by subtracting from RSP
19101 // Jump to continueMBB
19104 // Allocate by call to runtime
19108 // [rest of original BB]
19111 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19112 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19113 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19115 MachineRegisterInfo &MRI = MF->getRegInfo();
19116 const TargetRegisterClass *AddrRegClass =
19117 getRegClassFor(getPointerTy());
19119 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19120 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19121 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19122 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19123 sizeVReg = MI->getOperand(1).getReg(),
19124 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19126 MachineFunction::iterator MBBIter = BB;
19129 MF->insert(MBBIter, bumpMBB);
19130 MF->insert(MBBIter, mallocMBB);
19131 MF->insert(MBBIter, continueMBB);
19133 continueMBB->splice(continueMBB->begin(), BB,
19134 std::next(MachineBasicBlock::iterator(MI)), BB->end());
19135 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19137 // Add code to the main basic block to check if the stack limit has been hit,
19138 // and if so, jump to mallocMBB otherwise to bumpMBB.
19139 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19140 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19141 .addReg(tmpSPVReg).addReg(sizeVReg);
19142 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19143 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19144 .addReg(SPLimitVReg);
19145 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19147 // bumpMBB simply decreases the stack pointer, since we know the current
19148 // stacklet has enough space.
19149 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19150 .addReg(SPLimitVReg);
19151 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19152 .addReg(SPLimitVReg);
19153 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19155 // Calls into a routine in libgcc to allocate more space from the heap.
19156 const uint32_t *RegMask =
19157 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19159 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19161 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19162 .addExternalSymbol("__morestack_allocate_stack_space")
19163 .addRegMask(RegMask)
19164 .addReg(X86::RDI, RegState::Implicit)
19165 .addReg(X86::RAX, RegState::ImplicitDefine);
19166 } else if (Is64Bit) {
19167 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19169 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19170 .addExternalSymbol("__morestack_allocate_stack_space")
19171 .addRegMask(RegMask)
19172 .addReg(X86::EDI, RegState::Implicit)
19173 .addReg(X86::EAX, RegState::ImplicitDefine);
19175 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19177 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19178 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19179 .addExternalSymbol("__morestack_allocate_stack_space")
19180 .addRegMask(RegMask)
19181 .addReg(X86::EAX, RegState::ImplicitDefine);
19185 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19188 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19189 .addReg(IsLP64 ? X86::RAX : X86::EAX);
19190 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19192 // Set up the CFG correctly.
19193 BB->addSuccessor(bumpMBB);
19194 BB->addSuccessor(mallocMBB);
19195 mallocMBB->addSuccessor(continueMBB);
19196 bumpMBB->addSuccessor(continueMBB);
19198 // Take care of the PHI nodes.
19199 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19200 MI->getOperand(0).getReg())
19201 .addReg(mallocPtrVReg).addMBB(mallocMBB)
19202 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19204 // Delete the original pseudo instruction.
19205 MI->eraseFromParent();
19208 return continueMBB;
19211 MachineBasicBlock *
19212 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19213 MachineBasicBlock *BB) const {
19214 DebugLoc DL = MI->getDebugLoc();
19216 assert(!Subtarget->isTargetMachO());
19218 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19220 MI->eraseFromParent(); // The pseudo instruction is gone now.
19224 MachineBasicBlock *
19225 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19226 MachineBasicBlock *BB) const {
19227 // This is pretty easy. We're taking the value that we received from
19228 // our load from the relocation, sticking it in either RDI (x86-64)
19229 // or EAX and doing an indirect call. The return value will then
19230 // be in the normal return register.
19231 MachineFunction *F = BB->getParent();
19232 const X86InstrInfo *TII = Subtarget->getInstrInfo();
19233 DebugLoc DL = MI->getDebugLoc();
19235 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19236 assert(MI->getOperand(3).isGlobal() && "This should be a global");
19238 // Get a register mask for the lowered call.
19239 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19240 // proper register mask.
19241 const uint32_t *RegMask =
19242 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19243 if (Subtarget->is64Bit()) {
19244 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19245 TII->get(X86::MOV64rm), X86::RDI)
19247 .addImm(0).addReg(0)
19248 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19249 MI->getOperand(3).getTargetFlags())
19251 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19252 addDirectMem(MIB, X86::RDI);
19253 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19254 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19255 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19256 TII->get(X86::MOV32rm), X86::EAX)
19258 .addImm(0).addReg(0)
19259 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19260 MI->getOperand(3).getTargetFlags())
19262 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19263 addDirectMem(MIB, X86::EAX);
19264 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19266 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19267 TII->get(X86::MOV32rm), X86::EAX)
19268 .addReg(TII->getGlobalBaseReg(F))
19269 .addImm(0).addReg(0)
19270 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19271 MI->getOperand(3).getTargetFlags())
19273 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19274 addDirectMem(MIB, X86::EAX);
19275 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19278 MI->eraseFromParent(); // The pseudo instruction is gone now.
19282 MachineBasicBlock *
19283 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19284 MachineBasicBlock *MBB) const {
19285 DebugLoc DL = MI->getDebugLoc();
19286 MachineFunction *MF = MBB->getParent();
19287 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19288 MachineRegisterInfo &MRI = MF->getRegInfo();
19290 const BasicBlock *BB = MBB->getBasicBlock();
19291 MachineFunction::iterator I = MBB;
19294 // Memory Reference
19295 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19296 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19299 unsigned MemOpndSlot = 0;
19301 unsigned CurOp = 0;
19303 DstReg = MI->getOperand(CurOp++).getReg();
19304 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19305 assert(RC->hasType(MVT::i32) && "Invalid destination!");
19306 unsigned mainDstReg = MRI.createVirtualRegister(RC);
19307 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19309 MemOpndSlot = CurOp;
19311 MVT PVT = getPointerTy();
19312 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19313 "Invalid Pointer Size!");
19315 // For v = setjmp(buf), we generate
19318 // buf[LabelOffset] = restoreMBB
19319 // SjLjSetup restoreMBB
19325 // v = phi(main, restore)
19328 // if base pointer being used, load it from frame
19331 MachineBasicBlock *thisMBB = MBB;
19332 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19333 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19334 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19335 MF->insert(I, mainMBB);
19336 MF->insert(I, sinkMBB);
19337 MF->push_back(restoreMBB);
19339 MachineInstrBuilder MIB;
19341 // Transfer the remainder of BB and its successor edges to sinkMBB.
19342 sinkMBB->splice(sinkMBB->begin(), MBB,
19343 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19344 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19347 unsigned PtrStoreOpc = 0;
19348 unsigned LabelReg = 0;
19349 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19350 Reloc::Model RM = MF->getTarget().getRelocationModel();
19351 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19352 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19354 // Prepare IP either in reg or imm.
19355 if (!UseImmLabel) {
19356 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19357 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19358 LabelReg = MRI.createVirtualRegister(PtrRC);
19359 if (Subtarget->is64Bit()) {
19360 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19364 .addMBB(restoreMBB)
19367 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19368 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19369 .addReg(XII->getGlobalBaseReg(MF))
19372 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19376 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19378 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19379 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19380 if (i == X86::AddrDisp)
19381 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19383 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19386 MIB.addReg(LabelReg);
19388 MIB.addMBB(restoreMBB);
19389 MIB.setMemRefs(MMOBegin, MMOEnd);
19391 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19392 .addMBB(restoreMBB);
19394 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19395 MIB.addRegMask(RegInfo->getNoPreservedMask());
19396 thisMBB->addSuccessor(mainMBB);
19397 thisMBB->addSuccessor(restoreMBB);
19401 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19402 mainMBB->addSuccessor(sinkMBB);
19405 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19406 TII->get(X86::PHI), DstReg)
19407 .addReg(mainDstReg).addMBB(mainMBB)
19408 .addReg(restoreDstReg).addMBB(restoreMBB);
19411 if (RegInfo->hasBasePointer(*MF)) {
19412 const bool Uses64BitFramePtr =
19413 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19414 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19415 X86FI->setRestoreBasePointer(MF);
19416 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19417 unsigned BasePtr = RegInfo->getBaseRegister();
19418 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19419 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19420 FramePtr, true, X86FI->getRestoreBasePointerOffset())
19421 .setMIFlag(MachineInstr::FrameSetup);
19423 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19424 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19425 restoreMBB->addSuccessor(sinkMBB);
19427 MI->eraseFromParent();
19431 MachineBasicBlock *
19432 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19433 MachineBasicBlock *MBB) const {
19434 DebugLoc DL = MI->getDebugLoc();
19435 MachineFunction *MF = MBB->getParent();
19436 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19437 MachineRegisterInfo &MRI = MF->getRegInfo();
19439 // Memory Reference
19440 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19441 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19443 MVT PVT = getPointerTy();
19444 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19445 "Invalid Pointer Size!");
19447 const TargetRegisterClass *RC =
19448 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19449 unsigned Tmp = MRI.createVirtualRegister(RC);
19450 // Since FP is only updated here but NOT referenced, it's treated as GPR.
19451 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19452 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19453 unsigned SP = RegInfo->getStackRegister();
19455 MachineInstrBuilder MIB;
19457 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19458 const int64_t SPOffset = 2 * PVT.getStoreSize();
19460 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19461 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19464 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19465 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19466 MIB.addOperand(MI->getOperand(i));
19467 MIB.setMemRefs(MMOBegin, MMOEnd);
19469 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19470 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19471 if (i == X86::AddrDisp)
19472 MIB.addDisp(MI->getOperand(i), LabelOffset);
19474 MIB.addOperand(MI->getOperand(i));
19476 MIB.setMemRefs(MMOBegin, MMOEnd);
19478 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19479 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19480 if (i == X86::AddrDisp)
19481 MIB.addDisp(MI->getOperand(i), SPOffset);
19483 MIB.addOperand(MI->getOperand(i));
19485 MIB.setMemRefs(MMOBegin, MMOEnd);
19487 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19489 MI->eraseFromParent();
19493 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19494 // accumulator loops. Writing back to the accumulator allows the coalescer
19495 // to remove extra copies in the loop.
19496 MachineBasicBlock *
19497 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19498 MachineBasicBlock *MBB) const {
19499 MachineOperand &AddendOp = MI->getOperand(3);
19501 // Bail out early if the addend isn't a register - we can't switch these.
19502 if (!AddendOp.isReg())
19505 MachineFunction &MF = *MBB->getParent();
19506 MachineRegisterInfo &MRI = MF.getRegInfo();
19508 // Check whether the addend is defined by a PHI:
19509 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19510 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19511 if (!AddendDef.isPHI())
19514 // Look for the following pattern:
19516 // %addend = phi [%entry, 0], [%loop, %result]
19518 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19522 // %addend = phi [%entry, 0], [%loop, %result]
19524 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19526 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19527 assert(AddendDef.getOperand(i).isReg());
19528 MachineOperand PHISrcOp = AddendDef.getOperand(i);
19529 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19530 if (&PHISrcInst == MI) {
19531 // Found a matching instruction.
19532 unsigned NewFMAOpc = 0;
19533 switch (MI->getOpcode()) {
19534 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19535 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19536 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19537 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19538 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19539 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19540 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19541 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19542 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19543 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19544 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19545 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19546 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19547 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19548 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19549 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19550 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19551 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19552 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19553 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19555 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19556 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19557 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19558 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19559 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19560 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19561 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19562 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19563 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19564 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19565 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19566 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19567 default: llvm_unreachable("Unrecognized FMA variant.");
19570 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19571 MachineInstrBuilder MIB =
19572 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19573 .addOperand(MI->getOperand(0))
19574 .addOperand(MI->getOperand(3))
19575 .addOperand(MI->getOperand(2))
19576 .addOperand(MI->getOperand(1));
19577 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19578 MI->eraseFromParent();
19585 MachineBasicBlock *
19586 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19587 MachineBasicBlock *BB) const {
19588 switch (MI->getOpcode()) {
19589 default: llvm_unreachable("Unexpected instr type to insert");
19590 case X86::TAILJMPd64:
19591 case X86::TAILJMPr64:
19592 case X86::TAILJMPm64:
19593 case X86::TAILJMPd64_REX:
19594 case X86::TAILJMPr64_REX:
19595 case X86::TAILJMPm64_REX:
19596 llvm_unreachable("TAILJMP64 would not be touched here.");
19597 case X86::TCRETURNdi64:
19598 case X86::TCRETURNri64:
19599 case X86::TCRETURNmi64:
19601 case X86::WIN_ALLOCA:
19602 return EmitLoweredWinAlloca(MI, BB);
19603 case X86::SEG_ALLOCA_32:
19604 case X86::SEG_ALLOCA_64:
19605 return EmitLoweredSegAlloca(MI, BB);
19606 case X86::TLSCall_32:
19607 case X86::TLSCall_64:
19608 return EmitLoweredTLSCall(MI, BB);
19609 case X86::CMOV_GR8:
19610 case X86::CMOV_FR32:
19611 case X86::CMOV_FR64:
19612 case X86::CMOV_V4F32:
19613 case X86::CMOV_V2F64:
19614 case X86::CMOV_V2I64:
19615 case X86::CMOV_V8F32:
19616 case X86::CMOV_V4F64:
19617 case X86::CMOV_V4I64:
19618 case X86::CMOV_V16F32:
19619 case X86::CMOV_V8F64:
19620 case X86::CMOV_V8I64:
19621 case X86::CMOV_GR16:
19622 case X86::CMOV_GR32:
19623 case X86::CMOV_RFP32:
19624 case X86::CMOV_RFP64:
19625 case X86::CMOV_RFP80:
19626 case X86::CMOV_V8I1:
19627 case X86::CMOV_V16I1:
19628 case X86::CMOV_V32I1:
19629 case X86::CMOV_V64I1:
19630 return EmitLoweredSelect(MI, BB);
19632 case X86::FP32_TO_INT16_IN_MEM:
19633 case X86::FP32_TO_INT32_IN_MEM:
19634 case X86::FP32_TO_INT64_IN_MEM:
19635 case X86::FP64_TO_INT16_IN_MEM:
19636 case X86::FP64_TO_INT32_IN_MEM:
19637 case X86::FP64_TO_INT64_IN_MEM:
19638 case X86::FP80_TO_INT16_IN_MEM:
19639 case X86::FP80_TO_INT32_IN_MEM:
19640 case X86::FP80_TO_INT64_IN_MEM: {
19641 MachineFunction *F = BB->getParent();
19642 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19643 DebugLoc DL = MI->getDebugLoc();
19645 // Change the floating point control register to use "round towards zero"
19646 // mode when truncating to an integer value.
19647 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19648 addFrameReference(BuildMI(*BB, MI, DL,
19649 TII->get(X86::FNSTCW16m)), CWFrameIdx);
19651 // Load the old value of the high byte of the control word...
19653 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19654 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19657 // Set the high part to be round to zero...
19658 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19661 // Reload the modified control word now...
19662 addFrameReference(BuildMI(*BB, MI, DL,
19663 TII->get(X86::FLDCW16m)), CWFrameIdx);
19665 // Restore the memory image of control word to original value
19666 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19669 // Get the X86 opcode to use.
19671 switch (MI->getOpcode()) {
19672 default: llvm_unreachable("illegal opcode!");
19673 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19674 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19675 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19676 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19677 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19678 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19679 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19680 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19681 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19685 MachineOperand &Op = MI->getOperand(0);
19687 AM.BaseType = X86AddressMode::RegBase;
19688 AM.Base.Reg = Op.getReg();
19690 AM.BaseType = X86AddressMode::FrameIndexBase;
19691 AM.Base.FrameIndex = Op.getIndex();
19693 Op = MI->getOperand(1);
19695 AM.Scale = Op.getImm();
19696 Op = MI->getOperand(2);
19698 AM.IndexReg = Op.getImm();
19699 Op = MI->getOperand(3);
19700 if (Op.isGlobal()) {
19701 AM.GV = Op.getGlobal();
19703 AM.Disp = Op.getImm();
19705 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19706 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19708 // Reload the original control word now.
19709 addFrameReference(BuildMI(*BB, MI, DL,
19710 TII->get(X86::FLDCW16m)), CWFrameIdx);
19712 MI->eraseFromParent(); // The pseudo instruction is gone now.
19715 // String/text processing lowering.
19716 case X86::PCMPISTRM128REG:
19717 case X86::VPCMPISTRM128REG:
19718 case X86::PCMPISTRM128MEM:
19719 case X86::VPCMPISTRM128MEM:
19720 case X86::PCMPESTRM128REG:
19721 case X86::VPCMPESTRM128REG:
19722 case X86::PCMPESTRM128MEM:
19723 case X86::VPCMPESTRM128MEM:
19724 assert(Subtarget->hasSSE42() &&
19725 "Target must have SSE4.2 or AVX features enabled");
19726 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19728 // String/text processing lowering.
19729 case X86::PCMPISTRIREG:
19730 case X86::VPCMPISTRIREG:
19731 case X86::PCMPISTRIMEM:
19732 case X86::VPCMPISTRIMEM:
19733 case X86::PCMPESTRIREG:
19734 case X86::VPCMPESTRIREG:
19735 case X86::PCMPESTRIMEM:
19736 case X86::VPCMPESTRIMEM:
19737 assert(Subtarget->hasSSE42() &&
19738 "Target must have SSE4.2 or AVX features enabled");
19739 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19741 // Thread synchronization.
19743 return EmitMonitor(MI, BB, Subtarget);
19747 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19749 case X86::VASTART_SAVE_XMM_REGS:
19750 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19752 case X86::VAARG_64:
19753 return EmitVAARG64WithCustomInserter(MI, BB);
19755 case X86::EH_SjLj_SetJmp32:
19756 case X86::EH_SjLj_SetJmp64:
19757 return emitEHSjLjSetJmp(MI, BB);
19759 case X86::EH_SjLj_LongJmp32:
19760 case X86::EH_SjLj_LongJmp64:
19761 return emitEHSjLjLongJmp(MI, BB);
19763 case TargetOpcode::STATEPOINT:
19764 // As an implementation detail, STATEPOINT shares the STACKMAP format at
19765 // this point in the process. We diverge later.
19766 return emitPatchPoint(MI, BB);
19768 case TargetOpcode::STACKMAP:
19769 case TargetOpcode::PATCHPOINT:
19770 return emitPatchPoint(MI, BB);
19772 case X86::VFMADDPDr213r:
19773 case X86::VFMADDPSr213r:
19774 case X86::VFMADDSDr213r:
19775 case X86::VFMADDSSr213r:
19776 case X86::VFMSUBPDr213r:
19777 case X86::VFMSUBPSr213r:
19778 case X86::VFMSUBSDr213r:
19779 case X86::VFMSUBSSr213r:
19780 case X86::VFNMADDPDr213r:
19781 case X86::VFNMADDPSr213r:
19782 case X86::VFNMADDSDr213r:
19783 case X86::VFNMADDSSr213r:
19784 case X86::VFNMSUBPDr213r:
19785 case X86::VFNMSUBPSr213r:
19786 case X86::VFNMSUBSDr213r:
19787 case X86::VFNMSUBSSr213r:
19788 case X86::VFMADDSUBPDr213r:
19789 case X86::VFMADDSUBPSr213r:
19790 case X86::VFMSUBADDPDr213r:
19791 case X86::VFMSUBADDPSr213r:
19792 case X86::VFMADDPDr213rY:
19793 case X86::VFMADDPSr213rY:
19794 case X86::VFMSUBPDr213rY:
19795 case X86::VFMSUBPSr213rY:
19796 case X86::VFNMADDPDr213rY:
19797 case X86::VFNMADDPSr213rY:
19798 case X86::VFNMSUBPDr213rY:
19799 case X86::VFNMSUBPSr213rY:
19800 case X86::VFMADDSUBPDr213rY:
19801 case X86::VFMADDSUBPSr213rY:
19802 case X86::VFMSUBADDPDr213rY:
19803 case X86::VFMSUBADDPSr213rY:
19804 return emitFMA3Instr(MI, BB);
19808 //===----------------------------------------------------------------------===//
19809 // X86 Optimization Hooks
19810 //===----------------------------------------------------------------------===//
19812 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19815 const SelectionDAG &DAG,
19816 unsigned Depth) const {
19817 unsigned BitWidth = KnownZero.getBitWidth();
19818 unsigned Opc = Op.getOpcode();
19819 assert((Opc >= ISD::BUILTIN_OP_END ||
19820 Opc == ISD::INTRINSIC_WO_CHAIN ||
19821 Opc == ISD::INTRINSIC_W_CHAIN ||
19822 Opc == ISD::INTRINSIC_VOID) &&
19823 "Should use MaskedValueIsZero if you don't know whether Op"
19824 " is a target node!");
19826 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19840 // These nodes' second result is a boolean.
19841 if (Op.getResNo() == 0)
19844 case X86ISD::SETCC:
19845 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19847 case ISD::INTRINSIC_WO_CHAIN: {
19848 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19849 unsigned NumLoBits = 0;
19852 case Intrinsic::x86_sse_movmsk_ps:
19853 case Intrinsic::x86_avx_movmsk_ps_256:
19854 case Intrinsic::x86_sse2_movmsk_pd:
19855 case Intrinsic::x86_avx_movmsk_pd_256:
19856 case Intrinsic::x86_mmx_pmovmskb:
19857 case Intrinsic::x86_sse2_pmovmskb_128:
19858 case Intrinsic::x86_avx2_pmovmskb: {
19859 // High bits of movmskp{s|d}, pmovmskb are known zero.
19861 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19862 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19863 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19864 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19865 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19866 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19867 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19868 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19870 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19879 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19881 const SelectionDAG &,
19882 unsigned Depth) const {
19883 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19884 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19885 return Op.getValueType().getScalarType().getSizeInBits();
19891 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19892 /// node is a GlobalAddress + offset.
19893 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19894 const GlobalValue* &GA,
19895 int64_t &Offset) const {
19896 if (N->getOpcode() == X86ISD::Wrapper) {
19897 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19898 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19899 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19903 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19906 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19907 /// same as extracting the high 128-bit part of 256-bit vector and then
19908 /// inserting the result into the low part of a new 256-bit vector
19909 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19910 EVT VT = SVOp->getValueType(0);
19911 unsigned NumElems = VT.getVectorNumElements();
19913 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19914 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19915 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19916 SVOp->getMaskElt(j) >= 0)
19922 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19923 /// same as extracting the low 128-bit part of 256-bit vector and then
19924 /// inserting the result into the high part of a new 256-bit vector
19925 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19926 EVT VT = SVOp->getValueType(0);
19927 unsigned NumElems = VT.getVectorNumElements();
19929 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19930 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19931 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19932 SVOp->getMaskElt(j) >= 0)
19938 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19939 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19940 TargetLowering::DAGCombinerInfo &DCI,
19941 const X86Subtarget* Subtarget) {
19943 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19944 SDValue V1 = SVOp->getOperand(0);
19945 SDValue V2 = SVOp->getOperand(1);
19946 EVT VT = SVOp->getValueType(0);
19947 unsigned NumElems = VT.getVectorNumElements();
19949 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19950 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19954 // V UNDEF BUILD_VECTOR UNDEF
19956 // CONCAT_VECTOR CONCAT_VECTOR
19959 // RESULT: V + zero extended
19961 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19962 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19963 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19966 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19969 // To match the shuffle mask, the first half of the mask should
19970 // be exactly the first vector, and all the rest a splat with the
19971 // first element of the second one.
19972 for (unsigned i = 0; i != NumElems/2; ++i)
19973 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19974 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19977 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19978 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19979 if (Ld->hasNUsesOfValue(1, 0)) {
19980 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19981 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19983 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19985 Ld->getPointerInfo(),
19986 Ld->getAlignment(),
19987 false/*isVolatile*/, true/*ReadMem*/,
19988 false/*WriteMem*/);
19990 // Make sure the newly-created LOAD is in the same position as Ld in
19991 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19992 // and update uses of Ld's output chain to use the TokenFactor.
19993 if (Ld->hasAnyUseOfValue(1)) {
19994 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19995 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19996 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19997 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19998 SDValue(ResNode.getNode(), 1));
20001 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
20005 // Emit a zeroed vector and insert the desired subvector on its
20007 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20008 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20009 return DCI.CombineTo(N, InsV);
20012 //===--------------------------------------------------------------------===//
20013 // Combine some shuffles into subvector extracts and inserts:
20016 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20017 if (isShuffleHigh128VectorInsertLow(SVOp)) {
20018 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20019 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20020 return DCI.CombineTo(N, InsV);
20023 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20024 if (isShuffleLow128VectorInsertHigh(SVOp)) {
20025 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20026 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20027 return DCI.CombineTo(N, InsV);
20033 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20036 /// This is the leaf of the recursive combinine below. When we have found some
20037 /// chain of single-use x86 shuffle instructions and accumulated the combined
20038 /// shuffle mask represented by them, this will try to pattern match that mask
20039 /// into either a single instruction if there is a special purpose instruction
20040 /// for this operation, or into a PSHUFB instruction which is a fully general
20041 /// instruction but should only be used to replace chains over a certain depth.
20042 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20043 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20044 TargetLowering::DAGCombinerInfo &DCI,
20045 const X86Subtarget *Subtarget) {
20046 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20048 // Find the operand that enters the chain. Note that multiple uses are OK
20049 // here, we're not going to remove the operand we find.
20050 SDValue Input = Op.getOperand(0);
20051 while (Input.getOpcode() == ISD::BITCAST)
20052 Input = Input.getOperand(0);
20054 MVT VT = Input.getSimpleValueType();
20055 MVT RootVT = Root.getSimpleValueType();
20058 // Just remove no-op shuffle masks.
20059 if (Mask.size() == 1) {
20060 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
20065 // Use the float domain if the operand type is a floating point type.
20066 bool FloatDomain = VT.isFloatingPoint();
20068 // For floating point shuffles, we don't have free copies in the shuffle
20069 // instructions or the ability to load as part of the instruction, so
20070 // canonicalize their shuffles to UNPCK or MOV variants.
20072 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20073 // vectors because it can have a load folded into it that UNPCK cannot. This
20074 // doesn't preclude something switching to the shorter encoding post-RA.
20076 // FIXME: Should teach these routines about AVX vector widths.
20077 if (FloatDomain && VT.getSizeInBits() == 128) {
20078 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20079 bool Lo = Mask.equals({0, 0});
20082 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20083 // is no slower than UNPCKLPD but has the option to fold the input operand
20084 // into even an unaligned memory load.
20085 if (Lo && Subtarget->hasSSE3()) {
20086 Shuffle = X86ISD::MOVDDUP;
20087 ShuffleVT = MVT::v2f64;
20089 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20090 // than the UNPCK variants.
20091 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20092 ShuffleVT = MVT::v4f32;
20094 if (Depth == 1 && Root->getOpcode() == Shuffle)
20095 return false; // Nothing to do!
20096 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20097 DCI.AddToWorklist(Op.getNode());
20098 if (Shuffle == X86ISD::MOVDDUP)
20099 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20101 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20102 DCI.AddToWorklist(Op.getNode());
20103 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20107 if (Subtarget->hasSSE3() &&
20108 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20109 bool Lo = Mask.equals({0, 0, 2, 2});
20110 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20111 MVT ShuffleVT = MVT::v4f32;
20112 if (Depth == 1 && Root->getOpcode() == Shuffle)
20113 return false; // Nothing to do!
20114 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20115 DCI.AddToWorklist(Op.getNode());
20116 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20117 DCI.AddToWorklist(Op.getNode());
20118 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20122 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20123 bool Lo = Mask.equals({0, 0, 1, 1});
20124 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20125 MVT ShuffleVT = MVT::v4f32;
20126 if (Depth == 1 && Root->getOpcode() == Shuffle)
20127 return false; // Nothing to do!
20128 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20129 DCI.AddToWorklist(Op.getNode());
20130 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20131 DCI.AddToWorklist(Op.getNode());
20132 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20138 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20139 // variants as none of these have single-instruction variants that are
20140 // superior to the UNPCK formulation.
20141 if (!FloatDomain && VT.getSizeInBits() == 128 &&
20142 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20143 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20144 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20146 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20147 bool Lo = Mask[0] == 0;
20148 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20149 if (Depth == 1 && Root->getOpcode() == Shuffle)
20150 return false; // Nothing to do!
20152 switch (Mask.size()) {
20154 ShuffleVT = MVT::v8i16;
20157 ShuffleVT = MVT::v16i8;
20160 llvm_unreachable("Impossible mask size!");
20162 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20163 DCI.AddToWorklist(Op.getNode());
20164 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20165 DCI.AddToWorklist(Op.getNode());
20166 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20171 // Don't try to re-form single instruction chains under any circumstances now
20172 // that we've done encoding canonicalization for them.
20176 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20177 // can replace them with a single PSHUFB instruction profitably. Intel's
20178 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20179 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20180 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20181 SmallVector<SDValue, 16> PSHUFBMask;
20182 int NumBytes = VT.getSizeInBits() / 8;
20183 int Ratio = NumBytes / Mask.size();
20184 for (int i = 0; i < NumBytes; ++i) {
20185 if (Mask[i / Ratio] == SM_SentinelUndef) {
20186 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20189 int M = Mask[i / Ratio] != SM_SentinelZero
20190 ? Ratio * Mask[i / Ratio] + i % Ratio
20192 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20194 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20195 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20196 DCI.AddToWorklist(Op.getNode());
20197 SDValue PSHUFBMaskOp =
20198 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20199 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20200 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20201 DCI.AddToWorklist(Op.getNode());
20202 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20207 // Failed to find any combines.
20211 /// \brief Fully generic combining of x86 shuffle instructions.
20213 /// This should be the last combine run over the x86 shuffle instructions. Once
20214 /// they have been fully optimized, this will recursively consider all chains
20215 /// of single-use shuffle instructions, build a generic model of the cumulative
20216 /// shuffle operation, and check for simpler instructions which implement this
20217 /// operation. We use this primarily for two purposes:
20219 /// 1) Collapse generic shuffles to specialized single instructions when
20220 /// equivalent. In most cases, this is just an encoding size win, but
20221 /// sometimes we will collapse multiple generic shuffles into a single
20222 /// special-purpose shuffle.
20223 /// 2) Look for sequences of shuffle instructions with 3 or more total
20224 /// instructions, and replace them with the slightly more expensive SSSE3
20225 /// PSHUFB instruction if available. We do this as the last combining step
20226 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
20227 /// a suitable short sequence of other instructions. The PHUFB will either
20228 /// use a register or have to read from memory and so is slightly (but only
20229 /// slightly) more expensive than the other shuffle instructions.
20231 /// Because this is inherently a quadratic operation (for each shuffle in
20232 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20233 /// This should never be an issue in practice as the shuffle lowering doesn't
20234 /// produce sequences of more than 8 instructions.
20236 /// FIXME: We will currently miss some cases where the redundant shuffling
20237 /// would simplify under the threshold for PSHUFB formation because of
20238 /// combine-ordering. To fix this, we should do the redundant instruction
20239 /// combining in this recursive walk.
20240 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20241 ArrayRef<int> RootMask,
20242 int Depth, bool HasPSHUFB,
20244 TargetLowering::DAGCombinerInfo &DCI,
20245 const X86Subtarget *Subtarget) {
20246 // Bound the depth of our recursive combine because this is ultimately
20247 // quadratic in nature.
20251 // Directly rip through bitcasts to find the underlying operand.
20252 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20253 Op = Op.getOperand(0);
20255 MVT VT = Op.getSimpleValueType();
20256 if (!VT.isVector())
20257 return false; // Bail if we hit a non-vector.
20259 assert(Root.getSimpleValueType().isVector() &&
20260 "Shuffles operate on vector types!");
20261 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20262 "Can only combine shuffles of the same vector register size.");
20264 if (!isTargetShuffle(Op.getOpcode()))
20266 SmallVector<int, 16> OpMask;
20268 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20269 // We only can combine unary shuffles which we can decode the mask for.
20270 if (!HaveMask || !IsUnary)
20273 assert(VT.getVectorNumElements() == OpMask.size() &&
20274 "Different mask size from vector size!");
20275 assert(((RootMask.size() > OpMask.size() &&
20276 RootMask.size() % OpMask.size() == 0) ||
20277 (OpMask.size() > RootMask.size() &&
20278 OpMask.size() % RootMask.size() == 0) ||
20279 OpMask.size() == RootMask.size()) &&
20280 "The smaller number of elements must divide the larger.");
20281 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20282 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20283 assert(((RootRatio == 1 && OpRatio == 1) ||
20284 (RootRatio == 1) != (OpRatio == 1)) &&
20285 "Must not have a ratio for both incoming and op masks!");
20287 SmallVector<int, 16> Mask;
20288 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20290 // Merge this shuffle operation's mask into our accumulated mask. Note that
20291 // this shuffle's mask will be the first applied to the input, followed by the
20292 // root mask to get us all the way to the root value arrangement. The reason
20293 // for this order is that we are recursing up the operation chain.
20294 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20295 int RootIdx = i / RootRatio;
20296 if (RootMask[RootIdx] < 0) {
20297 // This is a zero or undef lane, we're done.
20298 Mask.push_back(RootMask[RootIdx]);
20302 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20303 int OpIdx = RootMaskedIdx / OpRatio;
20304 if (OpMask[OpIdx] < 0) {
20305 // The incoming lanes are zero or undef, it doesn't matter which ones we
20307 Mask.push_back(OpMask[OpIdx]);
20311 // Ok, we have non-zero lanes, map them through.
20312 Mask.push_back(OpMask[OpIdx] * OpRatio +
20313 RootMaskedIdx % OpRatio);
20316 // See if we can recurse into the operand to combine more things.
20317 switch (Op.getOpcode()) {
20318 case X86ISD::PSHUFB:
20320 case X86ISD::PSHUFD:
20321 case X86ISD::PSHUFHW:
20322 case X86ISD::PSHUFLW:
20323 if (Op.getOperand(0).hasOneUse() &&
20324 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20325 HasPSHUFB, DAG, DCI, Subtarget))
20329 case X86ISD::UNPCKL:
20330 case X86ISD::UNPCKH:
20331 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20332 // We can't check for single use, we have to check that this shuffle is the only user.
20333 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20334 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20335 HasPSHUFB, DAG, DCI, Subtarget))
20340 // Minor canonicalization of the accumulated shuffle mask to make it easier
20341 // to match below. All this does is detect masks with squential pairs of
20342 // elements, and shrink them to the half-width mask. It does this in a loop
20343 // so it will reduce the size of the mask to the minimal width mask which
20344 // performs an equivalent shuffle.
20345 SmallVector<int, 16> WidenedMask;
20346 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20347 Mask = std::move(WidenedMask);
20348 WidenedMask.clear();
20351 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20355 /// \brief Get the PSHUF-style mask from PSHUF node.
20357 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20358 /// PSHUF-style masks that can be reused with such instructions.
20359 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20360 MVT VT = N.getSimpleValueType();
20361 SmallVector<int, 4> Mask;
20363 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20367 // If we have more than 128-bits, only the low 128-bits of shuffle mask
20368 // matter. Check that the upper masks are repeats and remove them.
20369 if (VT.getSizeInBits() > 128) {
20370 int LaneElts = 128 / VT.getScalarSizeInBits();
20372 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20373 for (int j = 0; j < LaneElts; ++j)
20374 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20375 "Mask doesn't repeat in high 128-bit lanes!");
20377 Mask.resize(LaneElts);
20380 switch (N.getOpcode()) {
20381 case X86ISD::PSHUFD:
20383 case X86ISD::PSHUFLW:
20386 case X86ISD::PSHUFHW:
20387 Mask.erase(Mask.begin(), Mask.begin() + 4);
20388 for (int &M : Mask)
20392 llvm_unreachable("No valid shuffle instruction found!");
20396 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20398 /// We walk up the chain and look for a combinable shuffle, skipping over
20399 /// shuffles that we could hoist this shuffle's transformation past without
20400 /// altering anything.
20402 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20404 TargetLowering::DAGCombinerInfo &DCI) {
20405 assert(N.getOpcode() == X86ISD::PSHUFD &&
20406 "Called with something other than an x86 128-bit half shuffle!");
20409 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20410 // of the shuffles in the chain so that we can form a fresh chain to replace
20412 SmallVector<SDValue, 8> Chain;
20413 SDValue V = N.getOperand(0);
20414 for (; V.hasOneUse(); V = V.getOperand(0)) {
20415 switch (V.getOpcode()) {
20417 return SDValue(); // Nothing combined!
20420 // Skip bitcasts as we always know the type for the target specific
20424 case X86ISD::PSHUFD:
20425 // Found another dword shuffle.
20428 case X86ISD::PSHUFLW:
20429 // Check that the low words (being shuffled) are the identity in the
20430 // dword shuffle, and the high words are self-contained.
20431 if (Mask[0] != 0 || Mask[1] != 1 ||
20432 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20435 Chain.push_back(V);
20438 case X86ISD::PSHUFHW:
20439 // Check that the high words (being shuffled) are the identity in the
20440 // dword shuffle, and the low words are self-contained.
20441 if (Mask[2] != 2 || Mask[3] != 3 ||
20442 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20445 Chain.push_back(V);
20448 case X86ISD::UNPCKL:
20449 case X86ISD::UNPCKH:
20450 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20451 // shuffle into a preceding word shuffle.
20452 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20453 V.getSimpleValueType().getScalarType() != MVT::i16)
20456 // Search for a half-shuffle which we can combine with.
20457 unsigned CombineOp =
20458 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20459 if (V.getOperand(0) != V.getOperand(1) ||
20460 !V->isOnlyUserOf(V.getOperand(0).getNode()))
20462 Chain.push_back(V);
20463 V = V.getOperand(0);
20465 switch (V.getOpcode()) {
20467 return SDValue(); // Nothing to combine.
20469 case X86ISD::PSHUFLW:
20470 case X86ISD::PSHUFHW:
20471 if (V.getOpcode() == CombineOp)
20474 Chain.push_back(V);
20478 V = V.getOperand(0);
20482 } while (V.hasOneUse());
20485 // Break out of the loop if we break out of the switch.
20489 if (!V.hasOneUse())
20490 // We fell out of the loop without finding a viable combining instruction.
20493 // Merge this node's mask and our incoming mask.
20494 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20495 for (int &M : Mask)
20497 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20498 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20500 // Rebuild the chain around this new shuffle.
20501 while (!Chain.empty()) {
20502 SDValue W = Chain.pop_back_val();
20504 if (V.getValueType() != W.getOperand(0).getValueType())
20505 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20507 switch (W.getOpcode()) {
20509 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20511 case X86ISD::UNPCKL:
20512 case X86ISD::UNPCKH:
20513 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20516 case X86ISD::PSHUFD:
20517 case X86ISD::PSHUFLW:
20518 case X86ISD::PSHUFHW:
20519 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20523 if (V.getValueType() != N.getValueType())
20524 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20526 // Return the new chain to replace N.
20530 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20532 /// We walk up the chain, skipping shuffles of the other half and looking
20533 /// through shuffles which switch halves trying to find a shuffle of the same
20534 /// pair of dwords.
20535 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20537 TargetLowering::DAGCombinerInfo &DCI) {
20539 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20540 "Called with something other than an x86 128-bit half shuffle!");
20542 unsigned CombineOpcode = N.getOpcode();
20544 // Walk up a single-use chain looking for a combinable shuffle.
20545 SDValue V = N.getOperand(0);
20546 for (; V.hasOneUse(); V = V.getOperand(0)) {
20547 switch (V.getOpcode()) {
20549 return false; // Nothing combined!
20552 // Skip bitcasts as we always know the type for the target specific
20556 case X86ISD::PSHUFLW:
20557 case X86ISD::PSHUFHW:
20558 if (V.getOpcode() == CombineOpcode)
20561 // Other-half shuffles are no-ops.
20564 // Break out of the loop if we break out of the switch.
20568 if (!V.hasOneUse())
20569 // We fell out of the loop without finding a viable combining instruction.
20572 // Combine away the bottom node as its shuffle will be accumulated into
20573 // a preceding shuffle.
20574 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20576 // Record the old value.
20579 // Merge this node's mask and our incoming mask (adjusted to account for all
20580 // the pshufd instructions encountered).
20581 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20582 for (int &M : Mask)
20584 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20585 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20587 // Check that the shuffles didn't cancel each other out. If not, we need to
20588 // combine to the new one.
20590 // Replace the combinable shuffle with the combined one, updating all users
20591 // so that we re-evaluate the chain here.
20592 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20597 /// \brief Try to combine x86 target specific shuffles.
20598 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20599 TargetLowering::DAGCombinerInfo &DCI,
20600 const X86Subtarget *Subtarget) {
20602 MVT VT = N.getSimpleValueType();
20603 SmallVector<int, 4> Mask;
20605 switch (N.getOpcode()) {
20606 case X86ISD::PSHUFD:
20607 case X86ISD::PSHUFLW:
20608 case X86ISD::PSHUFHW:
20609 Mask = getPSHUFShuffleMask(N);
20610 assert(Mask.size() == 4);
20616 // Nuke no-op shuffles that show up after combining.
20617 if (isNoopShuffleMask(Mask))
20618 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20620 // Look for simplifications involving one or two shuffle instructions.
20621 SDValue V = N.getOperand(0);
20622 switch (N.getOpcode()) {
20625 case X86ISD::PSHUFLW:
20626 case X86ISD::PSHUFHW:
20627 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20629 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20630 return SDValue(); // We combined away this shuffle, so we're done.
20632 // See if this reduces to a PSHUFD which is no more expensive and can
20633 // combine with more operations. Note that it has to at least flip the
20634 // dwords as otherwise it would have been removed as a no-op.
20635 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20636 int DMask[] = {0, 1, 2, 3};
20637 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20638 DMask[DOffset + 0] = DOffset + 1;
20639 DMask[DOffset + 1] = DOffset + 0;
20640 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20641 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20642 DCI.AddToWorklist(V.getNode());
20643 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20644 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20645 DCI.AddToWorklist(V.getNode());
20646 return DAG.getNode(ISD::BITCAST, DL, VT, V);
20649 // Look for shuffle patterns which can be implemented as a single unpack.
20650 // FIXME: This doesn't handle the location of the PSHUFD generically, and
20651 // only works when we have a PSHUFD followed by two half-shuffles.
20652 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20653 (V.getOpcode() == X86ISD::PSHUFLW ||
20654 V.getOpcode() == X86ISD::PSHUFHW) &&
20655 V.getOpcode() != N.getOpcode() &&
20657 SDValue D = V.getOperand(0);
20658 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20659 D = D.getOperand(0);
20660 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20661 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20662 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20663 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20664 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20666 for (int i = 0; i < 4; ++i) {
20667 WordMask[i + NOffset] = Mask[i] + NOffset;
20668 WordMask[i + VOffset] = VMask[i] + VOffset;
20670 // Map the word mask through the DWord mask.
20672 for (int i = 0; i < 8; ++i)
20673 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20674 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20675 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20676 // We can replace all three shuffles with an unpack.
20677 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20678 DCI.AddToWorklist(V.getNode());
20679 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20688 case X86ISD::PSHUFD:
20689 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20698 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20700 /// We combine this directly on the abstract vector shuffle nodes so it is
20701 /// easier to generically match. We also insert dummy vector shuffle nodes for
20702 /// the operands which explicitly discard the lanes which are unused by this
20703 /// operation to try to flow through the rest of the combiner the fact that
20704 /// they're unused.
20705 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20707 EVT VT = N->getValueType(0);
20709 // We only handle target-independent shuffles.
20710 // FIXME: It would be easy and harmless to use the target shuffle mask
20711 // extraction tool to support more.
20712 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20715 auto *SVN = cast<ShuffleVectorSDNode>(N);
20716 ArrayRef<int> Mask = SVN->getMask();
20717 SDValue V1 = N->getOperand(0);
20718 SDValue V2 = N->getOperand(1);
20720 // We require the first shuffle operand to be the SUB node, and the second to
20721 // be the ADD node.
20722 // FIXME: We should support the commuted patterns.
20723 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20726 // If there are other uses of these operations we can't fold them.
20727 if (!V1->hasOneUse() || !V2->hasOneUse())
20730 // Ensure that both operations have the same operands. Note that we can
20731 // commute the FADD operands.
20732 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20733 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20734 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20737 // We're looking for blends between FADD and FSUB nodes. We insist on these
20738 // nodes being lined up in a specific expected pattern.
20739 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20740 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20741 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20744 // Only specific types are legal at this point, assert so we notice if and
20745 // when these change.
20746 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20747 VT == MVT::v4f64) &&
20748 "Unknown vector type encountered!");
20750 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20753 /// PerformShuffleCombine - Performs several different shuffle combines.
20754 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20755 TargetLowering::DAGCombinerInfo &DCI,
20756 const X86Subtarget *Subtarget) {
20758 SDValue N0 = N->getOperand(0);
20759 SDValue N1 = N->getOperand(1);
20760 EVT VT = N->getValueType(0);
20762 // Don't create instructions with illegal types after legalize types has run.
20763 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20764 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20767 // If we have legalized the vector types, look for blends of FADD and FSUB
20768 // nodes that we can fuse into an ADDSUB node.
20769 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20770 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20773 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20774 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20775 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20776 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20778 // During Type Legalization, when promoting illegal vector types,
20779 // the backend might introduce new shuffle dag nodes and bitcasts.
20781 // This code performs the following transformation:
20782 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20783 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20785 // We do this only if both the bitcast and the BINOP dag nodes have
20786 // one use. Also, perform this transformation only if the new binary
20787 // operation is legal. This is to avoid introducing dag nodes that
20788 // potentially need to be further expanded (or custom lowered) into a
20789 // less optimal sequence of dag nodes.
20790 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20791 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20792 N0.getOpcode() == ISD::BITCAST) {
20793 SDValue BC0 = N0.getOperand(0);
20794 EVT SVT = BC0.getValueType();
20795 unsigned Opcode = BC0.getOpcode();
20796 unsigned NumElts = VT.getVectorNumElements();
20798 if (BC0.hasOneUse() && SVT.isVector() &&
20799 SVT.getVectorNumElements() * 2 == NumElts &&
20800 TLI.isOperationLegal(Opcode, VT)) {
20801 bool CanFold = false;
20813 unsigned SVTNumElts = SVT.getVectorNumElements();
20814 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20815 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20816 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20817 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20818 CanFold = SVOp->getMaskElt(i) < 0;
20821 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20822 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20823 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20824 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20829 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20830 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20831 // consecutive, non-overlapping, and in the right order.
20832 SmallVector<SDValue, 16> Elts;
20833 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20834 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20836 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20840 if (isTargetShuffle(N->getOpcode())) {
20842 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20843 if (Shuffle.getNode())
20846 // Try recursively combining arbitrary sequences of x86 shuffle
20847 // instructions into higher-order shuffles. We do this after combining
20848 // specific PSHUF instruction sequences into their minimal form so that we
20849 // can evaluate how many specialized shuffle instructions are involved in
20850 // a particular chain.
20851 SmallVector<int, 1> NonceMask; // Just a placeholder.
20852 NonceMask.push_back(0);
20853 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20854 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20856 return SDValue(); // This routine will use CombineTo to replace N.
20862 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20863 /// specific shuffle of a load can be folded into a single element load.
20864 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20865 /// shuffles have been custom lowered so we need to handle those here.
20866 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20867 TargetLowering::DAGCombinerInfo &DCI) {
20868 if (DCI.isBeforeLegalizeOps())
20871 SDValue InVec = N->getOperand(0);
20872 SDValue EltNo = N->getOperand(1);
20874 if (!isa<ConstantSDNode>(EltNo))
20877 EVT OriginalVT = InVec.getValueType();
20879 if (InVec.getOpcode() == ISD::BITCAST) {
20880 // Don't duplicate a load with other uses.
20881 if (!InVec.hasOneUse())
20883 EVT BCVT = InVec.getOperand(0).getValueType();
20884 if (!BCVT.isVector() ||
20885 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20887 InVec = InVec.getOperand(0);
20890 EVT CurrentVT = InVec.getValueType();
20892 if (!isTargetShuffle(InVec.getOpcode()))
20895 // Don't duplicate a load with other uses.
20896 if (!InVec.hasOneUse())
20899 SmallVector<int, 16> ShuffleMask;
20901 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20902 ShuffleMask, UnaryShuffle))
20905 // Select the input vector, guarding against out of range extract vector.
20906 unsigned NumElems = CurrentVT.getVectorNumElements();
20907 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20908 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20909 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20910 : InVec.getOperand(1);
20912 // If inputs to shuffle are the same for both ops, then allow 2 uses
20913 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20914 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20916 if (LdNode.getOpcode() == ISD::BITCAST) {
20917 // Don't duplicate a load with other uses.
20918 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20921 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20922 LdNode = LdNode.getOperand(0);
20925 if (!ISD::isNormalLoad(LdNode.getNode()))
20928 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20930 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20933 EVT EltVT = N->getValueType(0);
20934 // If there's a bitcast before the shuffle, check if the load type and
20935 // alignment is valid.
20936 unsigned Align = LN0->getAlignment();
20937 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20938 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20939 EltVT.getTypeForEVT(*DAG.getContext()));
20941 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20944 // All checks match so transform back to vector_shuffle so that DAG combiner
20945 // can finish the job
20948 // Create shuffle node taking into account the case that its a unary shuffle
20949 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20950 : InVec.getOperand(1);
20951 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20952 InVec.getOperand(0), Shuffle,
20954 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20955 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20959 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20960 /// special and don't usually play with other vector types, it's better to
20961 /// handle them early to be sure we emit efficient code by avoiding
20962 /// store-load conversions.
20963 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20964 if (N->getValueType(0) != MVT::x86mmx ||
20965 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20966 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20969 SDValue V = N->getOperand(0);
20970 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20971 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20972 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20973 N->getValueType(0), V.getOperand(0));
20978 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20979 /// generation and convert it from being a bunch of shuffles and extracts
20980 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20981 /// storing the value and loading scalars back, while for x64 we should
20982 /// use 64-bit extracts and shifts.
20983 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20984 TargetLowering::DAGCombinerInfo &DCI) {
20985 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20986 if (NewOp.getNode())
20989 SDValue InputVector = N->getOperand(0);
20990 SDLoc dl(InputVector);
20991 // Detect mmx to i32 conversion through a v2i32 elt extract.
20992 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20993 N->getValueType(0) == MVT::i32 &&
20994 InputVector.getValueType() == MVT::v2i32) {
20996 // The bitcast source is a direct mmx result.
20997 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20998 if (MMXSrc.getValueType() == MVT::x86mmx)
20999 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21000 N->getValueType(0),
21001 InputVector.getNode()->getOperand(0));
21003 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21004 SDValue MMXSrcOp = MMXSrc.getOperand(0);
21005 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21006 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21007 MMXSrcOp.getOpcode() == ISD::BITCAST &&
21008 MMXSrcOp.getValueType() == MVT::v1i64 &&
21009 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21010 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21011 N->getValueType(0),
21012 MMXSrcOp.getOperand(0));
21015 EVT VT = N->getValueType(0);
21017 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21018 InputVector.getOpcode() == ISD::BITCAST &&
21019 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21020 uint64_t ExtractedElt =
21021 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21022 uint64_t InputValue =
21023 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21024 uint64_t Res = (InputValue >> ExtractedElt) & 1;
21025 return DAG.getConstant(Res, dl, MVT::i1);
21027 // Only operate on vectors of 4 elements, where the alternative shuffling
21028 // gets to be more expensive.
21029 if (InputVector.getValueType() != MVT::v4i32)
21032 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21033 // single use which is a sign-extend or zero-extend, and all elements are
21035 SmallVector<SDNode *, 4> Uses;
21036 unsigned ExtractedElements = 0;
21037 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21038 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21039 if (UI.getUse().getResNo() != InputVector.getResNo())
21042 SDNode *Extract = *UI;
21043 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21046 if (Extract->getValueType(0) != MVT::i32)
21048 if (!Extract->hasOneUse())
21050 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21051 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21053 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21056 // Record which element was extracted.
21057 ExtractedElements |=
21058 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21060 Uses.push_back(Extract);
21063 // If not all the elements were used, this may not be worthwhile.
21064 if (ExtractedElements != 15)
21067 // Ok, we've now decided to do the transformation.
21068 // If 64-bit shifts are legal, use the extract-shift sequence,
21069 // otherwise bounce the vector off the cache.
21070 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21073 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21074 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
21075 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21076 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21077 DAG.getConstant(0, dl, VecIdxTy));
21078 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21079 DAG.getConstant(1, dl, VecIdxTy));
21081 SDValue ShAmt = DAG.getConstant(32, dl,
21082 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21083 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21084 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21085 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21086 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21087 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21088 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21090 // Store the value to a temporary stack slot.
21091 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21092 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21093 MachinePointerInfo(), false, false, 0);
21095 EVT ElementType = InputVector.getValueType().getVectorElementType();
21096 unsigned EltSize = ElementType.getSizeInBits() / 8;
21098 // Replace each use (extract) with a load of the appropriate element.
21099 for (unsigned i = 0; i < 4; ++i) {
21100 uint64_t Offset = EltSize * i;
21101 SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21103 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21104 StackPtr, OffsetVal);
21106 // Load the scalar.
21107 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21108 ScalarAddr, MachinePointerInfo(),
21109 false, false, false, 0);
21114 // Replace the extracts
21115 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21116 UE = Uses.end(); UI != UE; ++UI) {
21117 SDNode *Extract = *UI;
21119 SDValue Idx = Extract->getOperand(1);
21120 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21121 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21124 // The replacement was made in place; don't return anything.
21128 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21129 static std::pair<unsigned, bool>
21130 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21131 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21132 if (!VT.isVector())
21133 return std::make_pair(0, false);
21135 bool NeedSplit = false;
21136 switch (VT.getSimpleVT().SimpleTy) {
21137 default: return std::make_pair(0, false);
21140 if (!Subtarget->hasVLX())
21141 return std::make_pair(0, false);
21145 if (!Subtarget->hasBWI())
21146 return std::make_pair(0, false);
21150 if (!Subtarget->hasAVX512())
21151 return std::make_pair(0, false);
21156 if (!Subtarget->hasAVX2())
21158 if (!Subtarget->hasAVX())
21159 return std::make_pair(0, false);
21164 if (!Subtarget->hasSSE2())
21165 return std::make_pair(0, false);
21168 // SSE2 has only a small subset of the operations.
21169 bool hasUnsigned = Subtarget->hasSSE41() ||
21170 (Subtarget->hasSSE2() && VT == MVT::v16i8);
21171 bool hasSigned = Subtarget->hasSSE41() ||
21172 (Subtarget->hasSSE2() && VT == MVT::v8i16);
21174 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21177 // Check for x CC y ? x : y.
21178 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21179 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21184 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21187 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21190 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21193 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21195 // Check for x CC y ? y : x -- a min/max with reversed arms.
21196 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21197 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21202 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21205 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21208 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21211 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21215 return std::make_pair(Opc, NeedSplit);
21219 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21220 const X86Subtarget *Subtarget) {
21222 SDValue Cond = N->getOperand(0);
21223 SDValue LHS = N->getOperand(1);
21224 SDValue RHS = N->getOperand(2);
21226 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21227 SDValue CondSrc = Cond->getOperand(0);
21228 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21229 Cond = CondSrc->getOperand(0);
21232 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21235 // A vselect where all conditions and data are constants can be optimized into
21236 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21237 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21238 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21241 unsigned MaskValue = 0;
21242 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21245 MVT VT = N->getSimpleValueType(0);
21246 unsigned NumElems = VT.getVectorNumElements();
21247 SmallVector<int, 8> ShuffleMask(NumElems, -1);
21248 for (unsigned i = 0; i < NumElems; ++i) {
21249 // Be sure we emit undef where we can.
21250 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21251 ShuffleMask[i] = -1;
21253 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21256 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21257 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21259 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21262 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21264 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21265 TargetLowering::DAGCombinerInfo &DCI,
21266 const X86Subtarget *Subtarget) {
21268 SDValue Cond = N->getOperand(0);
21269 // Get the LHS/RHS of the select.
21270 SDValue LHS = N->getOperand(1);
21271 SDValue RHS = N->getOperand(2);
21272 EVT VT = LHS.getValueType();
21273 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21275 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21276 // instructions match the semantics of the common C idiom x<y?x:y but not
21277 // x<=y?x:y, because of how they handle negative zero (which can be
21278 // ignored in unsafe-math mode).
21279 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21280 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21281 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21282 (Subtarget->hasSSE2() ||
21283 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21284 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21286 unsigned Opcode = 0;
21287 // Check for x CC y ? x : y.
21288 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21289 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21293 // Converting this to a min would handle NaNs incorrectly, and swapping
21294 // the operands would cause it to handle comparisons between positive
21295 // and negative zero incorrectly.
21296 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21297 if (!DAG.getTarget().Options.UnsafeFPMath &&
21298 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21300 std::swap(LHS, RHS);
21302 Opcode = X86ISD::FMIN;
21305 // Converting this to a min would handle comparisons between positive
21306 // and negative zero incorrectly.
21307 if (!DAG.getTarget().Options.UnsafeFPMath &&
21308 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21310 Opcode = X86ISD::FMIN;
21313 // Converting this to a min would handle both negative zeros and NaNs
21314 // incorrectly, but we can swap the operands to fix both.
21315 std::swap(LHS, RHS);
21319 Opcode = X86ISD::FMIN;
21323 // Converting this to a max would handle comparisons between positive
21324 // and negative zero incorrectly.
21325 if (!DAG.getTarget().Options.UnsafeFPMath &&
21326 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21328 Opcode = X86ISD::FMAX;
21331 // Converting this to a max would handle NaNs incorrectly, and swapping
21332 // the operands would cause it to handle comparisons between positive
21333 // and negative zero incorrectly.
21334 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21335 if (!DAG.getTarget().Options.UnsafeFPMath &&
21336 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21338 std::swap(LHS, RHS);
21340 Opcode = X86ISD::FMAX;
21343 // Converting this to a max would handle both negative zeros and NaNs
21344 // incorrectly, but we can swap the operands to fix both.
21345 std::swap(LHS, RHS);
21349 Opcode = X86ISD::FMAX;
21352 // Check for x CC y ? y : x -- a min/max with reversed arms.
21353 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21354 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21358 // Converting this to a min would handle comparisons between positive
21359 // and negative zero incorrectly, and swapping the operands would
21360 // cause it to handle NaNs incorrectly.
21361 if (!DAG.getTarget().Options.UnsafeFPMath &&
21362 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21363 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21365 std::swap(LHS, RHS);
21367 Opcode = X86ISD::FMIN;
21370 // Converting this to a min would handle NaNs incorrectly.
21371 if (!DAG.getTarget().Options.UnsafeFPMath &&
21372 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21374 Opcode = X86ISD::FMIN;
21377 // Converting this to a min would handle both negative zeros and NaNs
21378 // incorrectly, but we can swap the operands to fix both.
21379 std::swap(LHS, RHS);
21383 Opcode = X86ISD::FMIN;
21387 // Converting this to a max would handle NaNs incorrectly.
21388 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21390 Opcode = X86ISD::FMAX;
21393 // Converting this to a max would handle comparisons between positive
21394 // and negative zero incorrectly, and swapping the operands would
21395 // cause it to handle NaNs incorrectly.
21396 if (!DAG.getTarget().Options.UnsafeFPMath &&
21397 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21398 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21400 std::swap(LHS, RHS);
21402 Opcode = X86ISD::FMAX;
21405 // Converting this to a max would handle both negative zeros and NaNs
21406 // incorrectly, but we can swap the operands to fix both.
21407 std::swap(LHS, RHS);
21411 Opcode = X86ISD::FMAX;
21417 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21420 EVT CondVT = Cond.getValueType();
21421 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21422 CondVT.getVectorElementType() == MVT::i1) {
21423 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21424 // lowering on KNL. In this case we convert it to
21425 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21426 // The same situation for all 128 and 256-bit vectors of i8 and i16.
21427 // Since SKX these selects have a proper lowering.
21428 EVT OpVT = LHS.getValueType();
21429 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21430 (OpVT.getVectorElementType() == MVT::i8 ||
21431 OpVT.getVectorElementType() == MVT::i16) &&
21432 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21433 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21434 DCI.AddToWorklist(Cond.getNode());
21435 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21438 // If this is a select between two integer constants, try to do some
21440 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21441 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21442 // Don't do this for crazy integer types.
21443 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21444 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21445 // so that TrueC (the true value) is larger than FalseC.
21446 bool NeedsCondInvert = false;
21448 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21449 // Efficiently invertible.
21450 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
21451 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
21452 isa<ConstantSDNode>(Cond.getOperand(1))))) {
21453 NeedsCondInvert = true;
21454 std::swap(TrueC, FalseC);
21457 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
21458 if (FalseC->getAPIntValue() == 0 &&
21459 TrueC->getAPIntValue().isPowerOf2()) {
21460 if (NeedsCondInvert) // Invert the condition if needed.
21461 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21462 DAG.getConstant(1, DL, Cond.getValueType()));
21464 // Zero extend the condition if needed.
21465 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21467 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21468 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21469 DAG.getConstant(ShAmt, DL, MVT::i8));
21472 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21473 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21474 if (NeedsCondInvert) // Invert the condition if needed.
21475 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21476 DAG.getConstant(1, DL, Cond.getValueType()));
21478 // Zero extend the condition if needed.
21479 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21480 FalseC->getValueType(0), Cond);
21481 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21482 SDValue(FalseC, 0));
21485 // Optimize cases that will turn into an LEA instruction. This requires
21486 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21487 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21488 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21489 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21491 bool isFastMultiplier = false;
21493 switch ((unsigned char)Diff) {
21495 case 1: // result = add base, cond
21496 case 2: // result = lea base( , cond*2)
21497 case 3: // result = lea base(cond, cond*2)
21498 case 4: // result = lea base( , cond*4)
21499 case 5: // result = lea base(cond, cond*4)
21500 case 8: // result = lea base( , cond*8)
21501 case 9: // result = lea base(cond, cond*8)
21502 isFastMultiplier = true;
21507 if (isFastMultiplier) {
21508 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21509 if (NeedsCondInvert) // Invert the condition if needed.
21510 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21511 DAG.getConstant(1, DL, Cond.getValueType()));
21513 // Zero extend the condition if needed.
21514 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21516 // Scale the condition by the difference.
21518 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21519 DAG.getConstant(Diff, DL,
21520 Cond.getValueType()));
21522 // Add the base if non-zero.
21523 if (FalseC->getAPIntValue() != 0)
21524 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21525 SDValue(FalseC, 0));
21532 // Canonicalize max and min:
21533 // (x > y) ? x : y -> (x >= y) ? x : y
21534 // (x < y) ? x : y -> (x <= y) ? x : y
21535 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21536 // the need for an extra compare
21537 // against zero. e.g.
21538 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21540 // testl %edi, %edi
21542 // cmovgl %edi, %eax
21546 // cmovsl %eax, %edi
21547 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21548 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21549 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21550 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21555 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21556 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21557 Cond.getOperand(0), Cond.getOperand(1), NewCC);
21558 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21563 // Early exit check
21564 if (!TLI.isTypeLegal(VT))
21567 // Match VSELECTs into subs with unsigned saturation.
21568 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21569 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21570 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21571 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21572 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21574 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21575 // left side invert the predicate to simplify logic below.
21577 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21579 CC = ISD::getSetCCInverse(CC, true);
21580 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21584 if (Other.getNode() && Other->getNumOperands() == 2 &&
21585 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21586 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21587 SDValue CondRHS = Cond->getOperand(1);
21589 // Look for a general sub with unsigned saturation first.
21590 // x >= y ? x-y : 0 --> subus x, y
21591 // x > y ? x-y : 0 --> subus x, y
21592 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21593 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21594 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21596 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21597 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21598 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21599 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21600 // If the RHS is a constant we have to reverse the const
21601 // canonicalization.
21602 // x > C-1 ? x+-C : 0 --> subus x, C
21603 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21604 CondRHSConst->getAPIntValue() ==
21605 (-OpRHSConst->getAPIntValue() - 1))
21606 return DAG.getNode(
21607 X86ISD::SUBUS, DL, VT, OpLHS,
21608 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21610 // Another special case: If C was a sign bit, the sub has been
21611 // canonicalized into a xor.
21612 // FIXME: Would it be better to use computeKnownBits to determine
21613 // whether it's safe to decanonicalize the xor?
21614 // x s< 0 ? x^C : 0 --> subus x, C
21615 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21616 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21617 OpRHSConst->getAPIntValue().isSignBit())
21618 // Note that we have to rebuild the RHS constant here to ensure we
21619 // don't rely on particular values of undef lanes.
21620 return DAG.getNode(
21621 X86ISD::SUBUS, DL, VT, OpLHS,
21622 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21627 // Try to match a min/max vector operation.
21628 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21629 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21630 unsigned Opc = ret.first;
21631 bool NeedSplit = ret.second;
21633 if (Opc && NeedSplit) {
21634 unsigned NumElems = VT.getVectorNumElements();
21635 // Extract the LHS vectors
21636 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21637 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21639 // Extract the RHS vectors
21640 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21641 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21643 // Create min/max for each subvector
21644 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21645 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21647 // Merge the result
21648 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21650 return DAG.getNode(Opc, DL, VT, LHS, RHS);
21653 // Simplify vector selection if condition value type matches vselect
21655 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21656 assert(Cond.getValueType().isVector() &&
21657 "vector select expects a vector selector!");
21659 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21660 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21662 // Try invert the condition if true value is not all 1s and false value
21664 if (!TValIsAllOnes && !FValIsAllZeros &&
21665 // Check if the selector will be produced by CMPP*/PCMP*
21666 Cond.getOpcode() == ISD::SETCC &&
21667 // Check if SETCC has already been promoted
21668 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21669 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21670 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21672 if (TValIsAllZeros || FValIsAllOnes) {
21673 SDValue CC = Cond.getOperand(2);
21674 ISD::CondCode NewCC =
21675 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21676 Cond.getOperand(0).getValueType().isInteger());
21677 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21678 std::swap(LHS, RHS);
21679 TValIsAllOnes = FValIsAllOnes;
21680 FValIsAllZeros = TValIsAllZeros;
21684 if (TValIsAllOnes || FValIsAllZeros) {
21687 if (TValIsAllOnes && FValIsAllZeros)
21689 else if (TValIsAllOnes)
21690 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21691 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21692 else if (FValIsAllZeros)
21693 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21694 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21696 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21700 // We should generate an X86ISD::BLENDI from a vselect if its argument
21701 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21702 // constants. This specific pattern gets generated when we split a
21703 // selector for a 512 bit vector in a machine without AVX512 (but with
21704 // 256-bit vectors), during legalization:
21706 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21708 // Iff we find this pattern and the build_vectors are built from
21709 // constants, we translate the vselect into a shuffle_vector that we
21710 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21711 if ((N->getOpcode() == ISD::VSELECT ||
21712 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21713 !DCI.isBeforeLegalize()) {
21714 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21715 if (Shuffle.getNode())
21719 // If this is a *dynamic* select (non-constant condition) and we can match
21720 // this node with one of the variable blend instructions, restructure the
21721 // condition so that the blends can use the high bit of each element and use
21722 // SimplifyDemandedBits to simplify the condition operand.
21723 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21724 !DCI.isBeforeLegalize() &&
21725 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21726 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21728 // Don't optimize vector selects that map to mask-registers.
21732 // We can only handle the cases where VSELECT is directly legal on the
21733 // subtarget. We custom lower VSELECT nodes with constant conditions and
21734 // this makes it hard to see whether a dynamic VSELECT will correctly
21735 // lower, so we both check the operation's status and explicitly handle the
21736 // cases where a *dynamic* blend will fail even though a constant-condition
21737 // blend could be custom lowered.
21738 // FIXME: We should find a better way to handle this class of problems.
21739 // Potentially, we should combine constant-condition vselect nodes
21740 // pre-legalization into shuffles and not mark as many types as custom
21742 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21744 // FIXME: We don't support i16-element blends currently. We could and
21745 // should support them by making *all* the bits in the condition be set
21746 // rather than just the high bit and using an i8-element blend.
21747 if (VT.getScalarType() == MVT::i16)
21749 // Dynamic blending was only available from SSE4.1 onward.
21750 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21752 // Byte blends are only available in AVX2
21753 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21754 !Subtarget->hasAVX2())
21757 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21758 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21760 APInt KnownZero, KnownOne;
21761 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21762 DCI.isBeforeLegalizeOps());
21763 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21764 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21766 // If we changed the computation somewhere in the DAG, this change
21767 // will affect all users of Cond.
21768 // Make sure it is fine and update all the nodes so that we do not
21769 // use the generic VSELECT anymore. Otherwise, we may perform
21770 // wrong optimizations as we messed up with the actual expectation
21771 // for the vector boolean values.
21772 if (Cond != TLO.Old) {
21773 // Check all uses of that condition operand to check whether it will be
21774 // consumed by non-BLEND instructions, which may depend on all bits are
21776 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21778 if (I->getOpcode() != ISD::VSELECT)
21779 // TODO: Add other opcodes eventually lowered into BLEND.
21782 // Update all the users of the condition, before committing the change,
21783 // so that the VSELECT optimizations that expect the correct vector
21784 // boolean value will not be triggered.
21785 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21787 DAG.ReplaceAllUsesOfValueWith(
21789 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21790 Cond, I->getOperand(1), I->getOperand(2)));
21791 DCI.CommitTargetLoweringOpt(TLO);
21794 // At this point, only Cond is changed. Change the condition
21795 // just for N to keep the opportunity to optimize all other
21796 // users their own way.
21797 DAG.ReplaceAllUsesOfValueWith(
21799 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21800 TLO.New, N->getOperand(1), N->getOperand(2)));
21808 // Check whether a boolean test is testing a boolean value generated by
21809 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21812 // Simplify the following patterns:
21813 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21814 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21815 // to (Op EFLAGS Cond)
21817 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21818 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21819 // to (Op EFLAGS !Cond)
21821 // where Op could be BRCOND or CMOV.
21823 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21824 // Quit if not CMP and SUB with its value result used.
21825 if (Cmp.getOpcode() != X86ISD::CMP &&
21826 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21829 // Quit if not used as a boolean value.
21830 if (CC != X86::COND_E && CC != X86::COND_NE)
21833 // Check CMP operands. One of them should be 0 or 1 and the other should be
21834 // an SetCC or extended from it.
21835 SDValue Op1 = Cmp.getOperand(0);
21836 SDValue Op2 = Cmp.getOperand(1);
21839 const ConstantSDNode* C = nullptr;
21840 bool needOppositeCond = (CC == X86::COND_E);
21841 bool checkAgainstTrue = false; // Is it a comparison against 1?
21843 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21845 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21847 else // Quit if all operands are not constants.
21850 if (C->getZExtValue() == 1) {
21851 needOppositeCond = !needOppositeCond;
21852 checkAgainstTrue = true;
21853 } else if (C->getZExtValue() != 0)
21854 // Quit if the constant is neither 0 or 1.
21857 bool truncatedToBoolWithAnd = false;
21858 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21859 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21860 SetCC.getOpcode() == ISD::TRUNCATE ||
21861 SetCC.getOpcode() == ISD::AND) {
21862 if (SetCC.getOpcode() == ISD::AND) {
21864 ConstantSDNode *CS;
21865 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21866 CS->getZExtValue() == 1)
21868 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21869 CS->getZExtValue() == 1)
21873 SetCC = SetCC.getOperand(OpIdx);
21874 truncatedToBoolWithAnd = true;
21876 SetCC = SetCC.getOperand(0);
21879 switch (SetCC.getOpcode()) {
21880 case X86ISD::SETCC_CARRY:
21881 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21882 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21883 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21884 // truncated to i1 using 'and'.
21885 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21887 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21888 "Invalid use of SETCC_CARRY!");
21890 case X86ISD::SETCC:
21891 // Set the condition code or opposite one if necessary.
21892 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21893 if (needOppositeCond)
21894 CC = X86::GetOppositeBranchCondition(CC);
21895 return SetCC.getOperand(1);
21896 case X86ISD::CMOV: {
21897 // Check whether false/true value has canonical one, i.e. 0 or 1.
21898 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21899 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21900 // Quit if true value is not a constant.
21903 // Quit if false value is not a constant.
21905 SDValue Op = SetCC.getOperand(0);
21906 // Skip 'zext' or 'trunc' node.
21907 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21908 Op.getOpcode() == ISD::TRUNCATE)
21909 Op = Op.getOperand(0);
21910 // A special case for rdrand/rdseed, where 0 is set if false cond is
21912 if ((Op.getOpcode() != X86ISD::RDRAND &&
21913 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21916 // Quit if false value is not the constant 0 or 1.
21917 bool FValIsFalse = true;
21918 if (FVal && FVal->getZExtValue() != 0) {
21919 if (FVal->getZExtValue() != 1)
21921 // If FVal is 1, opposite cond is needed.
21922 needOppositeCond = !needOppositeCond;
21923 FValIsFalse = false;
21925 // Quit if TVal is not the constant opposite of FVal.
21926 if (FValIsFalse && TVal->getZExtValue() != 1)
21928 if (!FValIsFalse && TVal->getZExtValue() != 0)
21930 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21931 if (needOppositeCond)
21932 CC = X86::GetOppositeBranchCondition(CC);
21933 return SetCC.getOperand(3);
21940 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21942 /// (X86or (X86setcc) (X86setcc))
21943 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21944 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21945 X86::CondCode &CC1, SDValue &Flags,
21947 if (Cond->getOpcode() == X86ISD::CMP) {
21948 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21949 if (!CondOp1C || !CondOp1C->isNullValue())
21952 Cond = Cond->getOperand(0);
21957 SDValue SetCC0, SetCC1;
21958 switch (Cond->getOpcode()) {
21959 default: return false;
21966 SetCC0 = Cond->getOperand(0);
21967 SetCC1 = Cond->getOperand(1);
21971 // Make sure we have SETCC nodes, using the same flags value.
21972 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21973 SetCC1.getOpcode() != X86ISD::SETCC ||
21974 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21977 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21978 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21979 Flags = SetCC0->getOperand(1);
21983 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21984 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21985 TargetLowering::DAGCombinerInfo &DCI,
21986 const X86Subtarget *Subtarget) {
21989 // If the flag operand isn't dead, don't touch this CMOV.
21990 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21993 SDValue FalseOp = N->getOperand(0);
21994 SDValue TrueOp = N->getOperand(1);
21995 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21996 SDValue Cond = N->getOperand(3);
21998 if (CC == X86::COND_E || CC == X86::COND_NE) {
21999 switch (Cond.getOpcode()) {
22003 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22004 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22005 return (CC == X86::COND_E) ? FalseOp : TrueOp;
22011 Flags = checkBoolTestSetCCCombine(Cond, CC);
22012 if (Flags.getNode() &&
22013 // Extra check as FCMOV only supports a subset of X86 cond.
22014 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22015 SDValue Ops[] = { FalseOp, TrueOp,
22016 DAG.getConstant(CC, DL, MVT::i8), Flags };
22017 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22020 // If this is a select between two integer constants, try to do some
22021 // optimizations. Note that the operands are ordered the opposite of SELECT
22023 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22024 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22025 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22026 // larger than FalseC (the false value).
22027 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22028 CC = X86::GetOppositeBranchCondition(CC);
22029 std::swap(TrueC, FalseC);
22030 std::swap(TrueOp, FalseOp);
22033 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
22034 // This is efficient for any integer data type (including i8/i16) and
22036 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22037 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22038 DAG.getConstant(CC, DL, MVT::i8), Cond);
22040 // Zero extend the condition if needed.
22041 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22043 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22044 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22045 DAG.getConstant(ShAmt, DL, MVT::i8));
22046 if (N->getNumValues() == 2) // Dead flag value?
22047 return DCI.CombineTo(N, Cond, SDValue());
22051 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
22052 // for any integer data type, including i8/i16.
22053 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22054 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22055 DAG.getConstant(CC, DL, MVT::i8), Cond);
22057 // Zero extend the condition if needed.
22058 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22059 FalseC->getValueType(0), Cond);
22060 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22061 SDValue(FalseC, 0));
22063 if (N->getNumValues() == 2) // Dead flag value?
22064 return DCI.CombineTo(N, Cond, SDValue());
22068 // Optimize cases that will turn into an LEA instruction. This requires
22069 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22070 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22071 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22072 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22074 bool isFastMultiplier = false;
22076 switch ((unsigned char)Diff) {
22078 case 1: // result = add base, cond
22079 case 2: // result = lea base( , cond*2)
22080 case 3: // result = lea base(cond, cond*2)
22081 case 4: // result = lea base( , cond*4)
22082 case 5: // result = lea base(cond, cond*4)
22083 case 8: // result = lea base( , cond*8)
22084 case 9: // result = lea base(cond, cond*8)
22085 isFastMultiplier = true;
22090 if (isFastMultiplier) {
22091 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22092 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22093 DAG.getConstant(CC, DL, MVT::i8), Cond);
22094 // Zero extend the condition if needed.
22095 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22097 // Scale the condition by the difference.
22099 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22100 DAG.getConstant(Diff, DL, Cond.getValueType()));
22102 // Add the base if non-zero.
22103 if (FalseC->getAPIntValue() != 0)
22104 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22105 SDValue(FalseC, 0));
22106 if (N->getNumValues() == 2) // Dead flag value?
22107 return DCI.CombineTo(N, Cond, SDValue());
22114 // Handle these cases:
22115 // (select (x != c), e, c) -> select (x != c), e, x),
22116 // (select (x == c), c, e) -> select (x == c), x, e)
22117 // where the c is an integer constant, and the "select" is the combination
22118 // of CMOV and CMP.
22120 // The rationale for this change is that the conditional-move from a constant
22121 // needs two instructions, however, conditional-move from a register needs
22122 // only one instruction.
22124 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22125 // some instruction-combining opportunities. This opt needs to be
22126 // postponed as late as possible.
22128 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22129 // the DCI.xxxx conditions are provided to postpone the optimization as
22130 // late as possible.
22132 ConstantSDNode *CmpAgainst = nullptr;
22133 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22134 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22135 !isa<ConstantSDNode>(Cond.getOperand(0))) {
22137 if (CC == X86::COND_NE &&
22138 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22139 CC = X86::GetOppositeBranchCondition(CC);
22140 std::swap(TrueOp, FalseOp);
22143 if (CC == X86::COND_E &&
22144 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22145 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22146 DAG.getConstant(CC, DL, MVT::i8), Cond };
22147 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22152 // Fold and/or of setcc's to double CMOV:
22153 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22154 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22156 // This combine lets us generate:
22157 // cmovcc1 (jcc1 if we don't have CMOV)
22163 // cmovne (jne if we don't have CMOV)
22164 // When we can't use the CMOV instruction, it might increase branch
22166 // When we can use CMOV, or when there is no mispredict, this improves
22167 // throughput and reduces register pressure.
22169 if (CC == X86::COND_NE) {
22171 X86::CondCode CC0, CC1;
22173 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22175 std::swap(FalseOp, TrueOp);
22176 CC0 = X86::GetOppositeBranchCondition(CC0);
22177 CC1 = X86::GetOppositeBranchCondition(CC1);
22180 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22182 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22183 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22184 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22185 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22193 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22194 const X86Subtarget *Subtarget) {
22195 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22197 default: return SDValue();
22198 // SSE/AVX/AVX2 blend intrinsics.
22199 case Intrinsic::x86_avx2_pblendvb:
22200 // Don't try to simplify this intrinsic if we don't have AVX2.
22201 if (!Subtarget->hasAVX2())
22204 case Intrinsic::x86_avx_blendv_pd_256:
22205 case Intrinsic::x86_avx_blendv_ps_256:
22206 // Don't try to simplify this intrinsic if we don't have AVX.
22207 if (!Subtarget->hasAVX())
22210 case Intrinsic::x86_sse41_blendvps:
22211 case Intrinsic::x86_sse41_blendvpd:
22212 case Intrinsic::x86_sse41_pblendvb: {
22213 SDValue Op0 = N->getOperand(1);
22214 SDValue Op1 = N->getOperand(2);
22215 SDValue Mask = N->getOperand(3);
22217 // Don't try to simplify this intrinsic if we don't have SSE4.1.
22218 if (!Subtarget->hasSSE41())
22221 // fold (blend A, A, Mask) -> A
22224 // fold (blend A, B, allZeros) -> A
22225 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22227 // fold (blend A, B, allOnes) -> B
22228 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22231 // Simplify the case where the mask is a constant i32 value.
22232 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22233 if (C->isNullValue())
22235 if (C->isAllOnesValue())
22242 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22243 case Intrinsic::x86_sse2_psrai_w:
22244 case Intrinsic::x86_sse2_psrai_d:
22245 case Intrinsic::x86_avx2_psrai_w:
22246 case Intrinsic::x86_avx2_psrai_d:
22247 case Intrinsic::x86_sse2_psra_w:
22248 case Intrinsic::x86_sse2_psra_d:
22249 case Intrinsic::x86_avx2_psra_w:
22250 case Intrinsic::x86_avx2_psra_d: {
22251 SDValue Op0 = N->getOperand(1);
22252 SDValue Op1 = N->getOperand(2);
22253 EVT VT = Op0.getValueType();
22254 assert(VT.isVector() && "Expected a vector type!");
22256 if (isa<BuildVectorSDNode>(Op1))
22257 Op1 = Op1.getOperand(0);
22259 if (!isa<ConstantSDNode>(Op1))
22262 EVT SVT = VT.getVectorElementType();
22263 unsigned SVTBits = SVT.getSizeInBits();
22265 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22266 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22267 uint64_t ShAmt = C.getZExtValue();
22269 // Don't try to convert this shift into a ISD::SRA if the shift
22270 // count is bigger than or equal to the element size.
22271 if (ShAmt >= SVTBits)
22274 // Trivial case: if the shift count is zero, then fold this
22275 // into the first operand.
22279 // Replace this packed shift intrinsic with a target independent
22282 SDValue Splat = DAG.getConstant(C, DL, VT);
22283 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22288 /// PerformMulCombine - Optimize a single multiply with constant into two
22289 /// in order to implement it with two cheaper instructions, e.g.
22290 /// LEA + SHL, LEA + LEA.
22291 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22292 TargetLowering::DAGCombinerInfo &DCI) {
22293 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22296 EVT VT = N->getValueType(0);
22297 if (VT != MVT::i64 && VT != MVT::i32)
22300 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22303 uint64_t MulAmt = C->getZExtValue();
22304 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22307 uint64_t MulAmt1 = 0;
22308 uint64_t MulAmt2 = 0;
22309 if ((MulAmt % 9) == 0) {
22311 MulAmt2 = MulAmt / 9;
22312 } else if ((MulAmt % 5) == 0) {
22314 MulAmt2 = MulAmt / 5;
22315 } else if ((MulAmt % 3) == 0) {
22317 MulAmt2 = MulAmt / 3;
22320 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22323 if (isPowerOf2_64(MulAmt2) &&
22324 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22325 // If second multiplifer is pow2, issue it first. We want the multiply by
22326 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22328 std::swap(MulAmt1, MulAmt2);
22331 if (isPowerOf2_64(MulAmt1))
22332 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22333 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22335 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22336 DAG.getConstant(MulAmt1, DL, VT));
22338 if (isPowerOf2_64(MulAmt2))
22339 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22340 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22342 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22343 DAG.getConstant(MulAmt2, DL, VT));
22345 // Do not add new nodes to DAG combiner worklist.
22346 DCI.CombineTo(N, NewMul, false);
22351 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22352 SDValue N0 = N->getOperand(0);
22353 SDValue N1 = N->getOperand(1);
22354 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22355 EVT VT = N0.getValueType();
22357 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22358 // since the result of setcc_c is all zero's or all ones.
22359 if (VT.isInteger() && !VT.isVector() &&
22360 N1C && N0.getOpcode() == ISD::AND &&
22361 N0.getOperand(1).getOpcode() == ISD::Constant) {
22362 SDValue N00 = N0.getOperand(0);
22363 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22364 ((N00.getOpcode() == ISD::ANY_EXTEND ||
22365 N00.getOpcode() == ISD::ZERO_EXTEND) &&
22366 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22367 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22368 APInt ShAmt = N1C->getAPIntValue();
22369 Mask = Mask.shl(ShAmt);
22372 return DAG.getNode(ISD::AND, DL, VT,
22373 N00, DAG.getConstant(Mask, DL, VT));
22378 // Hardware support for vector shifts is sparse which makes us scalarize the
22379 // vector operations in many cases. Also, on sandybridge ADD is faster than
22381 // (shl V, 1) -> add V,V
22382 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22383 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22384 assert(N0.getValueType().isVector() && "Invalid vector shift type");
22385 // We shift all of the values by one. In many cases we do not have
22386 // hardware support for this operation. This is better expressed as an ADD
22388 if (N1SplatC->getZExtValue() == 1)
22389 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22395 /// \brief Returns a vector of 0s if the node in input is a vector logical
22396 /// shift by a constant amount which is known to be bigger than or equal
22397 /// to the vector element size in bits.
22398 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22399 const X86Subtarget *Subtarget) {
22400 EVT VT = N->getValueType(0);
22402 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22403 (!Subtarget->hasInt256() ||
22404 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22407 SDValue Amt = N->getOperand(1);
22409 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22410 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22411 APInt ShiftAmt = AmtSplat->getAPIntValue();
22412 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22414 // SSE2/AVX2 logical shifts always return a vector of 0s
22415 // if the shift amount is bigger than or equal to
22416 // the element size. The constant shift amount will be
22417 // encoded as a 8-bit immediate.
22418 if (ShiftAmt.trunc(8).uge(MaxAmount))
22419 return getZeroVector(VT, Subtarget, DAG, DL);
22425 /// PerformShiftCombine - Combine shifts.
22426 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22427 TargetLowering::DAGCombinerInfo &DCI,
22428 const X86Subtarget *Subtarget) {
22429 if (N->getOpcode() == ISD::SHL) {
22430 SDValue V = PerformSHLCombine(N, DAG);
22431 if (V.getNode()) return V;
22434 if (N->getOpcode() != ISD::SRA) {
22435 // Try to fold this logical shift into a zero vector.
22436 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22437 if (V.getNode()) return V;
22443 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
22444 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22445 // and friends. Likewise for OR -> CMPNEQSS.
22446 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22447 TargetLowering::DAGCombinerInfo &DCI,
22448 const X86Subtarget *Subtarget) {
22451 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22452 // we're requiring SSE2 for both.
22453 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22454 SDValue N0 = N->getOperand(0);
22455 SDValue N1 = N->getOperand(1);
22456 SDValue CMP0 = N0->getOperand(1);
22457 SDValue CMP1 = N1->getOperand(1);
22460 // The SETCCs should both refer to the same CMP.
22461 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22464 SDValue CMP00 = CMP0->getOperand(0);
22465 SDValue CMP01 = CMP0->getOperand(1);
22466 EVT VT = CMP00.getValueType();
22468 if (VT == MVT::f32 || VT == MVT::f64) {
22469 bool ExpectingFlags = false;
22470 // Check for any users that want flags:
22471 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22472 !ExpectingFlags && UI != UE; ++UI)
22473 switch (UI->getOpcode()) {
22478 ExpectingFlags = true;
22480 case ISD::CopyToReg:
22481 case ISD::SIGN_EXTEND:
22482 case ISD::ZERO_EXTEND:
22483 case ISD::ANY_EXTEND:
22487 if (!ExpectingFlags) {
22488 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22489 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22491 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22492 X86::CondCode tmp = cc0;
22497 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
22498 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22499 // FIXME: need symbolic constants for these magic numbers.
22500 // See X86ATTInstPrinter.cpp:printSSECC().
22501 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22502 if (Subtarget->hasAVX512()) {
22503 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22505 DAG.getConstant(x86cc, DL, MVT::i8));
22506 if (N->getValueType(0) != MVT::i1)
22507 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22511 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22512 CMP00.getValueType(), CMP00, CMP01,
22513 DAG.getConstant(x86cc, DL,
22516 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22517 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22519 if (is64BitFP && !Subtarget->is64Bit()) {
22520 // On a 32-bit target, we cannot bitcast the 64-bit float to a
22521 // 64-bit integer, since that's not a legal type. Since
22522 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22523 // bits, but can do this little dance to extract the lowest 32 bits
22524 // and work with those going forward.
22525 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22527 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22529 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22530 Vector32, DAG.getIntPtrConstant(0, DL));
22534 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22536 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22537 DAG.getConstant(1, DL, IntVT));
22538 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22540 return OneBitOfTruth;
22548 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22549 /// so it can be folded inside ANDNP.
22550 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22551 EVT VT = N->getValueType(0);
22553 // Match direct AllOnes for 128 and 256-bit vectors
22554 if (ISD::isBuildVectorAllOnes(N))
22557 // Look through a bit convert.
22558 if (N->getOpcode() == ISD::BITCAST)
22559 N = N->getOperand(0).getNode();
22561 // Sometimes the operand may come from a insert_subvector building a 256-bit
22563 if (VT.is256BitVector() &&
22564 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22565 SDValue V1 = N->getOperand(0);
22566 SDValue V2 = N->getOperand(1);
22568 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22569 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22570 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22571 ISD::isBuildVectorAllOnes(V2.getNode()))
22578 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22579 // register. In most cases we actually compare or select YMM-sized registers
22580 // and mixing the two types creates horrible code. This method optimizes
22581 // some of the transition sequences.
22582 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22583 TargetLowering::DAGCombinerInfo &DCI,
22584 const X86Subtarget *Subtarget) {
22585 EVT VT = N->getValueType(0);
22586 if (!VT.is256BitVector())
22589 assert((N->getOpcode() == ISD::ANY_EXTEND ||
22590 N->getOpcode() == ISD::ZERO_EXTEND ||
22591 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22593 SDValue Narrow = N->getOperand(0);
22594 EVT NarrowVT = Narrow->getValueType(0);
22595 if (!NarrowVT.is128BitVector())
22598 if (Narrow->getOpcode() != ISD::XOR &&
22599 Narrow->getOpcode() != ISD::AND &&
22600 Narrow->getOpcode() != ISD::OR)
22603 SDValue N0 = Narrow->getOperand(0);
22604 SDValue N1 = Narrow->getOperand(1);
22607 // The Left side has to be a trunc.
22608 if (N0.getOpcode() != ISD::TRUNCATE)
22611 // The type of the truncated inputs.
22612 EVT WideVT = N0->getOperand(0)->getValueType(0);
22616 // The right side has to be a 'trunc' or a constant vector.
22617 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22618 ConstantSDNode *RHSConstSplat = nullptr;
22619 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22620 RHSConstSplat = RHSBV->getConstantSplatNode();
22621 if (!RHSTrunc && !RHSConstSplat)
22624 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22626 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22629 // Set N0 and N1 to hold the inputs to the new wide operation.
22630 N0 = N0->getOperand(0);
22631 if (RHSConstSplat) {
22632 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22633 SDValue(RHSConstSplat, 0));
22634 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22635 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22636 } else if (RHSTrunc) {
22637 N1 = N1->getOperand(0);
22640 // Generate the wide operation.
22641 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22642 unsigned Opcode = N->getOpcode();
22644 case ISD::ANY_EXTEND:
22646 case ISD::ZERO_EXTEND: {
22647 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22648 APInt Mask = APInt::getAllOnesValue(InBits);
22649 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22650 return DAG.getNode(ISD::AND, DL, VT,
22651 Op, DAG.getConstant(Mask, DL, VT));
22653 case ISD::SIGN_EXTEND:
22654 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22655 Op, DAG.getValueType(NarrowVT));
22657 llvm_unreachable("Unexpected opcode");
22661 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22662 TargetLowering::DAGCombinerInfo &DCI,
22663 const X86Subtarget *Subtarget) {
22664 SDValue N0 = N->getOperand(0);
22665 SDValue N1 = N->getOperand(1);
22668 // A vector zext_in_reg may be represented as a shuffle,
22669 // feeding into a bitcast (this represents anyext) feeding into
22670 // an and with a mask.
22671 // We'd like to try to combine that into a shuffle with zero
22672 // plus a bitcast, removing the and.
22673 if (N0.getOpcode() != ISD::BITCAST ||
22674 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22677 // The other side of the AND should be a splat of 2^C, where C
22678 // is the number of bits in the source type.
22679 if (N1.getOpcode() == ISD::BITCAST)
22680 N1 = N1.getOperand(0);
22681 if (N1.getOpcode() != ISD::BUILD_VECTOR)
22683 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22685 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22686 EVT SrcType = Shuffle->getValueType(0);
22688 // We expect a single-source shuffle
22689 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22692 unsigned SrcSize = SrcType.getScalarSizeInBits();
22694 APInt SplatValue, SplatUndef;
22695 unsigned SplatBitSize;
22697 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22698 SplatBitSize, HasAnyUndefs))
22701 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22702 // Make sure the splat matches the mask we expect
22703 if (SplatBitSize > ResSize ||
22704 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22707 // Make sure the input and output size make sense
22708 if (SrcSize >= ResSize || ResSize % SrcSize)
22711 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22712 // The number of u's between each two values depends on the ratio between
22713 // the source and dest type.
22714 unsigned ZextRatio = ResSize / SrcSize;
22715 bool IsZext = true;
22716 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22717 if (i % ZextRatio) {
22718 if (Shuffle->getMaskElt(i) > 0) {
22724 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22725 // Expected element number
22735 // Ok, perform the transformation - replace the shuffle with
22736 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22737 // (instead of undef) where the k elements come from the zero vector.
22738 SmallVector<int, 8> Mask;
22739 unsigned NumElems = SrcType.getVectorNumElements();
22740 for (unsigned i = 0; i < NumElems; ++i)
22742 Mask.push_back(NumElems);
22744 Mask.push_back(i / ZextRatio);
22746 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22747 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22748 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22751 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22752 TargetLowering::DAGCombinerInfo &DCI,
22753 const X86Subtarget *Subtarget) {
22754 if (DCI.isBeforeLegalizeOps())
22757 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22760 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22763 EVT VT = N->getValueType(0);
22764 SDValue N0 = N->getOperand(0);
22765 SDValue N1 = N->getOperand(1);
22768 // Create BEXTR instructions
22769 // BEXTR is ((X >> imm) & (2**size-1))
22770 if (VT == MVT::i32 || VT == MVT::i64) {
22771 // Check for BEXTR.
22772 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22773 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22774 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22775 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22776 if (MaskNode && ShiftNode) {
22777 uint64_t Mask = MaskNode->getZExtValue();
22778 uint64_t Shift = ShiftNode->getZExtValue();
22779 if (isMask_64(Mask)) {
22780 uint64_t MaskSize = countPopulation(Mask);
22781 if (Shift + MaskSize <= VT.getSizeInBits())
22782 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22783 DAG.getConstant(Shift | (MaskSize << 8), DL,
22792 // Want to form ANDNP nodes:
22793 // 1) In the hopes of then easily combining them with OR and AND nodes
22794 // to form PBLEND/PSIGN.
22795 // 2) To match ANDN packed intrinsics
22796 if (VT != MVT::v2i64 && VT != MVT::v4i64)
22799 // Check LHS for vnot
22800 if (N0.getOpcode() == ISD::XOR &&
22801 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22802 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22803 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22805 // Check RHS for vnot
22806 if (N1.getOpcode() == ISD::XOR &&
22807 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22808 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22809 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22814 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22815 TargetLowering::DAGCombinerInfo &DCI,
22816 const X86Subtarget *Subtarget) {
22817 if (DCI.isBeforeLegalizeOps())
22820 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22824 SDValue N0 = N->getOperand(0);
22825 SDValue N1 = N->getOperand(1);
22826 EVT VT = N->getValueType(0);
22828 // look for psign/blend
22829 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22830 if (!Subtarget->hasSSSE3() ||
22831 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22834 // Canonicalize pandn to RHS
22835 if (N0.getOpcode() == X86ISD::ANDNP)
22837 // or (and (m, y), (pandn m, x))
22838 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22839 SDValue Mask = N1.getOperand(0);
22840 SDValue X = N1.getOperand(1);
22842 if (N0.getOperand(0) == Mask)
22843 Y = N0.getOperand(1);
22844 if (N0.getOperand(1) == Mask)
22845 Y = N0.getOperand(0);
22847 // Check to see if the mask appeared in both the AND and ANDNP and
22851 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22852 // Look through mask bitcast.
22853 if (Mask.getOpcode() == ISD::BITCAST)
22854 Mask = Mask.getOperand(0);
22855 if (X.getOpcode() == ISD::BITCAST)
22856 X = X.getOperand(0);
22857 if (Y.getOpcode() == ISD::BITCAST)
22858 Y = Y.getOperand(0);
22860 EVT MaskVT = Mask.getValueType();
22862 // Validate that the Mask operand is a vector sra node.
22863 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22864 // there is no psrai.b
22865 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22866 unsigned SraAmt = ~0;
22867 if (Mask.getOpcode() == ISD::SRA) {
22868 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22869 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22870 SraAmt = AmtConst->getZExtValue();
22871 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22872 SDValue SraC = Mask.getOperand(1);
22873 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22875 if ((SraAmt + 1) != EltBits)
22880 // Now we know we at least have a plendvb with the mask val. See if
22881 // we can form a psignb/w/d.
22882 // psign = x.type == y.type == mask.type && y = sub(0, x);
22883 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22884 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22885 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22886 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22887 "Unsupported VT for PSIGN");
22888 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22889 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22891 // PBLENDVB only available on SSE 4.1
22892 if (!Subtarget->hasSSE41())
22895 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22897 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22898 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22899 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22900 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22901 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22905 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22908 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22909 MachineFunction &MF = DAG.getMachineFunction();
22911 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22913 // SHLD/SHRD instructions have lower register pressure, but on some
22914 // platforms they have higher latency than the equivalent
22915 // series of shifts/or that would otherwise be generated.
22916 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22917 // have higher latencies and we are not optimizing for size.
22918 if (!OptForSize && Subtarget->isSHLDSlow())
22921 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22923 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22925 if (!N0.hasOneUse() || !N1.hasOneUse())
22928 SDValue ShAmt0 = N0.getOperand(1);
22929 if (ShAmt0.getValueType() != MVT::i8)
22931 SDValue ShAmt1 = N1.getOperand(1);
22932 if (ShAmt1.getValueType() != MVT::i8)
22934 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22935 ShAmt0 = ShAmt0.getOperand(0);
22936 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22937 ShAmt1 = ShAmt1.getOperand(0);
22940 unsigned Opc = X86ISD::SHLD;
22941 SDValue Op0 = N0.getOperand(0);
22942 SDValue Op1 = N1.getOperand(0);
22943 if (ShAmt0.getOpcode() == ISD::SUB) {
22944 Opc = X86ISD::SHRD;
22945 std::swap(Op0, Op1);
22946 std::swap(ShAmt0, ShAmt1);
22949 unsigned Bits = VT.getSizeInBits();
22950 if (ShAmt1.getOpcode() == ISD::SUB) {
22951 SDValue Sum = ShAmt1.getOperand(0);
22952 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22953 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22954 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22955 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22956 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22957 return DAG.getNode(Opc, DL, VT,
22959 DAG.getNode(ISD::TRUNCATE, DL,
22962 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22963 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22965 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22966 return DAG.getNode(Opc, DL, VT,
22967 N0.getOperand(0), N1.getOperand(0),
22968 DAG.getNode(ISD::TRUNCATE, DL,
22975 // Generate NEG and CMOV for integer abs.
22976 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22977 EVT VT = N->getValueType(0);
22979 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22980 // 8-bit integer abs to NEG and CMOV.
22981 if (VT.isInteger() && VT.getSizeInBits() == 8)
22984 SDValue N0 = N->getOperand(0);
22985 SDValue N1 = N->getOperand(1);
22988 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22989 // and change it to SUB and CMOV.
22990 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22991 N0.getOpcode() == ISD::ADD &&
22992 N0.getOperand(1) == N1 &&
22993 N1.getOpcode() == ISD::SRA &&
22994 N1.getOperand(0) == N0.getOperand(0))
22995 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22996 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22997 // Generate SUB & CMOV.
22998 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22999 DAG.getConstant(0, DL, VT), N0.getOperand(0));
23001 SDValue Ops[] = { N0.getOperand(0), Neg,
23002 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23003 SDValue(Neg.getNode(), 1) };
23004 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23009 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23010 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23011 TargetLowering::DAGCombinerInfo &DCI,
23012 const X86Subtarget *Subtarget) {
23013 if (DCI.isBeforeLegalizeOps())
23016 if (Subtarget->hasCMov()) {
23017 SDValue RV = performIntegerAbsCombine(N, DAG);
23025 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23026 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23027 TargetLowering::DAGCombinerInfo &DCI,
23028 const X86Subtarget *Subtarget) {
23029 LoadSDNode *Ld = cast<LoadSDNode>(N);
23030 EVT RegVT = Ld->getValueType(0);
23031 EVT MemVT = Ld->getMemoryVT();
23033 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23035 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23036 // into two 16-byte operations.
23037 ISD::LoadExtType Ext = Ld->getExtensionType();
23038 unsigned Alignment = Ld->getAlignment();
23039 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23040 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23041 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23042 unsigned NumElems = RegVT.getVectorNumElements();
23046 SDValue Ptr = Ld->getBasePtr();
23047 SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23049 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23051 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23052 Ld->getPointerInfo(), Ld->isVolatile(),
23053 Ld->isNonTemporal(), Ld->isInvariant(),
23055 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23056 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23057 Ld->getPointerInfo(), Ld->isVolatile(),
23058 Ld->isNonTemporal(), Ld->isInvariant(),
23059 std::min(16U, Alignment));
23060 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23062 Load2.getValue(1));
23064 SDValue NewVec = DAG.getUNDEF(RegVT);
23065 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23066 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23067 return DCI.CombineTo(N, NewVec, TF, true);
23073 /// PerformMLOADCombine - Resolve extending loads
23074 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23075 TargetLowering::DAGCombinerInfo &DCI,
23076 const X86Subtarget *Subtarget) {
23077 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23078 if (Mld->getExtensionType() != ISD::SEXTLOAD)
23081 EVT VT = Mld->getValueType(0);
23082 unsigned NumElems = VT.getVectorNumElements();
23083 EVT LdVT = Mld->getMemoryVT();
23086 assert(LdVT != VT && "Cannot extend to the same type");
23087 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23088 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23089 // From, To sizes and ElemCount must be pow of two
23090 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23091 "Unexpected size for extending masked load");
23093 unsigned SizeRatio = ToSz / FromSz;
23094 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23096 // Create a type on which we perform the shuffle
23097 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23098 LdVT.getScalarType(), NumElems*SizeRatio);
23099 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23101 // Convert Src0 value
23102 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
23103 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23104 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23105 for (unsigned i = 0; i != NumElems; ++i)
23106 ShuffleVec[i] = i * SizeRatio;
23108 // Can't shuffle using an illegal type.
23109 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23110 && "WideVecVT should be legal");
23111 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23112 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23114 // Prepare the new mask
23116 SDValue Mask = Mld->getMask();
23117 if (Mask.getValueType() == VT) {
23118 // Mask and original value have the same type
23119 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23120 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23121 for (unsigned i = 0; i != NumElems; ++i)
23122 ShuffleVec[i] = i * SizeRatio;
23123 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23124 ShuffleVec[i] = NumElems*SizeRatio;
23125 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23126 DAG.getConstant(0, dl, WideVecVT),
23130 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23131 unsigned WidenNumElts = NumElems*SizeRatio;
23132 unsigned MaskNumElts = VT.getVectorNumElements();
23133 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23136 unsigned NumConcat = WidenNumElts / MaskNumElts;
23137 SmallVector<SDValue, 16> Ops(NumConcat);
23138 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23140 for (unsigned i = 1; i != NumConcat; ++i)
23143 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23146 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23147 Mld->getBasePtr(), NewMask, WideSrc0,
23148 Mld->getMemoryVT(), Mld->getMemOperand(),
23150 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23151 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23154 /// PerformMSTORECombine - Resolve truncating stores
23155 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23156 const X86Subtarget *Subtarget) {
23157 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23158 if (!Mst->isTruncatingStore())
23161 EVT VT = Mst->getValue().getValueType();
23162 unsigned NumElems = VT.getVectorNumElements();
23163 EVT StVT = Mst->getMemoryVT();
23166 assert(StVT != VT && "Cannot truncate to the same type");
23167 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23168 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23170 // From, To sizes and ElemCount must be pow of two
23171 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23172 "Unexpected size for truncating masked store");
23173 // We are going to use the original vector elt for storing.
23174 // Accumulated smaller vector elements must be a multiple of the store size.
23175 assert (((NumElems * FromSz) % ToSz) == 0 &&
23176 "Unexpected ratio for truncating masked store");
23178 unsigned SizeRatio = FromSz / ToSz;
23179 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23181 // Create a type on which we perform the shuffle
23182 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23183 StVT.getScalarType(), NumElems*SizeRatio);
23185 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23187 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23188 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23189 for (unsigned i = 0; i != NumElems; ++i)
23190 ShuffleVec[i] = i * SizeRatio;
23192 // Can't shuffle using an illegal type.
23193 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23194 && "WideVecVT should be legal");
23196 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23197 DAG.getUNDEF(WideVecVT),
23201 SDValue Mask = Mst->getMask();
23202 if (Mask.getValueType() == VT) {
23203 // Mask and original value have the same type
23204 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23205 for (unsigned i = 0; i != NumElems; ++i)
23206 ShuffleVec[i] = i * SizeRatio;
23207 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23208 ShuffleVec[i] = NumElems*SizeRatio;
23209 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23210 DAG.getConstant(0, dl, WideVecVT),
23214 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23215 unsigned WidenNumElts = NumElems*SizeRatio;
23216 unsigned MaskNumElts = VT.getVectorNumElements();
23217 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23220 unsigned NumConcat = WidenNumElts / MaskNumElts;
23221 SmallVector<SDValue, 16> Ops(NumConcat);
23222 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23224 for (unsigned i = 1; i != NumConcat; ++i)
23227 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23230 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23231 NewMask, StVT, Mst->getMemOperand(), false);
23233 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23234 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23235 const X86Subtarget *Subtarget) {
23236 StoreSDNode *St = cast<StoreSDNode>(N);
23237 EVT VT = St->getValue().getValueType();
23238 EVT StVT = St->getMemoryVT();
23240 SDValue StoredVal = St->getOperand(1);
23241 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23243 // If we are saving a concatenation of two XMM registers and 32-byte stores
23244 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23245 unsigned Alignment = St->getAlignment();
23246 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23247 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23248 StVT == VT && !IsAligned) {
23249 unsigned NumElems = VT.getVectorNumElements();
23253 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23254 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23256 SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23257 SDValue Ptr0 = St->getBasePtr();
23258 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23260 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23261 St->getPointerInfo(), St->isVolatile(),
23262 St->isNonTemporal(), Alignment);
23263 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23264 St->getPointerInfo(), St->isVolatile(),
23265 St->isNonTemporal(),
23266 std::min(16U, Alignment));
23267 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23270 // Optimize trunc store (of multiple scalars) to shuffle and store.
23271 // First, pack all of the elements in one place. Next, store to memory
23272 // in fewer chunks.
23273 if (St->isTruncatingStore() && VT.isVector()) {
23274 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23275 unsigned NumElems = VT.getVectorNumElements();
23276 assert(StVT != VT && "Cannot truncate to the same type");
23277 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23278 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23280 // From, To sizes and ElemCount must be pow of two
23281 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23282 // We are going to use the original vector elt for storing.
23283 // Accumulated smaller vector elements must be a multiple of the store size.
23284 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23286 unsigned SizeRatio = FromSz / ToSz;
23288 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23290 // Create a type on which we perform the shuffle
23291 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23292 StVT.getScalarType(), NumElems*SizeRatio);
23294 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23296 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23297 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23298 for (unsigned i = 0; i != NumElems; ++i)
23299 ShuffleVec[i] = i * SizeRatio;
23301 // Can't shuffle using an illegal type.
23302 if (!TLI.isTypeLegal(WideVecVT))
23305 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23306 DAG.getUNDEF(WideVecVT),
23308 // At this point all of the data is stored at the bottom of the
23309 // register. We now need to save it to mem.
23311 // Find the largest store unit
23312 MVT StoreType = MVT::i8;
23313 for (MVT Tp : MVT::integer_valuetypes()) {
23314 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23318 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23319 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23320 (64 <= NumElems * ToSz))
23321 StoreType = MVT::f64;
23323 // Bitcast the original vector into a vector of store-size units
23324 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23325 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23326 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23327 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23328 SmallVector<SDValue, 8> Chains;
23329 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23330 TLI.getPointerTy());
23331 SDValue Ptr = St->getBasePtr();
23333 // Perform one or more big stores into memory.
23334 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23335 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23336 StoreType, ShuffWide,
23337 DAG.getIntPtrConstant(i, dl));
23338 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23339 St->getPointerInfo(), St->isVolatile(),
23340 St->isNonTemporal(), St->getAlignment());
23341 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23342 Chains.push_back(Ch);
23345 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23348 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
23349 // the FP state in cases where an emms may be missing.
23350 // A preferable solution to the general problem is to figure out the right
23351 // places to insert EMMS. This qualifies as a quick hack.
23353 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23354 if (VT.getSizeInBits() != 64)
23357 const Function *F = DAG.getMachineFunction().getFunction();
23358 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23360 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23361 if ((VT.isVector() ||
23362 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23363 isa<LoadSDNode>(St->getValue()) &&
23364 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23365 St->getChain().hasOneUse() && !St->isVolatile()) {
23366 SDNode* LdVal = St->getValue().getNode();
23367 LoadSDNode *Ld = nullptr;
23368 int TokenFactorIndex = -1;
23369 SmallVector<SDValue, 8> Ops;
23370 SDNode* ChainVal = St->getChain().getNode();
23371 // Must be a store of a load. We currently handle two cases: the load
23372 // is a direct child, and it's under an intervening TokenFactor. It is
23373 // possible to dig deeper under nested TokenFactors.
23374 if (ChainVal == LdVal)
23375 Ld = cast<LoadSDNode>(St->getChain());
23376 else if (St->getValue().hasOneUse() &&
23377 ChainVal->getOpcode() == ISD::TokenFactor) {
23378 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23379 if (ChainVal->getOperand(i).getNode() == LdVal) {
23380 TokenFactorIndex = i;
23381 Ld = cast<LoadSDNode>(St->getValue());
23383 Ops.push_back(ChainVal->getOperand(i));
23387 if (!Ld || !ISD::isNormalLoad(Ld))
23390 // If this is not the MMX case, i.e. we are just turning i64 load/store
23391 // into f64 load/store, avoid the transformation if there are multiple
23392 // uses of the loaded value.
23393 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23398 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23399 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23401 if (Subtarget->is64Bit() || F64IsLegal) {
23402 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23403 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23404 Ld->getPointerInfo(), Ld->isVolatile(),
23405 Ld->isNonTemporal(), Ld->isInvariant(),
23406 Ld->getAlignment());
23407 SDValue NewChain = NewLd.getValue(1);
23408 if (TokenFactorIndex != -1) {
23409 Ops.push_back(NewChain);
23410 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23412 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23413 St->getPointerInfo(),
23414 St->isVolatile(), St->isNonTemporal(),
23415 St->getAlignment());
23418 // Otherwise, lower to two pairs of 32-bit loads / stores.
23419 SDValue LoAddr = Ld->getBasePtr();
23420 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23421 DAG.getConstant(4, LdDL, MVT::i32));
23423 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23424 Ld->getPointerInfo(),
23425 Ld->isVolatile(), Ld->isNonTemporal(),
23426 Ld->isInvariant(), Ld->getAlignment());
23427 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23428 Ld->getPointerInfo().getWithOffset(4),
23429 Ld->isVolatile(), Ld->isNonTemporal(),
23431 MinAlign(Ld->getAlignment(), 4));
23433 SDValue NewChain = LoLd.getValue(1);
23434 if (TokenFactorIndex != -1) {
23435 Ops.push_back(LoLd);
23436 Ops.push_back(HiLd);
23437 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23440 LoAddr = St->getBasePtr();
23441 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23442 DAG.getConstant(4, StDL, MVT::i32));
23444 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23445 St->getPointerInfo(),
23446 St->isVolatile(), St->isNonTemporal(),
23447 St->getAlignment());
23448 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23449 St->getPointerInfo().getWithOffset(4),
23451 St->isNonTemporal(),
23452 MinAlign(St->getAlignment(), 4));
23453 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23456 // This is similar to the above case, but here we handle a scalar 64-bit
23457 // integer store that is extracted from a vector on a 32-bit target.
23458 // If we have SSE2, then we can treat it like a floating-point double
23459 // to get past legalization. The execution dependencies fixup pass will
23460 // choose the optimal machine instruction for the store if this really is
23461 // an integer or v2f32 rather than an f64.
23462 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23463 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23464 SDValue OldExtract = St->getOperand(1);
23465 SDValue ExtOp0 = OldExtract.getOperand(0);
23466 unsigned VecSize = ExtOp0.getValueSizeInBits();
23467 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23468 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23469 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23470 BitCast, OldExtract.getOperand(1));
23471 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23472 St->getPointerInfo(), St->isVolatile(),
23473 St->isNonTemporal(), St->getAlignment());
23479 /// Return 'true' if this vector operation is "horizontal"
23480 /// and return the operands for the horizontal operation in LHS and RHS. A
23481 /// horizontal operation performs the binary operation on successive elements
23482 /// of its first operand, then on successive elements of its second operand,
23483 /// returning the resulting values in a vector. For example, if
23484 /// A = < float a0, float a1, float a2, float a3 >
23486 /// B = < float b0, float b1, float b2, float b3 >
23487 /// then the result of doing a horizontal operation on A and B is
23488 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23489 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23490 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23491 /// set to A, RHS to B, and the routine returns 'true'.
23492 /// Note that the binary operation should have the property that if one of the
23493 /// operands is UNDEF then the result is UNDEF.
23494 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23495 // Look for the following pattern: if
23496 // A = < float a0, float a1, float a2, float a3 >
23497 // B = < float b0, float b1, float b2, float b3 >
23499 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23500 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23501 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23502 // which is A horizontal-op B.
23504 // At least one of the operands should be a vector shuffle.
23505 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23506 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23509 MVT VT = LHS.getSimpleValueType();
23511 assert((VT.is128BitVector() || VT.is256BitVector()) &&
23512 "Unsupported vector type for horizontal add/sub");
23514 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23515 // operate independently on 128-bit lanes.
23516 unsigned NumElts = VT.getVectorNumElements();
23517 unsigned NumLanes = VT.getSizeInBits()/128;
23518 unsigned NumLaneElts = NumElts / NumLanes;
23519 assert((NumLaneElts % 2 == 0) &&
23520 "Vector type should have an even number of elements in each lane");
23521 unsigned HalfLaneElts = NumLaneElts/2;
23523 // View LHS in the form
23524 // LHS = VECTOR_SHUFFLE A, B, LMask
23525 // If LHS is not a shuffle then pretend it is the shuffle
23526 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23527 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23530 SmallVector<int, 16> LMask(NumElts);
23531 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23532 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23533 A = LHS.getOperand(0);
23534 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23535 B = LHS.getOperand(1);
23536 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23537 std::copy(Mask.begin(), Mask.end(), LMask.begin());
23539 if (LHS.getOpcode() != ISD::UNDEF)
23541 for (unsigned i = 0; i != NumElts; ++i)
23545 // Likewise, view RHS in the form
23546 // RHS = VECTOR_SHUFFLE C, D, RMask
23548 SmallVector<int, 16> RMask(NumElts);
23549 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23550 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23551 C = RHS.getOperand(0);
23552 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23553 D = RHS.getOperand(1);
23554 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23555 std::copy(Mask.begin(), Mask.end(), RMask.begin());
23557 if (RHS.getOpcode() != ISD::UNDEF)
23559 for (unsigned i = 0; i != NumElts; ++i)
23563 // Check that the shuffles are both shuffling the same vectors.
23564 if (!(A == C && B == D) && !(A == D && B == C))
23567 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23568 if (!A.getNode() && !B.getNode())
23571 // If A and B occur in reverse order in RHS, then "swap" them (which means
23572 // rewriting the mask).
23574 ShuffleVectorSDNode::commuteMask(RMask);
23576 // At this point LHS and RHS are equivalent to
23577 // LHS = VECTOR_SHUFFLE A, B, LMask
23578 // RHS = VECTOR_SHUFFLE A, B, RMask
23579 // Check that the masks correspond to performing a horizontal operation.
23580 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23581 for (unsigned i = 0; i != NumLaneElts; ++i) {
23582 int LIdx = LMask[i+l], RIdx = RMask[i+l];
23584 // Ignore any UNDEF components.
23585 if (LIdx < 0 || RIdx < 0 ||
23586 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23587 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23590 // Check that successive elements are being operated on. If not, this is
23591 // not a horizontal operation.
23592 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23593 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23594 if (!(LIdx == Index && RIdx == Index + 1) &&
23595 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23600 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23601 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23605 /// Do target-specific dag combines on floating point adds.
23606 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23607 const X86Subtarget *Subtarget) {
23608 EVT VT = N->getValueType(0);
23609 SDValue LHS = N->getOperand(0);
23610 SDValue RHS = N->getOperand(1);
23612 // Try to synthesize horizontal adds from adds of shuffles.
23613 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23614 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23615 isHorizontalBinOp(LHS, RHS, true))
23616 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23620 /// Do target-specific dag combines on floating point subs.
23621 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23622 const X86Subtarget *Subtarget) {
23623 EVT VT = N->getValueType(0);
23624 SDValue LHS = N->getOperand(0);
23625 SDValue RHS = N->getOperand(1);
23627 // Try to synthesize horizontal subs from subs of shuffles.
23628 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23629 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23630 isHorizontalBinOp(LHS, RHS, false))
23631 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23635 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23636 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23637 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23639 // F[X]OR(0.0, x) -> x
23640 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23641 if (C->getValueAPF().isPosZero())
23642 return N->getOperand(1);
23644 // F[X]OR(x, 0.0) -> x
23645 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23646 if (C->getValueAPF().isPosZero())
23647 return N->getOperand(0);
23651 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23652 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23653 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23655 // Only perform optimizations if UnsafeMath is used.
23656 if (!DAG.getTarget().Options.UnsafeFPMath)
23659 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23660 // into FMINC and FMAXC, which are Commutative operations.
23661 unsigned NewOp = 0;
23662 switch (N->getOpcode()) {
23663 default: llvm_unreachable("unknown opcode");
23664 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
23665 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
23668 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23669 N->getOperand(0), N->getOperand(1));
23672 /// Do target-specific dag combines on X86ISD::FAND nodes.
23673 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23674 // FAND(0.0, x) -> 0.0
23675 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23676 if (C->getValueAPF().isPosZero())
23677 return N->getOperand(0);
23679 // FAND(x, 0.0) -> 0.0
23680 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23681 if (C->getValueAPF().isPosZero())
23682 return N->getOperand(1);
23687 /// Do target-specific dag combines on X86ISD::FANDN nodes
23688 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23689 // FANDN(0.0, x) -> x
23690 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23691 if (C->getValueAPF().isPosZero())
23692 return N->getOperand(1);
23694 // FANDN(x, 0.0) -> 0.0
23695 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23696 if (C->getValueAPF().isPosZero())
23697 return N->getOperand(1);
23702 static SDValue PerformBTCombine(SDNode *N,
23704 TargetLowering::DAGCombinerInfo &DCI) {
23705 // BT ignores high bits in the bit index operand.
23706 SDValue Op1 = N->getOperand(1);
23707 if (Op1.hasOneUse()) {
23708 unsigned BitWidth = Op1.getValueSizeInBits();
23709 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23710 APInt KnownZero, KnownOne;
23711 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23712 !DCI.isBeforeLegalizeOps());
23713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23714 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23715 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23716 DCI.CommitTargetLoweringOpt(TLO);
23721 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23722 SDValue Op = N->getOperand(0);
23723 if (Op.getOpcode() == ISD::BITCAST)
23724 Op = Op.getOperand(0);
23725 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23726 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23727 VT.getVectorElementType().getSizeInBits() ==
23728 OpVT.getVectorElementType().getSizeInBits()) {
23729 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23734 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23735 const X86Subtarget *Subtarget) {
23736 EVT VT = N->getValueType(0);
23737 if (!VT.isVector())
23740 SDValue N0 = N->getOperand(0);
23741 SDValue N1 = N->getOperand(1);
23742 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23745 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23746 // both SSE and AVX2 since there is no sign-extended shift right
23747 // operation on a vector with 64-bit elements.
23748 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23749 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23750 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23751 N0.getOpcode() == ISD::SIGN_EXTEND)) {
23752 SDValue N00 = N0.getOperand(0);
23754 // EXTLOAD has a better solution on AVX2,
23755 // it may be replaced with X86ISD::VSEXT node.
23756 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23757 if (!ISD::isNormalLoad(N00.getNode()))
23760 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23761 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23763 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23769 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23770 TargetLowering::DAGCombinerInfo &DCI,
23771 const X86Subtarget *Subtarget) {
23772 SDValue N0 = N->getOperand(0);
23773 EVT VT = N->getValueType(0);
23774 EVT SVT = VT.getScalarType();
23775 EVT InVT = N0->getValueType(0);
23776 EVT InSVT = InVT.getScalarType();
23779 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23780 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23781 // This exposes the sext to the sdivrem lowering, so that it directly extends
23782 // from AH (which we otherwise need to do contortions to access).
23783 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23784 InVT == MVT::i8 && VT == MVT::i32) {
23785 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23786 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
23787 N0.getOperand(0), N0.getOperand(1));
23788 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23789 return R.getValue(1);
23792 if (!DCI.isBeforeLegalizeOps()) {
23793 if (N0.getValueType() == MVT::i1) {
23794 SDValue Zero = DAG.getConstant(0, DL, VT);
23796 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
23797 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
23802 if (VT.isVector()) {
23803 auto ExtendToVec128 = [&DAG](SDLoc DL, SDValue N) {
23804 EVT InVT = N->getValueType(0);
23805 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
23806 128 / InVT.getScalarSizeInBits());
23807 SmallVector<SDValue, 8> Opnds(128 / InVT.getSizeInBits(),
23808 DAG.getUNDEF(InVT));
23810 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
23813 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
23814 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
23815 if (VT.getSizeInBits() == 128 &&
23816 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23817 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23818 SDValue ExOp = ExtendToVec128(DL, N0);
23819 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
23822 // On pre-AVX2 targets, split into 128-bit nodes of
23823 // ISD::SIGN_EXTEND_VECTOR_INREG.
23824 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
23825 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23826 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23827 unsigned NumVecs = VT.getSizeInBits() / 128;
23828 unsigned NumSubElts = 128 / SVT.getSizeInBits();
23829 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
23830 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
23832 SmallVector<SDValue, 8> Opnds;
23833 for (unsigned i = 0, Offset = 0; i != NumVecs;
23834 ++i, Offset += NumSubElts) {
23835 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
23836 DAG.getIntPtrConstant(Offset, DL));
23837 SrcVec = ExtendToVec128(DL, SrcVec);
23838 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
23839 Opnds.push_back(SrcVec);
23841 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
23845 if (!Subtarget->hasFp256())
23848 if (VT.isVector() && VT.getSizeInBits() == 256) {
23849 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23857 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23858 const X86Subtarget* Subtarget) {
23860 EVT VT = N->getValueType(0);
23862 // Let legalize expand this if it isn't a legal type yet.
23863 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23866 EVT ScalarVT = VT.getScalarType();
23867 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23868 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23871 SDValue A = N->getOperand(0);
23872 SDValue B = N->getOperand(1);
23873 SDValue C = N->getOperand(2);
23875 bool NegA = (A.getOpcode() == ISD::FNEG);
23876 bool NegB = (B.getOpcode() == ISD::FNEG);
23877 bool NegC = (C.getOpcode() == ISD::FNEG);
23879 // Negative multiplication when NegA xor NegB
23880 bool NegMul = (NegA != NegB);
23882 A = A.getOperand(0);
23884 B = B.getOperand(0);
23886 C = C.getOperand(0);
23890 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23892 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23894 return DAG.getNode(Opcode, dl, VT, A, B, C);
23897 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23898 TargetLowering::DAGCombinerInfo &DCI,
23899 const X86Subtarget *Subtarget) {
23900 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23901 // (and (i32 x86isd::setcc_carry), 1)
23902 // This eliminates the zext. This transformation is necessary because
23903 // ISD::SETCC is always legalized to i8.
23905 SDValue N0 = N->getOperand(0);
23906 EVT VT = N->getValueType(0);
23908 if (N0.getOpcode() == ISD::AND &&
23910 N0.getOperand(0).hasOneUse()) {
23911 SDValue N00 = N0.getOperand(0);
23912 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23913 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23914 if (!C || C->getZExtValue() != 1)
23916 return DAG.getNode(ISD::AND, dl, VT,
23917 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23918 N00.getOperand(0), N00.getOperand(1)),
23919 DAG.getConstant(1, dl, VT));
23923 if (N0.getOpcode() == ISD::TRUNCATE &&
23925 N0.getOperand(0).hasOneUse()) {
23926 SDValue N00 = N0.getOperand(0);
23927 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23928 return DAG.getNode(ISD::AND, dl, VT,
23929 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23930 N00.getOperand(0), N00.getOperand(1)),
23931 DAG.getConstant(1, dl, VT));
23934 if (VT.is256BitVector()) {
23935 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23940 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23941 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23942 // This exposes the zext to the udivrem lowering, so that it directly extends
23943 // from AH (which we otherwise need to do contortions to access).
23944 if (N0.getOpcode() == ISD::UDIVREM &&
23945 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23946 (VT == MVT::i32 || VT == MVT::i64)) {
23947 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23948 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23949 N0.getOperand(0), N0.getOperand(1));
23950 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23951 return R.getValue(1);
23957 // Optimize x == -y --> x+y == 0
23958 // x != -y --> x+y != 0
23959 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23960 const X86Subtarget* Subtarget) {
23961 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23962 SDValue LHS = N->getOperand(0);
23963 SDValue RHS = N->getOperand(1);
23964 EVT VT = N->getValueType(0);
23967 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23968 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23969 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23970 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23971 LHS.getOperand(1));
23972 return DAG.getSetCC(DL, N->getValueType(0), addV,
23973 DAG.getConstant(0, DL, addV.getValueType()), CC);
23975 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23976 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23977 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23978 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23979 RHS.getOperand(1));
23980 return DAG.getSetCC(DL, N->getValueType(0), addV,
23981 DAG.getConstant(0, DL, addV.getValueType()), CC);
23984 if (VT.getScalarType() == MVT::i1 &&
23985 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23987 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23988 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23989 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23991 if (!IsSEXT0 || !IsVZero1) {
23992 // Swap the operands and update the condition code.
23993 std::swap(LHS, RHS);
23994 CC = ISD::getSetCCSwappedOperands(CC);
23996 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23997 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23998 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24001 if (IsSEXT0 && IsVZero1) {
24002 assert(VT == LHS.getOperand(0).getValueType() &&
24003 "Uexpected operand type");
24004 if (CC == ISD::SETGT)
24005 return DAG.getConstant(0, DL, VT);
24006 if (CC == ISD::SETLE)
24007 return DAG.getConstant(1, DL, VT);
24008 if (CC == ISD::SETEQ || CC == ISD::SETGE)
24009 return DAG.getNOT(DL, LHS.getOperand(0), VT);
24011 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24012 "Unexpected condition code!");
24013 return LHS.getOperand(0);
24020 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24021 SelectionDAG &DAG) {
24023 MVT VT = Load->getSimpleValueType(0);
24024 MVT EVT = VT.getVectorElementType();
24025 SDValue Addr = Load->getOperand(1);
24026 SDValue NewAddr = DAG.getNode(
24027 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24028 DAG.getConstant(Index * EVT.getStoreSize(), dl,
24029 Addr.getSimpleValueType()));
24032 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24033 DAG.getMachineFunction().getMachineMemOperand(
24034 Load->getMemOperand(), 0, EVT.getStoreSize()));
24038 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24039 const X86Subtarget *Subtarget) {
24041 MVT VT = N->getOperand(1)->getSimpleValueType(0);
24042 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24043 "X86insertps is only defined for v4x32");
24045 SDValue Ld = N->getOperand(1);
24046 if (MayFoldLoad(Ld)) {
24047 // Extract the countS bits from the immediate so we can get the proper
24048 // address when narrowing the vector load to a specific element.
24049 // When the second source op is a memory address, insertps doesn't use
24050 // countS and just gets an f32 from that address.
24051 unsigned DestIndex =
24052 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24054 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24056 // Create this as a scalar to vector to match the instruction pattern.
24057 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24058 // countS bits are ignored when loading from memory on insertps, which
24059 // means we don't need to explicitly set them to 0.
24060 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24061 LoadScalarToVector, N->getOperand(2));
24066 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24067 SDValue V0 = N->getOperand(0);
24068 SDValue V1 = N->getOperand(1);
24070 EVT VT = N->getValueType(0);
24072 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24073 // operands and changing the mask to 1. This saves us a bunch of
24074 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24075 // x86InstrInfo knows how to commute this back after instruction selection
24076 // if it would help register allocation.
24078 // TODO: If optimizing for size or a processor that doesn't suffer from
24079 // partial register update stalls, this should be transformed into a MOVSD
24080 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24082 if (VT == MVT::v2f64)
24083 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24084 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24085 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24086 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24092 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24093 // as "sbb reg,reg", since it can be extended without zext and produces
24094 // an all-ones bit which is more useful than 0/1 in some cases.
24095 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24098 return DAG.getNode(ISD::AND, DL, VT,
24099 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24100 DAG.getConstant(X86::COND_B, DL, MVT::i8),
24102 DAG.getConstant(1, DL, VT));
24103 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24104 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24105 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24106 DAG.getConstant(X86::COND_B, DL, MVT::i8),
24110 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24111 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24112 TargetLowering::DAGCombinerInfo &DCI,
24113 const X86Subtarget *Subtarget) {
24115 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24116 SDValue EFLAGS = N->getOperand(1);
24118 if (CC == X86::COND_A) {
24119 // Try to convert COND_A into COND_B in an attempt to facilitate
24120 // materializing "setb reg".
24122 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24123 // cannot take an immediate as its first operand.
24125 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24126 EFLAGS.getValueType().isInteger() &&
24127 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24128 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24129 EFLAGS.getNode()->getVTList(),
24130 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24131 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24132 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24136 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24137 // a zext and produces an all-ones bit which is more useful than 0/1 in some
24139 if (CC == X86::COND_B)
24140 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24144 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24145 if (Flags.getNode()) {
24146 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24147 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24153 // Optimize branch condition evaluation.
24155 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24156 TargetLowering::DAGCombinerInfo &DCI,
24157 const X86Subtarget *Subtarget) {
24159 SDValue Chain = N->getOperand(0);
24160 SDValue Dest = N->getOperand(1);
24161 SDValue EFLAGS = N->getOperand(3);
24162 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24166 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24167 if (Flags.getNode()) {
24168 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24169 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24176 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24177 SelectionDAG &DAG) {
24178 // Take advantage of vector comparisons producing 0 or -1 in each lane to
24179 // optimize away operation when it's from a constant.
24181 // The general transformation is:
24182 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24183 // AND(VECTOR_CMP(x,y), constant2)
24184 // constant2 = UNARYOP(constant)
24186 // Early exit if this isn't a vector operation, the operand of the
24187 // unary operation isn't a bitwise AND, or if the sizes of the operations
24188 // aren't the same.
24189 EVT VT = N->getValueType(0);
24190 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24191 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24192 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24195 // Now check that the other operand of the AND is a constant. We could
24196 // make the transformation for non-constant splats as well, but it's unclear
24197 // that would be a benefit as it would not eliminate any operations, just
24198 // perform one more step in scalar code before moving to the vector unit.
24199 if (BuildVectorSDNode *BV =
24200 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24201 // Bail out if the vector isn't a constant.
24202 if (!BV->isConstant())
24205 // Everything checks out. Build up the new and improved node.
24207 EVT IntVT = BV->getValueType(0);
24208 // Create a new constant of the appropriate type for the transformed
24210 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24211 // The AND node needs bitcasts to/from an integer vector type around it.
24212 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24213 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24214 N->getOperand(0)->getOperand(0), MaskConst);
24215 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24222 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24223 const X86Subtarget *Subtarget) {
24224 // First try to optimize away the conversion entirely when it's
24225 // conditionally from a constant. Vectors only.
24226 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24227 if (Res != SDValue())
24230 // Now move on to more general possibilities.
24231 SDValue Op0 = N->getOperand(0);
24232 EVT InVT = Op0->getValueType(0);
24234 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24235 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24237 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24238 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24239 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24242 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24243 // a 32-bit target where SSE doesn't support i64->FP operations.
24244 if (Op0.getOpcode() == ISD::LOAD) {
24245 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24246 EVT VT = Ld->getValueType(0);
24248 // This transformation is not supported if the result type is f16
24249 if (N->getValueType(0) == MVT::f16)
24252 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24253 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24254 !Subtarget->is64Bit() && VT == MVT::i64) {
24255 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24256 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24257 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24264 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24265 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24266 X86TargetLowering::DAGCombinerInfo &DCI) {
24267 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24268 // the result is either zero or one (depending on the input carry bit).
24269 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24270 if (X86::isZeroNode(N->getOperand(0)) &&
24271 X86::isZeroNode(N->getOperand(1)) &&
24272 // We don't have a good way to replace an EFLAGS use, so only do this when
24274 SDValue(N, 1).use_empty()) {
24276 EVT VT = N->getValueType(0);
24277 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24278 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24279 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24280 DAG.getConstant(X86::COND_B, DL,
24283 DAG.getConstant(1, DL, VT));
24284 return DCI.CombineTo(N, Res1, CarryOut);
24290 // fold (add Y, (sete X, 0)) -> adc 0, Y
24291 // (add Y, (setne X, 0)) -> sbb -1, Y
24292 // (sub (sete X, 0), Y) -> sbb 0, Y
24293 // (sub (setne X, 0), Y) -> adc -1, Y
24294 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24297 // Look through ZExts.
24298 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24299 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24302 SDValue SetCC = Ext.getOperand(0);
24303 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24306 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24307 if (CC != X86::COND_E && CC != X86::COND_NE)
24310 SDValue Cmp = SetCC.getOperand(1);
24311 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24312 !X86::isZeroNode(Cmp.getOperand(1)) ||
24313 !Cmp.getOperand(0).getValueType().isInteger())
24316 SDValue CmpOp0 = Cmp.getOperand(0);
24317 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24318 DAG.getConstant(1, DL, CmpOp0.getValueType()));
24320 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24321 if (CC == X86::COND_NE)
24322 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24323 DL, OtherVal.getValueType(), OtherVal,
24324 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24326 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24327 DL, OtherVal.getValueType(), OtherVal,
24328 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24331 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24332 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24333 const X86Subtarget *Subtarget) {
24334 EVT VT = N->getValueType(0);
24335 SDValue Op0 = N->getOperand(0);
24336 SDValue Op1 = N->getOperand(1);
24338 // Try to synthesize horizontal adds from adds of shuffles.
24339 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24340 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24341 isHorizontalBinOp(Op0, Op1, true))
24342 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24344 return OptimizeConditionalInDecrement(N, DAG);
24347 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24348 const X86Subtarget *Subtarget) {
24349 SDValue Op0 = N->getOperand(0);
24350 SDValue Op1 = N->getOperand(1);
24352 // X86 can't encode an immediate LHS of a sub. See if we can push the
24353 // negation into a preceding instruction.
24354 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24355 // If the RHS of the sub is a XOR with one use and a constant, invert the
24356 // immediate. Then add one to the LHS of the sub so we can turn
24357 // X-Y -> X+~Y+1, saving one register.
24358 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24359 isa<ConstantSDNode>(Op1.getOperand(1))) {
24360 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24361 EVT VT = Op0.getValueType();
24362 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24364 DAG.getConstant(~XorC, SDLoc(Op1), VT));
24365 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24366 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24370 // Try to synthesize horizontal adds from adds of shuffles.
24371 EVT VT = N->getValueType(0);
24372 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24373 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24374 isHorizontalBinOp(Op0, Op1, true))
24375 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24377 return OptimizeConditionalInDecrement(N, DAG);
24380 /// performVZEXTCombine - Performs build vector combines
24381 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24382 TargetLowering::DAGCombinerInfo &DCI,
24383 const X86Subtarget *Subtarget) {
24385 MVT VT = N->getSimpleValueType(0);
24386 SDValue Op = N->getOperand(0);
24387 MVT OpVT = Op.getSimpleValueType();
24388 MVT OpEltVT = OpVT.getVectorElementType();
24389 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24391 // (vzext (bitcast (vzext (x)) -> (vzext x)
24393 while (V.getOpcode() == ISD::BITCAST)
24394 V = V.getOperand(0);
24396 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24397 MVT InnerVT = V.getSimpleValueType();
24398 MVT InnerEltVT = InnerVT.getVectorElementType();
24400 // If the element sizes match exactly, we can just do one larger vzext. This
24401 // is always an exact type match as vzext operates on integer types.
24402 if (OpEltVT == InnerEltVT) {
24403 assert(OpVT == InnerVT && "Types must match for vzext!");
24404 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24407 // The only other way we can combine them is if only a single element of the
24408 // inner vzext is used in the input to the outer vzext.
24409 if (InnerEltVT.getSizeInBits() < InputBits)
24412 // In this case, the inner vzext is completely dead because we're going to
24413 // only look at bits inside of the low element. Just do the outer vzext on
24414 // a bitcast of the input to the inner.
24415 return DAG.getNode(X86ISD::VZEXT, DL, VT,
24416 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24419 // Check if we can bypass extracting and re-inserting an element of an input
24420 // vector. Essentialy:
24421 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24422 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24423 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24424 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24425 SDValue ExtractedV = V.getOperand(0);
24426 SDValue OrigV = ExtractedV.getOperand(0);
24427 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24428 if (ExtractIdx->getZExtValue() == 0) {
24429 MVT OrigVT = OrigV.getSimpleValueType();
24430 // Extract a subvector if necessary...
24431 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24432 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24433 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24434 OrigVT.getVectorNumElements() / Ratio);
24435 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24436 DAG.getIntPtrConstant(0, DL));
24438 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24439 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24446 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24447 DAGCombinerInfo &DCI) const {
24448 SelectionDAG &DAG = DCI.DAG;
24449 switch (N->getOpcode()) {
24451 case ISD::EXTRACT_VECTOR_ELT:
24452 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24455 case X86ISD::SHRUNKBLEND:
24456 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24457 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
24458 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24459 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
24460 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
24461 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
24462 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
24465 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
24466 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
24467 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
24468 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
24469 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
24470 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24471 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
24472 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
24473 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24474 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
24475 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
24477 case X86ISD::FOR: return PerformFORCombine(N, DAG);
24479 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
24480 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
24481 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
24482 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
24483 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
24484 case ISD::ANY_EXTEND:
24485 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
24486 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
24487 case ISD::SIGN_EXTEND_INREG:
24488 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24489 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
24490 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24491 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24492 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
24493 case X86ISD::SHUFP: // Handle all target specific shuffles
24494 case X86ISD::PALIGNR:
24495 case X86ISD::UNPCKH:
24496 case X86ISD::UNPCKL:
24497 case X86ISD::MOVHLPS:
24498 case X86ISD::MOVLHPS:
24499 case X86ISD::PSHUFB:
24500 case X86ISD::PSHUFD:
24501 case X86ISD::PSHUFHW:
24502 case X86ISD::PSHUFLW:
24503 case X86ISD::MOVSS:
24504 case X86ISD::MOVSD:
24505 case X86ISD::VPERMILPI:
24506 case X86ISD::VPERM2X128:
24507 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24508 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
24509 case ISD::INTRINSIC_WO_CHAIN:
24510 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24511 case X86ISD::INSERTPS: {
24512 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24513 return PerformINSERTPSCombine(N, DAG, Subtarget);
24516 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
24522 /// isTypeDesirableForOp - Return true if the target has native support for
24523 /// the specified value type and it is 'desirable' to use the type for the
24524 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24525 /// instruction encodings are longer and some i16 instructions are slow.
24526 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24527 if (!isTypeLegal(VT))
24529 if (VT != MVT::i16)
24536 case ISD::SIGN_EXTEND:
24537 case ISD::ZERO_EXTEND:
24538 case ISD::ANY_EXTEND:
24551 /// IsDesirableToPromoteOp - This method query the target whether it is
24552 /// beneficial for dag combiner to promote the specified node. If true, it
24553 /// should return the desired promotion type by reference.
24554 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24555 EVT VT = Op.getValueType();
24556 if (VT != MVT::i16)
24559 bool Promote = false;
24560 bool Commute = false;
24561 switch (Op.getOpcode()) {
24564 LoadSDNode *LD = cast<LoadSDNode>(Op);
24565 // If the non-extending load has a single use and it's not live out, then it
24566 // might be folded.
24567 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24568 Op.hasOneUse()*/) {
24569 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24570 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24571 // The only case where we'd want to promote LOAD (rather then it being
24572 // promoted as an operand is when it's only use is liveout.
24573 if (UI->getOpcode() != ISD::CopyToReg)
24580 case ISD::SIGN_EXTEND:
24581 case ISD::ZERO_EXTEND:
24582 case ISD::ANY_EXTEND:
24587 SDValue N0 = Op.getOperand(0);
24588 // Look out for (store (shl (load), x)).
24589 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24602 SDValue N0 = Op.getOperand(0);
24603 SDValue N1 = Op.getOperand(1);
24604 if (!Commute && MayFoldLoad(N1))
24606 // Avoid disabling potential load folding opportunities.
24607 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24609 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24619 //===----------------------------------------------------------------------===//
24620 // X86 Inline Assembly Support
24621 //===----------------------------------------------------------------------===//
24623 // Helper to match a string separated by whitespace.
24624 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24625 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24627 for (StringRef Piece : Pieces) {
24628 if (!S.startswith(Piece)) // Check if the piece matches.
24631 S = S.substr(Piece.size());
24632 StringRef::size_type Pos = S.find_first_not_of(" \t");
24633 if (Pos == 0) // We matched a prefix.
24642 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24644 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24645 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24646 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24647 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24649 if (AsmPieces.size() == 3)
24651 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24658 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24659 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24661 std::string AsmStr = IA->getAsmString();
24663 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24664 if (!Ty || Ty->getBitWidth() % 16 != 0)
24667 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24668 SmallVector<StringRef, 4> AsmPieces;
24669 SplitString(AsmStr, AsmPieces, ";\n");
24671 switch (AsmPieces.size()) {
24672 default: return false;
24674 // FIXME: this should verify that we are targeting a 486 or better. If not,
24675 // we will turn this bswap into something that will be lowered to logical
24676 // ops instead of emitting the bswap asm. For now, we don't support 486 or
24677 // lower so don't worry about this.
24679 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24680 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24681 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24682 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24683 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24684 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24685 // No need to check constraints, nothing other than the equivalent of
24686 // "=r,0" would be valid here.
24687 return IntrinsicLowering::LowerToByteSwap(CI);
24690 // rorw $$8, ${0:w} --> llvm.bswap.i16
24691 if (CI->getType()->isIntegerTy(16) &&
24692 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24693 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24694 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24696 const std::string &ConstraintsStr = IA->getConstraintString();
24697 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24698 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24699 if (clobbersFlagRegisters(AsmPieces))
24700 return IntrinsicLowering::LowerToByteSwap(CI);
24704 if (CI->getType()->isIntegerTy(32) &&
24705 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24706 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24707 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24708 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24710 const std::string &ConstraintsStr = IA->getConstraintString();
24711 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24712 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24713 if (clobbersFlagRegisters(AsmPieces))
24714 return IntrinsicLowering::LowerToByteSwap(CI);
24717 if (CI->getType()->isIntegerTy(64)) {
24718 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24719 if (Constraints.size() >= 2 &&
24720 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24721 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24722 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
24723 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24724 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24725 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24726 return IntrinsicLowering::LowerToByteSwap(CI);
24734 /// getConstraintType - Given a constraint letter, return the type of
24735 /// constraint it is for this target.
24736 X86TargetLowering::ConstraintType
24737 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24738 if (Constraint.size() == 1) {
24739 switch (Constraint[0]) {
24750 return C_RegisterClass;
24774 return TargetLowering::getConstraintType(Constraint);
24777 /// Examine constraint type and operand type and determine a weight value.
24778 /// This object must already have been set up with the operand type
24779 /// and the current alternative constraint selected.
24780 TargetLowering::ConstraintWeight
24781 X86TargetLowering::getSingleConstraintMatchWeight(
24782 AsmOperandInfo &info, const char *constraint) const {
24783 ConstraintWeight weight = CW_Invalid;
24784 Value *CallOperandVal = info.CallOperandVal;
24785 // If we don't have a value, we can't do a match,
24786 // but allow it at the lowest weight.
24787 if (!CallOperandVal)
24789 Type *type = CallOperandVal->getType();
24790 // Look at the constraint type.
24791 switch (*constraint) {
24793 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24804 if (CallOperandVal->getType()->isIntegerTy())
24805 weight = CW_SpecificReg;
24810 if (type->isFloatingPointTy())
24811 weight = CW_SpecificReg;
24814 if (type->isX86_MMXTy() && Subtarget->hasMMX())
24815 weight = CW_SpecificReg;
24819 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24820 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24821 weight = CW_Register;
24824 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24825 if (C->getZExtValue() <= 31)
24826 weight = CW_Constant;
24830 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24831 if (C->getZExtValue() <= 63)
24832 weight = CW_Constant;
24836 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24837 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24838 weight = CW_Constant;
24842 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24843 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24844 weight = CW_Constant;
24848 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24849 if (C->getZExtValue() <= 3)
24850 weight = CW_Constant;
24854 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24855 if (C->getZExtValue() <= 0xff)
24856 weight = CW_Constant;
24861 if (isa<ConstantFP>(CallOperandVal)) {
24862 weight = CW_Constant;
24866 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24867 if ((C->getSExtValue() >= -0x80000000LL) &&
24868 (C->getSExtValue() <= 0x7fffffffLL))
24869 weight = CW_Constant;
24873 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24874 if (C->getZExtValue() <= 0xffffffff)
24875 weight = CW_Constant;
24882 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24883 /// with another that has more specific requirements based on the type of the
24884 /// corresponding operand.
24885 const char *X86TargetLowering::
24886 LowerXConstraint(EVT ConstraintVT) const {
24887 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24888 // 'f' like normal targets.
24889 if (ConstraintVT.isFloatingPoint()) {
24890 if (Subtarget->hasSSE2())
24892 if (Subtarget->hasSSE1())
24896 return TargetLowering::LowerXConstraint(ConstraintVT);
24899 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24900 /// vector. If it is invalid, don't add anything to Ops.
24901 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24902 std::string &Constraint,
24903 std::vector<SDValue>&Ops,
24904 SelectionDAG &DAG) const {
24907 // Only support length 1 constraints for now.
24908 if (Constraint.length() > 1) return;
24910 char ConstraintLetter = Constraint[0];
24911 switch (ConstraintLetter) {
24914 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24915 if (C->getZExtValue() <= 31) {
24916 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24917 Op.getValueType());
24923 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24924 if (C->getZExtValue() <= 63) {
24925 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24926 Op.getValueType());
24932 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24933 if (isInt<8>(C->getSExtValue())) {
24934 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24935 Op.getValueType());
24941 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24942 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24943 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24944 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24945 Op.getValueType());
24951 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24952 if (C->getZExtValue() <= 3) {
24953 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24954 Op.getValueType());
24960 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24961 if (C->getZExtValue() <= 255) {
24962 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24963 Op.getValueType());
24969 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24970 if (C->getZExtValue() <= 127) {
24971 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24972 Op.getValueType());
24978 // 32-bit signed value
24979 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24980 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24981 C->getSExtValue())) {
24982 // Widen to 64 bits here to get it sign extended.
24983 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24986 // FIXME gcc accepts some relocatable values here too, but only in certain
24987 // memory models; it's complicated.
24992 // 32-bit unsigned value
24993 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24994 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24995 C->getZExtValue())) {
24996 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24997 Op.getValueType());
25001 // FIXME gcc accepts some relocatable values here too, but only in certain
25002 // memory models; it's complicated.
25006 // Literal immediates are always ok.
25007 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25008 // Widen to 64 bits here to get it sign extended.
25009 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25013 // In any sort of PIC mode addresses need to be computed at runtime by
25014 // adding in a register or some sort of table lookup. These can't
25015 // be used as immediates.
25016 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25019 // If we are in non-pic codegen mode, we allow the address of a global (with
25020 // an optional displacement) to be used with 'i'.
25021 GlobalAddressSDNode *GA = nullptr;
25022 int64_t Offset = 0;
25024 // Match either (GA), (GA+C), (GA+C1+C2), etc.
25026 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25027 Offset += GA->getOffset();
25029 } else if (Op.getOpcode() == ISD::ADD) {
25030 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25031 Offset += C->getZExtValue();
25032 Op = Op.getOperand(0);
25035 } else if (Op.getOpcode() == ISD::SUB) {
25036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25037 Offset += -C->getZExtValue();
25038 Op = Op.getOperand(0);
25043 // Otherwise, this isn't something we can handle, reject it.
25047 const GlobalValue *GV = GA->getGlobal();
25048 // If we require an extra load to get this address, as in PIC mode, we
25049 // can't accept it.
25050 if (isGlobalStubReference(
25051 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25054 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25055 GA->getValueType(0), Offset);
25060 if (Result.getNode()) {
25061 Ops.push_back(Result);
25064 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25067 std::pair<unsigned, const TargetRegisterClass *>
25068 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25069 const std::string &Constraint,
25071 // First, see if this is a constraint that directly corresponds to an LLVM
25073 if (Constraint.size() == 1) {
25074 // GCC Constraint Letters
25075 switch (Constraint[0]) {
25077 // TODO: Slight differences here in allocation order and leaving
25078 // RIP in the class. Do they matter any more here than they do
25079 // in the normal allocation?
25080 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25081 if (Subtarget->is64Bit()) {
25082 if (VT == MVT::i32 || VT == MVT::f32)
25083 return std::make_pair(0U, &X86::GR32RegClass);
25084 if (VT == MVT::i16)
25085 return std::make_pair(0U, &X86::GR16RegClass);
25086 if (VT == MVT::i8 || VT == MVT::i1)
25087 return std::make_pair(0U, &X86::GR8RegClass);
25088 if (VT == MVT::i64 || VT == MVT::f64)
25089 return std::make_pair(0U, &X86::GR64RegClass);
25092 // 32-bit fallthrough
25093 case 'Q': // Q_REGS
25094 if (VT == MVT::i32 || VT == MVT::f32)
25095 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25096 if (VT == MVT::i16)
25097 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25098 if (VT == MVT::i8 || VT == MVT::i1)
25099 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25100 if (VT == MVT::i64)
25101 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25103 case 'r': // GENERAL_REGS
25104 case 'l': // INDEX_REGS
25105 if (VT == MVT::i8 || VT == MVT::i1)
25106 return std::make_pair(0U, &X86::GR8RegClass);
25107 if (VT == MVT::i16)
25108 return std::make_pair(0U, &X86::GR16RegClass);
25109 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25110 return std::make_pair(0U, &X86::GR32RegClass);
25111 return std::make_pair(0U, &X86::GR64RegClass);
25112 case 'R': // LEGACY_REGS
25113 if (VT == MVT::i8 || VT == MVT::i1)
25114 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25115 if (VT == MVT::i16)
25116 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25117 if (VT == MVT::i32 || !Subtarget->is64Bit())
25118 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25119 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25120 case 'f': // FP Stack registers.
25121 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25122 // value to the correct fpstack register class.
25123 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25124 return std::make_pair(0U, &X86::RFP32RegClass);
25125 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25126 return std::make_pair(0U, &X86::RFP64RegClass);
25127 return std::make_pair(0U, &X86::RFP80RegClass);
25128 case 'y': // MMX_REGS if MMX allowed.
25129 if (!Subtarget->hasMMX()) break;
25130 return std::make_pair(0U, &X86::VR64RegClass);
25131 case 'Y': // SSE_REGS if SSE2 allowed
25132 if (!Subtarget->hasSSE2()) break;
25134 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25135 if (!Subtarget->hasSSE1()) break;
25137 switch (VT.SimpleTy) {
25139 // Scalar SSE types.
25142 return std::make_pair(0U, &X86::FR32RegClass);
25145 return std::make_pair(0U, &X86::FR64RegClass);
25153 return std::make_pair(0U, &X86::VR128RegClass);
25161 return std::make_pair(0U, &X86::VR256RegClass);
25166 return std::make_pair(0U, &X86::VR512RegClass);
25172 // Use the default implementation in TargetLowering to convert the register
25173 // constraint into a member of a register class.
25174 std::pair<unsigned, const TargetRegisterClass*> Res;
25175 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25177 // Not found as a standard register?
25179 // Map st(0) -> st(7) -> ST0
25180 if (Constraint.size() == 7 && Constraint[0] == '{' &&
25181 tolower(Constraint[1]) == 's' &&
25182 tolower(Constraint[2]) == 't' &&
25183 Constraint[3] == '(' &&
25184 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25185 Constraint[5] == ')' &&
25186 Constraint[6] == '}') {
25188 Res.first = X86::FP0+Constraint[4]-'0';
25189 Res.second = &X86::RFP80RegClass;
25193 // GCC allows "st(0)" to be called just plain "st".
25194 if (StringRef("{st}").equals_lower(Constraint)) {
25195 Res.first = X86::FP0;
25196 Res.second = &X86::RFP80RegClass;
25201 if (StringRef("{flags}").equals_lower(Constraint)) {
25202 Res.first = X86::EFLAGS;
25203 Res.second = &X86::CCRRegClass;
25207 // 'A' means EAX + EDX.
25208 if (Constraint == "A") {
25209 Res.first = X86::EAX;
25210 Res.second = &X86::GR32_ADRegClass;
25216 // Otherwise, check to see if this is a register class of the wrong value
25217 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25218 // turn into {ax},{dx}.
25219 if (Res.second->hasType(VT))
25220 return Res; // Correct type already, nothing to do.
25222 // All of the single-register GCC register classes map their values onto
25223 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
25224 // really want an 8-bit or 32-bit register, map to the appropriate register
25225 // class and return the appropriate register.
25226 if (Res.second == &X86::GR16RegClass) {
25227 if (VT == MVT::i8 || VT == MVT::i1) {
25228 unsigned DestReg = 0;
25229 switch (Res.first) {
25231 case X86::AX: DestReg = X86::AL; break;
25232 case X86::DX: DestReg = X86::DL; break;
25233 case X86::CX: DestReg = X86::CL; break;
25234 case X86::BX: DestReg = X86::BL; break;
25237 Res.first = DestReg;
25238 Res.second = &X86::GR8RegClass;
25240 } else if (VT == MVT::i32 || VT == MVT::f32) {
25241 unsigned DestReg = 0;
25242 switch (Res.first) {
25244 case X86::AX: DestReg = X86::EAX; break;
25245 case X86::DX: DestReg = X86::EDX; break;
25246 case X86::CX: DestReg = X86::ECX; break;
25247 case X86::BX: DestReg = X86::EBX; break;
25248 case X86::SI: DestReg = X86::ESI; break;
25249 case X86::DI: DestReg = X86::EDI; break;
25250 case X86::BP: DestReg = X86::EBP; break;
25251 case X86::SP: DestReg = X86::ESP; break;
25254 Res.first = DestReg;
25255 Res.second = &X86::GR32RegClass;
25257 } else if (VT == MVT::i64 || VT == MVT::f64) {
25258 unsigned DestReg = 0;
25259 switch (Res.first) {
25261 case X86::AX: DestReg = X86::RAX; break;
25262 case X86::DX: DestReg = X86::RDX; break;
25263 case X86::CX: DestReg = X86::RCX; break;
25264 case X86::BX: DestReg = X86::RBX; break;
25265 case X86::SI: DestReg = X86::RSI; break;
25266 case X86::DI: DestReg = X86::RDI; break;
25267 case X86::BP: DestReg = X86::RBP; break;
25268 case X86::SP: DestReg = X86::RSP; break;
25271 Res.first = DestReg;
25272 Res.second = &X86::GR64RegClass;
25275 } else if (Res.second == &X86::FR32RegClass ||
25276 Res.second == &X86::FR64RegClass ||
25277 Res.second == &X86::VR128RegClass ||
25278 Res.second == &X86::VR256RegClass ||
25279 Res.second == &X86::FR32XRegClass ||
25280 Res.second == &X86::FR64XRegClass ||
25281 Res.second == &X86::VR128XRegClass ||
25282 Res.second == &X86::VR256XRegClass ||
25283 Res.second == &X86::VR512RegClass) {
25284 // Handle references to XMM physical registers that got mapped into the
25285 // wrong class. This can happen with constraints like {xmm0} where the
25286 // target independent register mapper will just pick the first match it can
25287 // find, ignoring the required type.
25289 if (VT == MVT::f32 || VT == MVT::i32)
25290 Res.second = &X86::FR32RegClass;
25291 else if (VT == MVT::f64 || VT == MVT::i64)
25292 Res.second = &X86::FR64RegClass;
25293 else if (X86::VR128RegClass.hasType(VT))
25294 Res.second = &X86::VR128RegClass;
25295 else if (X86::VR256RegClass.hasType(VT))
25296 Res.second = &X86::VR256RegClass;
25297 else if (X86::VR512RegClass.hasType(VT))
25298 Res.second = &X86::VR512RegClass;
25304 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25306 // Scaling factors are not free at all.
25307 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25308 // will take 2 allocations in the out of order engine instead of 1
25309 // for plain addressing mode, i.e. inst (reg1).
25311 // vaddps (%rsi,%drx), %ymm0, %ymm1
25312 // Requires two allocations (one for the load, one for the computation)
25314 // vaddps (%rsi), %ymm0, %ymm1
25315 // Requires just 1 allocation, i.e., freeing allocations for other operations
25316 // and having less micro operations to execute.
25318 // For some X86 architectures, this is even worse because for instance for
25319 // stores, the complex addressing mode forces the instruction to use the
25320 // "load" ports instead of the dedicated "store" port.
25321 // E.g., on Haswell:
25322 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25323 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25324 if (isLegalAddressingMode(AM, Ty))
25325 // Scale represents reg2 * scale, thus account for 1
25326 // as soon as we use a second register.
25327 return AM.Scale != 0;
25331 bool X86TargetLowering::isTargetFTOL() const {
25332 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();