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::SUB, MVT::i1, Custom);
1270 setOperationAction(ISD::ADD, MVT::i1, Custom);
1271 setOperationAction(ISD::MUL, MVT::i1, Custom);
1272 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1273 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1274 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1275 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1276 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1278 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1279 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1280 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1281 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1282 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1283 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1285 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1286 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1287 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1288 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1289 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1290 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1291 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1292 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1294 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1295 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1296 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1297 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1298 if (Subtarget->is64Bit()) {
1299 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1300 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1301 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1302 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1304 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1305 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1306 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1307 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1308 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1309 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1310 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1311 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1312 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1313 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1314 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1315 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1316 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1317 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1318 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1319 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1321 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1322 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1323 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1324 if (Subtarget->hasDQI()) {
1325 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1326 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1328 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1329 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1330 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1331 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1332 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1333 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1334 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1335 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1336 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1337 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1338 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1339 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1340 if (Subtarget->hasDQI()) {
1341 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1342 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1344 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1346 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1348 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1349 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1350 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1351 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1352 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1355 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1356 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1357 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1358 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1359 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1361 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1362 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1364 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1366 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1367 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1368 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1369 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1370 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1371 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1372 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1373 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1374 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1375 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1376 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1378 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1379 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1381 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1382 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1384 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1386 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1387 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1389 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1390 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1392 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1393 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1395 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1396 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1397 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1398 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1399 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1400 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1402 if (Subtarget->hasCDI()) {
1403 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1404 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1406 if (Subtarget->hasDQI()) {
1407 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1408 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1409 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1411 // Custom lower several nodes.
1412 for (MVT VT : MVT::vector_valuetypes()) {
1413 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1415 setOperationAction(ISD::AND, VT, Legal);
1416 setOperationAction(ISD::OR, VT, Legal);
1417 setOperationAction(ISD::XOR, VT, Legal);
1419 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1420 setOperationAction(ISD::MGATHER, VT, Custom);
1421 setOperationAction(ISD::MSCATTER, VT, Custom);
1423 // Extract subvector is special because the value type
1424 // (result) is 256/128-bit but the source is 512-bit wide.
1425 if (VT.is128BitVector() || VT.is256BitVector()) {
1426 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1428 if (VT.getVectorElementType() == MVT::i1)
1429 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1431 // Do not attempt to custom lower other non-512-bit vectors
1432 if (!VT.is512BitVector())
1435 if (EltSize >= 32) {
1436 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1437 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1438 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1439 setOperationAction(ISD::VSELECT, VT, Legal);
1440 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1441 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1442 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1443 setOperationAction(ISD::MLOAD, VT, Legal);
1444 setOperationAction(ISD::MSTORE, VT, Legal);
1447 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1448 MVT VT = (MVT::SimpleValueType)i;
1450 // Do not attempt to promote non-512-bit vectors.
1451 if (!VT.is512BitVector())
1454 setOperationAction(ISD::SELECT, VT, Promote);
1455 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1459 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1460 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1461 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1463 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1464 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1466 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1467 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1468 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1469 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1470 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1471 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1472 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1473 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1474 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1475 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1476 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1477 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1478 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1479 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1480 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1481 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1482 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1483 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1484 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1485 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1486 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1487 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1488 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1490 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1491 const MVT VT = (MVT::SimpleValueType)i;
1493 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1495 // Do not attempt to promote non-512-bit vectors.
1496 if (!VT.is512BitVector())
1500 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1501 setOperationAction(ISD::VSELECT, VT, Legal);
1506 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1507 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1508 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1510 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1511 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1512 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1513 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1514 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1515 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1516 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1517 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1518 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1519 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1521 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1522 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1523 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1524 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1525 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1526 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1527 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1528 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1531 // We want to custom lower some of our intrinsics.
1532 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1533 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1534 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1535 if (!Subtarget->is64Bit())
1536 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1538 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1539 // handle type legalization for these operations here.
1541 // FIXME: We really should do custom legalization for addition and
1542 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1543 // than generic legalization for 64-bit multiplication-with-overflow, though.
1544 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1545 // Add/Sub/Mul with overflow operations are custom lowered.
1547 setOperationAction(ISD::SADDO, VT, Custom);
1548 setOperationAction(ISD::UADDO, VT, Custom);
1549 setOperationAction(ISD::SSUBO, VT, Custom);
1550 setOperationAction(ISD::USUBO, VT, Custom);
1551 setOperationAction(ISD::SMULO, VT, Custom);
1552 setOperationAction(ISD::UMULO, VT, Custom);
1556 if (!Subtarget->is64Bit()) {
1557 // These libcalls are not available in 32-bit.
1558 setLibcallName(RTLIB::SHL_I128, nullptr);
1559 setLibcallName(RTLIB::SRL_I128, nullptr);
1560 setLibcallName(RTLIB::SRA_I128, nullptr);
1563 // Combine sin / cos into one node or libcall if possible.
1564 if (Subtarget->hasSinCos()) {
1565 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1566 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1567 if (Subtarget->isTargetDarwin()) {
1568 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1569 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1570 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1571 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1575 if (Subtarget->isTargetWin64()) {
1576 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1577 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1578 setOperationAction(ISD::SREM, MVT::i128, Custom);
1579 setOperationAction(ISD::UREM, MVT::i128, Custom);
1580 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1581 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1584 // We have target-specific dag combine patterns for the following nodes:
1585 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1586 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1587 setTargetDAGCombine(ISD::BITCAST);
1588 setTargetDAGCombine(ISD::VSELECT);
1589 setTargetDAGCombine(ISD::SELECT);
1590 setTargetDAGCombine(ISD::SHL);
1591 setTargetDAGCombine(ISD::SRA);
1592 setTargetDAGCombine(ISD::SRL);
1593 setTargetDAGCombine(ISD::OR);
1594 setTargetDAGCombine(ISD::AND);
1595 setTargetDAGCombine(ISD::ADD);
1596 setTargetDAGCombine(ISD::FADD);
1597 setTargetDAGCombine(ISD::FSUB);
1598 setTargetDAGCombine(ISD::FMA);
1599 setTargetDAGCombine(ISD::SUB);
1600 setTargetDAGCombine(ISD::LOAD);
1601 setTargetDAGCombine(ISD::MLOAD);
1602 setTargetDAGCombine(ISD::STORE);
1603 setTargetDAGCombine(ISD::MSTORE);
1604 setTargetDAGCombine(ISD::ZERO_EXTEND);
1605 setTargetDAGCombine(ISD::ANY_EXTEND);
1606 setTargetDAGCombine(ISD::SIGN_EXTEND);
1607 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1608 setTargetDAGCombine(ISD::SINT_TO_FP);
1609 setTargetDAGCombine(ISD::SETCC);
1610 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1611 setTargetDAGCombine(ISD::BUILD_VECTOR);
1612 setTargetDAGCombine(ISD::MUL);
1613 setTargetDAGCombine(ISD::XOR);
1615 computeRegisterProperties(Subtarget->getRegisterInfo());
1617 // On Darwin, -Os means optimize for size without hurting performance,
1618 // do not reduce the limit.
1619 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1620 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1621 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1622 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1623 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1624 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1625 setPrefLoopAlignment(4); // 2^4 bytes.
1627 // Predictable cmov don't hurt on atom because it's in-order.
1628 PredictableSelectIsExpensive = !Subtarget->isAtom();
1629 EnableExtLdPromotion = true;
1630 setPrefFunctionAlignment(4); // 2^4 bytes.
1632 verifyIntrinsicTables();
1635 // This has so far only been implemented for 64-bit MachO.
1636 bool X86TargetLowering::useLoadStackGuardNode() const {
1637 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1640 TargetLoweringBase::LegalizeTypeAction
1641 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1642 if (ExperimentalVectorWideningLegalization &&
1643 VT.getVectorNumElements() != 1 &&
1644 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1645 return TypeWidenVector;
1647 return TargetLoweringBase::getPreferredVectorAction(VT);
1650 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1652 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1654 const unsigned NumElts = VT.getVectorNumElements();
1655 const EVT EltVT = VT.getVectorElementType();
1656 if (VT.is512BitVector()) {
1657 if (Subtarget->hasAVX512())
1658 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1659 EltVT == MVT::f32 || EltVT == MVT::f64)
1661 case 8: return MVT::v8i1;
1662 case 16: return MVT::v16i1;
1664 if (Subtarget->hasBWI())
1665 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1667 case 32: return MVT::v32i1;
1668 case 64: return MVT::v64i1;
1672 if (VT.is256BitVector() || VT.is128BitVector()) {
1673 if (Subtarget->hasVLX())
1674 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1675 EltVT == MVT::f32 || EltVT == MVT::f64)
1677 case 2: return MVT::v2i1;
1678 case 4: return MVT::v4i1;
1679 case 8: return MVT::v8i1;
1681 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1682 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1684 case 8: return MVT::v8i1;
1685 case 16: return MVT::v16i1;
1686 case 32: return MVT::v32i1;
1690 return VT.changeVectorElementTypeToInteger();
1693 /// Helper for getByValTypeAlignment to determine
1694 /// the desired ByVal argument alignment.
1695 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1698 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1699 if (VTy->getBitWidth() == 128)
1701 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1702 unsigned EltAlign = 0;
1703 getMaxByValAlign(ATy->getElementType(), EltAlign);
1704 if (EltAlign > MaxAlign)
1705 MaxAlign = EltAlign;
1706 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1707 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1708 unsigned EltAlign = 0;
1709 getMaxByValAlign(STy->getElementType(i), EltAlign);
1710 if (EltAlign > MaxAlign)
1711 MaxAlign = EltAlign;
1718 /// Return the desired alignment for ByVal aggregate
1719 /// function arguments in the caller parameter area. For X86, aggregates
1720 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1721 /// are at 4-byte boundaries.
1722 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1723 if (Subtarget->is64Bit()) {
1724 // Max of 8 and alignment of type.
1725 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1732 if (Subtarget->hasSSE1())
1733 getMaxByValAlign(Ty, Align);
1737 /// Returns the target specific optimal type for load
1738 /// and store operations as a result of memset, memcpy, and memmove
1739 /// lowering. If DstAlign is zero that means it's safe to destination
1740 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1741 /// means there isn't a need to check it against alignment requirement,
1742 /// probably because the source does not need to be loaded. If 'IsMemset' is
1743 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1744 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1745 /// source is constant so it does not need to be loaded.
1746 /// It returns EVT::Other if the type should be determined using generic
1747 /// target-independent logic.
1749 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1750 unsigned DstAlign, unsigned SrcAlign,
1751 bool IsMemset, bool ZeroMemset,
1753 MachineFunction &MF) const {
1754 const Function *F = MF.getFunction();
1755 if ((!IsMemset || ZeroMemset) &&
1756 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1758 (Subtarget->isUnalignedMemAccessFast() ||
1759 ((DstAlign == 0 || DstAlign >= 16) &&
1760 (SrcAlign == 0 || SrcAlign >= 16)))) {
1762 if (Subtarget->hasInt256())
1764 if (Subtarget->hasFp256())
1767 if (Subtarget->hasSSE2())
1769 if (Subtarget->hasSSE1())
1771 } else if (!MemcpyStrSrc && Size >= 8 &&
1772 !Subtarget->is64Bit() &&
1773 Subtarget->hasSSE2()) {
1774 // Do not use f64 to lower memcpy if source is string constant. It's
1775 // better to use i32 to avoid the loads.
1779 if (Subtarget->is64Bit() && Size >= 8)
1784 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1786 return X86ScalarSSEf32;
1787 else if (VT == MVT::f64)
1788 return X86ScalarSSEf64;
1793 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1798 *Fast = Subtarget->isUnalignedMemAccessFast();
1802 /// Return the entry encoding for a jump table in the
1803 /// current function. The returned value is a member of the
1804 /// MachineJumpTableInfo::JTEntryKind enum.
1805 unsigned X86TargetLowering::getJumpTableEncoding() const {
1806 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1808 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1809 Subtarget->isPICStyleGOT())
1810 return MachineJumpTableInfo::EK_Custom32;
1812 // Otherwise, use the normal jump table encoding heuristics.
1813 return TargetLowering::getJumpTableEncoding();
1816 bool X86TargetLowering::useSoftFloat() const {
1817 return Subtarget->useSoftFloat();
1821 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1822 const MachineBasicBlock *MBB,
1823 unsigned uid,MCContext &Ctx) const{
1824 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1825 Subtarget->isPICStyleGOT());
1826 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1828 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1829 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1832 /// Returns relocation base for the given PIC jumptable.
1833 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1834 SelectionDAG &DAG) const {
1835 if (!Subtarget->is64Bit())
1836 // This doesn't have SDLoc associated with it, but is not really the
1837 // same as a Register.
1838 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1842 /// This returns the relocation base for the given PIC jumptable,
1843 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1844 const MCExpr *X86TargetLowering::
1845 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1846 MCContext &Ctx) const {
1847 // X86-64 uses RIP relative addressing based on the jump table label.
1848 if (Subtarget->isPICStyleRIPRel())
1849 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1851 // Otherwise, the reference is relative to the PIC base.
1852 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1855 std::pair<const TargetRegisterClass *, uint8_t>
1856 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1858 const TargetRegisterClass *RRC = nullptr;
1860 switch (VT.SimpleTy) {
1862 return TargetLowering::findRepresentativeClass(TRI, VT);
1863 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1864 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1867 RRC = &X86::VR64RegClass;
1869 case MVT::f32: case MVT::f64:
1870 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1871 case MVT::v4f32: case MVT::v2f64:
1872 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1874 RRC = &X86::VR128RegClass;
1877 return std::make_pair(RRC, Cost);
1880 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1881 unsigned &Offset) const {
1882 if (!Subtarget->isTargetLinux())
1885 if (Subtarget->is64Bit()) {
1886 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1888 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1900 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1901 unsigned DestAS) const {
1902 assert(SrcAS != DestAS && "Expected different address spaces!");
1904 return SrcAS < 256 && DestAS < 256;
1907 //===----------------------------------------------------------------------===//
1908 // Return Value Calling Convention Implementation
1909 //===----------------------------------------------------------------------===//
1911 #include "X86GenCallingConv.inc"
1914 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1915 MachineFunction &MF, bool isVarArg,
1916 const SmallVectorImpl<ISD::OutputArg> &Outs,
1917 LLVMContext &Context) const {
1918 SmallVector<CCValAssign, 16> RVLocs;
1919 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1920 return CCInfo.CheckReturn(Outs, RetCC_X86);
1923 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1924 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1929 X86TargetLowering::LowerReturn(SDValue Chain,
1930 CallingConv::ID CallConv, bool isVarArg,
1931 const SmallVectorImpl<ISD::OutputArg> &Outs,
1932 const SmallVectorImpl<SDValue> &OutVals,
1933 SDLoc dl, SelectionDAG &DAG) const {
1934 MachineFunction &MF = DAG.getMachineFunction();
1935 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1937 SmallVector<CCValAssign, 16> RVLocs;
1938 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1939 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1942 SmallVector<SDValue, 6> RetOps;
1943 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1944 // Operand #1 = Bytes To Pop
1945 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1948 // Copy the result values into the output registers.
1949 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1950 CCValAssign &VA = RVLocs[i];
1951 assert(VA.isRegLoc() && "Can only return in registers!");
1952 SDValue ValToCopy = OutVals[i];
1953 EVT ValVT = ValToCopy.getValueType();
1955 // Promote values to the appropriate types.
1956 if (VA.getLocInfo() == CCValAssign::SExt)
1957 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1958 else if (VA.getLocInfo() == CCValAssign::ZExt)
1959 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1960 else if (VA.getLocInfo() == CCValAssign::AExt) {
1961 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1962 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1964 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1966 else if (VA.getLocInfo() == CCValAssign::BCvt)
1967 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1969 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1970 "Unexpected FP-extend for return value.");
1972 // If this is x86-64, and we disabled SSE, we can't return FP values,
1973 // or SSE or MMX vectors.
1974 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1975 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1976 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1977 report_fatal_error("SSE register return with SSE disabled");
1979 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1980 // llvm-gcc has never done it right and no one has noticed, so this
1981 // should be OK for now.
1982 if (ValVT == MVT::f64 &&
1983 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1984 report_fatal_error("SSE2 register return with SSE2 disabled");
1986 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1987 // the RET instruction and handled by the FP Stackifier.
1988 if (VA.getLocReg() == X86::FP0 ||
1989 VA.getLocReg() == X86::FP1) {
1990 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1991 // change the value to the FP stack register class.
1992 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1993 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1994 RetOps.push_back(ValToCopy);
1995 // Don't emit a copytoreg.
1999 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2000 // which is returned in RAX / RDX.
2001 if (Subtarget->is64Bit()) {
2002 if (ValVT == MVT::x86mmx) {
2003 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2004 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2005 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2007 // If we don't have SSE2 available, convert to v4f32 so the generated
2008 // register is legal.
2009 if (!Subtarget->hasSSE2())
2010 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2015 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2016 Flag = Chain.getValue(1);
2017 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2020 // All x86 ABIs require that for returning structs by value we copy
2021 // the sret argument into %rax/%eax (depending on ABI) for the return.
2022 // We saved the argument into a virtual register in the entry block,
2023 // so now we copy the value out and into %rax/%eax.
2025 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2026 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2027 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2028 // either case FuncInfo->setSRetReturnReg() will have been called.
2029 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2030 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2033 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2034 X86::RAX : X86::EAX;
2035 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2036 Flag = Chain.getValue(1);
2038 // RAX/EAX now acts like a return value.
2039 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2042 RetOps[0] = Chain; // Update chain.
2044 // Add the flag if we have it.
2046 RetOps.push_back(Flag);
2048 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2051 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2052 if (N->getNumValues() != 1)
2054 if (!N->hasNUsesOfValue(1, 0))
2057 SDValue TCChain = Chain;
2058 SDNode *Copy = *N->use_begin();
2059 if (Copy->getOpcode() == ISD::CopyToReg) {
2060 // If the copy has a glue operand, we conservatively assume it isn't safe to
2061 // perform a tail call.
2062 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2064 TCChain = Copy->getOperand(0);
2065 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2068 bool HasRet = false;
2069 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2071 if (UI->getOpcode() != X86ISD::RET_FLAG)
2073 // If we are returning more than one value, we can definitely
2074 // not make a tail call see PR19530
2075 if (UI->getNumOperands() > 4)
2077 if (UI->getNumOperands() == 4 &&
2078 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2091 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2092 ISD::NodeType ExtendKind) const {
2094 // TODO: Is this also valid on 32-bit?
2095 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2096 ReturnMVT = MVT::i8;
2098 ReturnMVT = MVT::i32;
2100 EVT MinVT = getRegisterType(Context, ReturnMVT);
2101 return VT.bitsLT(MinVT) ? MinVT : VT;
2104 /// Lower the result values of a call into the
2105 /// appropriate copies out of appropriate physical registers.
2108 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2109 CallingConv::ID CallConv, bool isVarArg,
2110 const SmallVectorImpl<ISD::InputArg> &Ins,
2111 SDLoc dl, SelectionDAG &DAG,
2112 SmallVectorImpl<SDValue> &InVals) const {
2114 // Assign locations to each value returned by this call.
2115 SmallVector<CCValAssign, 16> RVLocs;
2116 bool Is64Bit = Subtarget->is64Bit();
2117 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2119 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2121 // Copy all of the result registers out of their specified physreg.
2122 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2123 CCValAssign &VA = RVLocs[i];
2124 EVT CopyVT = VA.getLocVT();
2126 // If this is x86-64, and we disabled SSE, we can't return FP values
2127 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2128 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2129 report_fatal_error("SSE register return with SSE disabled");
2132 // If we prefer to use the value in xmm registers, copy it out as f80 and
2133 // use a truncate to move it from fp stack reg to xmm reg.
2134 bool RoundAfterCopy = false;
2135 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2136 isScalarFPTypeInSSEReg(VA.getValVT())) {
2138 RoundAfterCopy = (CopyVT != VA.getLocVT());
2141 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2142 CopyVT, InFlag).getValue(1);
2143 SDValue Val = Chain.getValue(0);
2146 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2147 // This truncation won't change the value.
2148 DAG.getIntPtrConstant(1, dl));
2150 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2151 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2153 InFlag = Chain.getValue(2);
2154 InVals.push_back(Val);
2160 //===----------------------------------------------------------------------===//
2161 // C & StdCall & Fast Calling Convention implementation
2162 //===----------------------------------------------------------------------===//
2163 // StdCall calling convention seems to be standard for many Windows' API
2164 // routines and around. It differs from C calling convention just a little:
2165 // callee should clean up the stack, not caller. Symbols should be also
2166 // decorated in some fancy way :) It doesn't support any vector arguments.
2167 // For info on fast calling convention see Fast Calling Convention (tail call)
2168 // implementation LowerX86_32FastCCCallTo.
2170 /// CallIsStructReturn - Determines whether a call uses struct return
2172 enum StructReturnType {
2177 static StructReturnType
2178 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2180 return NotStructReturn;
2182 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2183 if (!Flags.isSRet())
2184 return NotStructReturn;
2185 if (Flags.isInReg())
2186 return RegStructReturn;
2187 return StackStructReturn;
2190 /// Determines whether a function uses struct return semantics.
2191 static StructReturnType
2192 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2194 return NotStructReturn;
2196 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2197 if (!Flags.isSRet())
2198 return NotStructReturn;
2199 if (Flags.isInReg())
2200 return RegStructReturn;
2201 return StackStructReturn;
2204 /// Make a copy of an aggregate at address specified by "Src" to address
2205 /// "Dst" with size and alignment information specified by the specific
2206 /// parameter attribute. The copy will be passed as a byval function parameter.
2208 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2209 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2211 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2213 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2214 /*isVolatile*/false, /*AlwaysInline=*/true,
2215 /*isTailCall*/false,
2216 MachinePointerInfo(), MachinePointerInfo());
2219 /// Return true if the calling convention is one that
2220 /// supports tail call optimization.
2221 static bool IsTailCallConvention(CallingConv::ID CC) {
2222 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2223 CC == CallingConv::HiPE);
2226 /// \brief Return true if the calling convention is a C calling convention.
2227 static bool IsCCallConvention(CallingConv::ID CC) {
2228 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2229 CC == CallingConv::X86_64_SysV);
2232 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2233 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2237 CallingConv::ID CalleeCC = CS.getCallingConv();
2238 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2244 /// Return true if the function is being made into
2245 /// a tailcall target by changing its ABI.
2246 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2247 bool GuaranteedTailCallOpt) {
2248 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2252 X86TargetLowering::LowerMemArgument(SDValue Chain,
2253 CallingConv::ID CallConv,
2254 const SmallVectorImpl<ISD::InputArg> &Ins,
2255 SDLoc dl, SelectionDAG &DAG,
2256 const CCValAssign &VA,
2257 MachineFrameInfo *MFI,
2259 // Create the nodes corresponding to a load from this parameter slot.
2260 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2261 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2262 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2263 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2266 // If value is passed by pointer we have address passed instead of the value
2268 bool ExtendedInMem = VA.isExtInLoc() &&
2269 VA.getValVT().getScalarType() == MVT::i1;
2271 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2272 ValVT = VA.getLocVT();
2274 ValVT = VA.getValVT();
2276 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2277 // changed with more analysis.
2278 // In case of tail call optimization mark all arguments mutable. Since they
2279 // could be overwritten by lowering of arguments in case of a tail call.
2280 if (Flags.isByVal()) {
2281 unsigned Bytes = Flags.getByValSize();
2282 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2283 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2284 return DAG.getFrameIndex(FI, getPointerTy());
2286 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2287 VA.getLocMemOffset(), isImmutable);
2288 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2289 SDValue Val = DAG.getLoad(ValVT, dl, Chain, FIN,
2290 MachinePointerInfo::getFixedStack(FI),
2291 false, false, false, 0);
2292 return ExtendedInMem ?
2293 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2297 // FIXME: Get this from tablegen.
2298 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2299 const X86Subtarget *Subtarget) {
2300 assert(Subtarget->is64Bit());
2302 if (Subtarget->isCallingConvWin64(CallConv)) {
2303 static const MCPhysReg GPR64ArgRegsWin64[] = {
2304 X86::RCX, X86::RDX, X86::R8, X86::R9
2306 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2309 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2310 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2312 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2315 // FIXME: Get this from tablegen.
2316 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2317 CallingConv::ID CallConv,
2318 const X86Subtarget *Subtarget) {
2319 assert(Subtarget->is64Bit());
2320 if (Subtarget->isCallingConvWin64(CallConv)) {
2321 // The XMM registers which might contain var arg parameters are shadowed
2322 // in their paired GPR. So we only need to save the GPR to their home
2324 // TODO: __vectorcall will change this.
2328 const Function *Fn = MF.getFunction();
2329 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2330 bool isSoftFloat = Subtarget->useSoftFloat();
2331 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2332 "SSE register cannot be used when SSE is disabled!");
2333 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2334 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2338 static const MCPhysReg XMMArgRegs64Bit[] = {
2339 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2340 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2342 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2346 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2347 CallingConv::ID CallConv,
2349 const SmallVectorImpl<ISD::InputArg> &Ins,
2352 SmallVectorImpl<SDValue> &InVals)
2354 MachineFunction &MF = DAG.getMachineFunction();
2355 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2356 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2358 const Function* Fn = MF.getFunction();
2359 if (Fn->hasExternalLinkage() &&
2360 Subtarget->isTargetCygMing() &&
2361 Fn->getName() == "main")
2362 FuncInfo->setForceFramePointer(true);
2364 MachineFrameInfo *MFI = MF.getFrameInfo();
2365 bool Is64Bit = Subtarget->is64Bit();
2366 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2368 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2369 "Var args not supported with calling convention fastcc, ghc or hipe");
2371 // Assign locations to all of the incoming arguments.
2372 SmallVector<CCValAssign, 16> ArgLocs;
2373 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2375 // Allocate shadow area for Win64
2377 CCInfo.AllocateStack(32, 8);
2379 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2381 unsigned LastVal = ~0U;
2383 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2384 CCValAssign &VA = ArgLocs[i];
2385 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2387 assert(VA.getValNo() != LastVal &&
2388 "Don't support value assigned to multiple locs yet");
2390 LastVal = VA.getValNo();
2392 if (VA.isRegLoc()) {
2393 EVT RegVT = VA.getLocVT();
2394 const TargetRegisterClass *RC;
2395 if (RegVT == MVT::i32)
2396 RC = &X86::GR32RegClass;
2397 else if (Is64Bit && RegVT == MVT::i64)
2398 RC = &X86::GR64RegClass;
2399 else if (RegVT == MVT::f32)
2400 RC = &X86::FR32RegClass;
2401 else if (RegVT == MVT::f64)
2402 RC = &X86::FR64RegClass;
2403 else if (RegVT.is512BitVector())
2404 RC = &X86::VR512RegClass;
2405 else if (RegVT.is256BitVector())
2406 RC = &X86::VR256RegClass;
2407 else if (RegVT.is128BitVector())
2408 RC = &X86::VR128RegClass;
2409 else if (RegVT == MVT::x86mmx)
2410 RC = &X86::VR64RegClass;
2411 else if (RegVT == MVT::i1)
2412 RC = &X86::VK1RegClass;
2413 else if (RegVT == MVT::v8i1)
2414 RC = &X86::VK8RegClass;
2415 else if (RegVT == MVT::v16i1)
2416 RC = &X86::VK16RegClass;
2417 else if (RegVT == MVT::v32i1)
2418 RC = &X86::VK32RegClass;
2419 else if (RegVT == MVT::v64i1)
2420 RC = &X86::VK64RegClass;
2422 llvm_unreachable("Unknown argument type!");
2424 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2425 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2427 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2428 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2430 if (VA.getLocInfo() == CCValAssign::SExt)
2431 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2432 DAG.getValueType(VA.getValVT()));
2433 else if (VA.getLocInfo() == CCValAssign::ZExt)
2434 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2435 DAG.getValueType(VA.getValVT()));
2436 else if (VA.getLocInfo() == CCValAssign::BCvt)
2437 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2439 if (VA.isExtInLoc()) {
2440 // Handle MMX values passed in XMM regs.
2441 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2442 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2444 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2447 assert(VA.isMemLoc());
2448 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2451 // If value is passed via pointer - do a load.
2452 if (VA.getLocInfo() == CCValAssign::Indirect)
2453 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2454 MachinePointerInfo(), false, false, false, 0);
2456 InVals.push_back(ArgValue);
2459 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2460 // All x86 ABIs require that for returning structs by value we copy the
2461 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2462 // the argument into a virtual register so that we can access it from the
2464 if (Ins[i].Flags.isSRet()) {
2465 unsigned Reg = FuncInfo->getSRetReturnReg();
2467 MVT PtrTy = getPointerTy();
2468 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2469 FuncInfo->setSRetReturnReg(Reg);
2471 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2472 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2477 unsigned StackSize = CCInfo.getNextStackOffset();
2478 // Align stack specially for tail calls.
2479 if (FuncIsMadeTailCallSafe(CallConv,
2480 MF.getTarget().Options.GuaranteedTailCallOpt))
2481 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2483 // If the function takes variable number of arguments, make a frame index for
2484 // the start of the first vararg value... for expansion of llvm.va_start. We
2485 // can skip this if there are no va_start calls.
2486 if (MFI->hasVAStart() &&
2487 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2488 CallConv != CallingConv::X86_ThisCall))) {
2489 FuncInfo->setVarArgsFrameIndex(
2490 MFI->CreateFixedObject(1, StackSize, true));
2493 MachineModuleInfo &MMI = MF.getMMI();
2494 const Function *WinEHParent = nullptr;
2495 if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2496 WinEHParent = MMI.getWinEHParent(Fn);
2497 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2498 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2500 // Figure out if XMM registers are in use.
2501 assert(!(Subtarget->useSoftFloat() &&
2502 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2503 "SSE register cannot be used when SSE is disabled!");
2505 // 64-bit calling conventions support varargs and register parameters, so we
2506 // have to do extra work to spill them in the prologue.
2507 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2508 // Find the first unallocated argument registers.
2509 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2510 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2511 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2512 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2513 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2514 "SSE register cannot be used when SSE is disabled!");
2516 // Gather all the live in physical registers.
2517 SmallVector<SDValue, 6> LiveGPRs;
2518 SmallVector<SDValue, 8> LiveXMMRegs;
2520 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2521 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2523 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2525 if (!ArgXMMs.empty()) {
2526 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2527 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2528 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2529 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2530 LiveXMMRegs.push_back(
2531 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2536 // Get to the caller-allocated home save location. Add 8 to account
2537 // for the return address.
2538 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2539 FuncInfo->setRegSaveFrameIndex(
2540 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2541 // Fixup to set vararg frame on shadow area (4 x i64).
2543 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2545 // For X86-64, if there are vararg parameters that are passed via
2546 // registers, then we must store them to their spots on the stack so
2547 // they may be loaded by deferencing the result of va_next.
2548 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2549 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2550 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2551 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2554 // Store the integer parameter registers.
2555 SmallVector<SDValue, 8> MemOps;
2556 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2558 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2559 for (SDValue Val : LiveGPRs) {
2560 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2561 DAG.getIntPtrConstant(Offset, dl));
2563 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2564 MachinePointerInfo::getFixedStack(
2565 FuncInfo->getRegSaveFrameIndex(), Offset),
2567 MemOps.push_back(Store);
2571 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2572 // Now store the XMM (fp + vector) parameter registers.
2573 SmallVector<SDValue, 12> SaveXMMOps;
2574 SaveXMMOps.push_back(Chain);
2575 SaveXMMOps.push_back(ALVal);
2576 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2577 FuncInfo->getRegSaveFrameIndex(), dl));
2578 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2579 FuncInfo->getVarArgsFPOffset(), dl));
2580 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2582 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2583 MVT::Other, SaveXMMOps));
2586 if (!MemOps.empty())
2587 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2588 } else if (IsWinEHOutlined) {
2589 // Get to the caller-allocated home save location. Add 8 to account
2590 // for the return address.
2591 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2592 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2593 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2595 MMI.getWinEHFuncInfo(Fn)
2596 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2597 FuncInfo->getRegSaveFrameIndex();
2599 // Store the second integer parameter (rdx) into rsp+16 relative to the
2600 // stack pointer at the entry of the function.
2602 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2603 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2604 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2605 Chain = DAG.getStore(
2606 Val.getValue(1), dl, Val, RSFIN,
2607 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2608 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2611 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2612 // Find the largest legal vector type.
2613 MVT VecVT = MVT::Other;
2614 // FIXME: Only some x86_32 calling conventions support AVX512.
2615 if (Subtarget->hasAVX512() &&
2616 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2617 CallConv == CallingConv::Intel_OCL_BI)))
2618 VecVT = MVT::v16f32;
2619 else if (Subtarget->hasAVX())
2621 else if (Subtarget->hasSSE2())
2624 // We forward some GPRs and some vector types.
2625 SmallVector<MVT, 2> RegParmTypes;
2626 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2627 RegParmTypes.push_back(IntVT);
2628 if (VecVT != MVT::Other)
2629 RegParmTypes.push_back(VecVT);
2631 // Compute the set of forwarded registers. The rest are scratch.
2632 SmallVectorImpl<ForwardedRegister> &Forwards =
2633 FuncInfo->getForwardedMustTailRegParms();
2634 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2636 // Conservatively forward AL on x86_64, since it might be used for varargs.
2637 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2638 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2639 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2642 // Copy all forwards from physical to virtual registers.
2643 for (ForwardedRegister &F : Forwards) {
2644 // FIXME: Can we use a less constrained schedule?
2645 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2646 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2647 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2651 // Some CCs need callee pop.
2652 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2653 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2654 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2656 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2657 // If this is an sret function, the return should pop the hidden pointer.
2658 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2659 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2660 argsAreStructReturn(Ins) == StackStructReturn)
2661 FuncInfo->setBytesToPopOnReturn(4);
2665 // RegSaveFrameIndex is X86-64 only.
2666 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2667 if (CallConv == CallingConv::X86_FastCall ||
2668 CallConv == CallingConv::X86_ThisCall)
2669 // fastcc functions can't have varargs.
2670 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2673 FuncInfo->setArgumentStackSize(StackSize);
2675 if (IsWinEHParent) {
2676 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2677 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2678 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2679 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2680 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2681 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2682 /*isVolatile=*/true,
2683 /*isNonTemporal=*/false, /*Alignment=*/0);
2690 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2691 SDValue StackPtr, SDValue Arg,
2692 SDLoc dl, SelectionDAG &DAG,
2693 const CCValAssign &VA,
2694 ISD::ArgFlagsTy Flags) const {
2695 unsigned LocMemOffset = VA.getLocMemOffset();
2696 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2697 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2698 if (Flags.isByVal())
2699 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2701 return DAG.getStore(Chain, dl, Arg, PtrOff,
2702 MachinePointerInfo::getStack(LocMemOffset),
2706 /// Emit a load of return address if tail call
2707 /// optimization is performed and it is required.
2709 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2710 SDValue &OutRetAddr, SDValue Chain,
2711 bool IsTailCall, bool Is64Bit,
2712 int FPDiff, SDLoc dl) const {
2713 // Adjust the Return address stack slot.
2714 EVT VT = getPointerTy();
2715 OutRetAddr = getReturnAddressFrameIndex(DAG);
2717 // Load the "old" Return address.
2718 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2719 false, false, false, 0);
2720 return SDValue(OutRetAddr.getNode(), 1);
2723 /// Emit a store of the return address if tail call
2724 /// optimization is performed and it is required (FPDiff!=0).
2725 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2726 SDValue Chain, SDValue RetAddrFrIdx,
2727 EVT PtrVT, unsigned SlotSize,
2728 int FPDiff, SDLoc dl) {
2729 // Store the return address to the appropriate stack slot.
2730 if (!FPDiff) return Chain;
2731 // Calculate the new stack slot for the return address.
2732 int NewReturnAddrFI =
2733 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2735 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2736 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2737 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2743 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2744 SmallVectorImpl<SDValue> &InVals) const {
2745 SelectionDAG &DAG = CLI.DAG;
2747 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2748 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2749 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2750 SDValue Chain = CLI.Chain;
2751 SDValue Callee = CLI.Callee;
2752 CallingConv::ID CallConv = CLI.CallConv;
2753 bool &isTailCall = CLI.IsTailCall;
2754 bool isVarArg = CLI.IsVarArg;
2756 MachineFunction &MF = DAG.getMachineFunction();
2757 bool Is64Bit = Subtarget->is64Bit();
2758 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2759 StructReturnType SR = callIsStructReturn(Outs);
2760 bool IsSibcall = false;
2761 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2763 if (MF.getTarget().Options.DisableTailCalls)
2766 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2768 // Force this to be a tail call. The verifier rules are enough to ensure
2769 // that we can lower this successfully without moving the return address
2772 } else if (isTailCall) {
2773 // Check if it's really possible to do a tail call.
2774 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2775 isVarArg, SR != NotStructReturn,
2776 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2777 Outs, OutVals, Ins, DAG);
2779 // Sibcalls are automatically detected tailcalls which do not require
2781 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2788 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2789 "Var args not supported with calling convention fastcc, ghc or hipe");
2791 // Analyze operands of the call, assigning locations to each operand.
2792 SmallVector<CCValAssign, 16> ArgLocs;
2793 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2795 // Allocate shadow area for Win64
2797 CCInfo.AllocateStack(32, 8);
2799 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2801 // Get a count of how many bytes are to be pushed on the stack.
2802 unsigned NumBytes = CCInfo.getNextStackOffset();
2804 // This is a sibcall. The memory operands are available in caller's
2805 // own caller's stack.
2807 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2808 IsTailCallConvention(CallConv))
2809 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2812 if (isTailCall && !IsSibcall && !IsMustTail) {
2813 // Lower arguments at fp - stackoffset + fpdiff.
2814 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2816 FPDiff = NumBytesCallerPushed - NumBytes;
2818 // Set the delta of movement of the returnaddr stackslot.
2819 // But only set if delta is greater than previous delta.
2820 if (FPDiff < X86Info->getTCReturnAddrDelta())
2821 X86Info->setTCReturnAddrDelta(FPDiff);
2824 unsigned NumBytesToPush = NumBytes;
2825 unsigned NumBytesToPop = NumBytes;
2827 // If we have an inalloca argument, all stack space has already been allocated
2828 // for us and be right at the top of the stack. We don't support multiple
2829 // arguments passed in memory when using inalloca.
2830 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2832 if (!ArgLocs.back().isMemLoc())
2833 report_fatal_error("cannot use inalloca attribute on a register "
2835 if (ArgLocs.back().getLocMemOffset() != 0)
2836 report_fatal_error("any parameter with the inalloca attribute must be "
2837 "the only memory argument");
2841 Chain = DAG.getCALLSEQ_START(
2842 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2844 SDValue RetAddrFrIdx;
2845 // Load return address for tail calls.
2846 if (isTailCall && FPDiff)
2847 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2848 Is64Bit, FPDiff, dl);
2850 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2851 SmallVector<SDValue, 8> MemOpChains;
2854 // Walk the register/memloc assignments, inserting copies/loads. In the case
2855 // of tail call optimization arguments are handle later.
2856 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2857 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2858 // Skip inalloca arguments, they have already been written.
2859 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2860 if (Flags.isInAlloca())
2863 CCValAssign &VA = ArgLocs[i];
2864 EVT RegVT = VA.getLocVT();
2865 SDValue Arg = OutVals[i];
2866 bool isByVal = Flags.isByVal();
2868 // Promote the value if needed.
2869 switch (VA.getLocInfo()) {
2870 default: llvm_unreachable("Unknown loc info!");
2871 case CCValAssign::Full: break;
2872 case CCValAssign::SExt:
2873 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2875 case CCValAssign::ZExt:
2876 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2878 case CCValAssign::AExt:
2879 if (Arg.getValueType().isVector() &&
2880 Arg.getValueType().getScalarType() == MVT::i1)
2881 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2882 else if (RegVT.is128BitVector()) {
2883 // Special case: passing MMX values in XMM registers.
2884 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2885 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2886 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2888 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2890 case CCValAssign::BCvt:
2891 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2893 case CCValAssign::Indirect: {
2894 // Store the argument.
2895 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2896 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2897 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2898 MachinePointerInfo::getFixedStack(FI),
2905 if (VA.isRegLoc()) {
2906 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2907 if (isVarArg && IsWin64) {
2908 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2909 // shadow reg if callee is a varargs function.
2910 unsigned ShadowReg = 0;
2911 switch (VA.getLocReg()) {
2912 case X86::XMM0: ShadowReg = X86::RCX; break;
2913 case X86::XMM1: ShadowReg = X86::RDX; break;
2914 case X86::XMM2: ShadowReg = X86::R8; break;
2915 case X86::XMM3: ShadowReg = X86::R9; break;
2918 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2920 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2921 assert(VA.isMemLoc());
2922 if (!StackPtr.getNode())
2923 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2925 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2926 dl, DAG, VA, Flags));
2930 if (!MemOpChains.empty())
2931 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2933 if (Subtarget->isPICStyleGOT()) {
2934 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2937 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2938 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2940 // If we are tail calling and generating PIC/GOT style code load the
2941 // address of the callee into ECX. The value in ecx is used as target of
2942 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2943 // for tail calls on PIC/GOT architectures. Normally we would just put the
2944 // address of GOT into ebx and then call target@PLT. But for tail calls
2945 // ebx would be restored (since ebx is callee saved) before jumping to the
2948 // Note: The actual moving to ECX is done further down.
2949 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2950 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2951 !G->getGlobal()->hasProtectedVisibility())
2952 Callee = LowerGlobalAddress(Callee, DAG);
2953 else if (isa<ExternalSymbolSDNode>(Callee))
2954 Callee = LowerExternalSymbol(Callee, DAG);
2958 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2959 // From AMD64 ABI document:
2960 // For calls that may call functions that use varargs or stdargs
2961 // (prototype-less calls or calls to functions containing ellipsis (...) in
2962 // the declaration) %al is used as hidden argument to specify the number
2963 // of SSE registers used. The contents of %al do not need to match exactly
2964 // the number of registers, but must be an ubound on the number of SSE
2965 // registers used and is in the range 0 - 8 inclusive.
2967 // Count the number of XMM registers allocated.
2968 static const MCPhysReg XMMArgRegs[] = {
2969 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2970 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2972 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2973 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2974 && "SSE registers cannot be used when SSE is disabled");
2976 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2977 DAG.getConstant(NumXMMRegs, dl,
2981 if (isVarArg && IsMustTail) {
2982 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2983 for (const auto &F : Forwards) {
2984 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2985 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2989 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2990 // don't need this because the eligibility check rejects calls that require
2991 // shuffling arguments passed in memory.
2992 if (!IsSibcall && isTailCall) {
2993 // Force all the incoming stack arguments to be loaded from the stack
2994 // before any new outgoing arguments are stored to the stack, because the
2995 // outgoing stack slots may alias the incoming argument stack slots, and
2996 // the alias isn't otherwise explicit. This is slightly more conservative
2997 // than necessary, because it means that each store effectively depends
2998 // on every argument instead of just those arguments it would clobber.
2999 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3001 SmallVector<SDValue, 8> MemOpChains2;
3004 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3005 CCValAssign &VA = ArgLocs[i];
3008 assert(VA.isMemLoc());
3009 SDValue Arg = OutVals[i];
3010 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3011 // Skip inalloca arguments. They don't require any work.
3012 if (Flags.isInAlloca())
3014 // Create frame index.
3015 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3016 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3017 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3018 FIN = DAG.getFrameIndex(FI, getPointerTy());
3020 if (Flags.isByVal()) {
3021 // Copy relative to framepointer.
3022 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3023 if (!StackPtr.getNode())
3024 StackPtr = DAG.getCopyFromReg(Chain, dl,
3025 RegInfo->getStackRegister(),
3027 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3029 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3033 // Store relative to framepointer.
3034 MemOpChains2.push_back(
3035 DAG.getStore(ArgChain, dl, Arg, FIN,
3036 MachinePointerInfo::getFixedStack(FI),
3041 if (!MemOpChains2.empty())
3042 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3044 // Store the return address to the appropriate stack slot.
3045 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3046 getPointerTy(), RegInfo->getSlotSize(),
3050 // Build a sequence of copy-to-reg nodes chained together with token chain
3051 // and flag operands which copy the outgoing args into registers.
3053 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3054 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3055 RegsToPass[i].second, InFlag);
3056 InFlag = Chain.getValue(1);
3059 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3060 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3061 // In the 64-bit large code model, we have to make all calls
3062 // through a register, since the call instruction's 32-bit
3063 // pc-relative offset may not be large enough to hold the whole
3065 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3066 // If the callee is a GlobalAddress node (quite common, every direct call
3067 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3069 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3071 // We should use extra load for direct calls to dllimported functions in
3073 const GlobalValue *GV = G->getGlobal();
3074 if (!GV->hasDLLImportStorageClass()) {
3075 unsigned char OpFlags = 0;
3076 bool ExtraLoad = false;
3077 unsigned WrapperKind = ISD::DELETED_NODE;
3079 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3080 // external symbols most go through the PLT in PIC mode. If the symbol
3081 // has hidden or protected visibility, or if it is static or local, then
3082 // we don't need to use the PLT - we can directly call it.
3083 if (Subtarget->isTargetELF() &&
3084 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3085 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3086 OpFlags = X86II::MO_PLT;
3087 } else if (Subtarget->isPICStyleStubAny() &&
3088 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3089 (!Subtarget->getTargetTriple().isMacOSX() ||
3090 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3091 // PC-relative references to external symbols should go through $stub,
3092 // unless we're building with the leopard linker or later, which
3093 // automatically synthesizes these stubs.
3094 OpFlags = X86II::MO_DARWIN_STUB;
3095 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3096 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3097 // If the function is marked as non-lazy, generate an indirect call
3098 // which loads from the GOT directly. This avoids runtime overhead
3099 // at the cost of eager binding (and one extra byte of encoding).
3100 OpFlags = X86II::MO_GOTPCREL;
3101 WrapperKind = X86ISD::WrapperRIP;
3105 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3106 G->getOffset(), OpFlags);
3108 // Add a wrapper if needed.
3109 if (WrapperKind != ISD::DELETED_NODE)
3110 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3111 // Add extra indirection if needed.
3113 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3114 MachinePointerInfo::getGOT(),
3115 false, false, false, 0);
3117 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3118 unsigned char OpFlags = 0;
3120 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3121 // external symbols should go through the PLT.
3122 if (Subtarget->isTargetELF() &&
3123 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3124 OpFlags = X86II::MO_PLT;
3125 } else if (Subtarget->isPICStyleStubAny() &&
3126 (!Subtarget->getTargetTriple().isMacOSX() ||
3127 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3128 // PC-relative references to external symbols should go through $stub,
3129 // unless we're building with the leopard linker or later, which
3130 // automatically synthesizes these stubs.
3131 OpFlags = X86II::MO_DARWIN_STUB;
3134 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3136 } else if (Subtarget->isTarget64BitILP32() &&
3137 Callee->getValueType(0) == MVT::i32) {
3138 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3139 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3142 // Returns a chain & a flag for retval copy to use.
3143 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3144 SmallVector<SDValue, 8> Ops;
3146 if (!IsSibcall && isTailCall) {
3147 Chain = DAG.getCALLSEQ_END(Chain,
3148 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3149 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3150 InFlag = Chain.getValue(1);
3153 Ops.push_back(Chain);
3154 Ops.push_back(Callee);
3157 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3159 // Add argument registers to the end of the list so that they are known live
3161 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3162 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3163 RegsToPass[i].second.getValueType()));
3165 // Add a register mask operand representing the call-preserved registers.
3166 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3167 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3168 assert(Mask && "Missing call preserved mask for calling convention");
3169 Ops.push_back(DAG.getRegisterMask(Mask));
3171 if (InFlag.getNode())
3172 Ops.push_back(InFlag);
3176 //// If this is the first return lowered for this function, add the regs
3177 //// to the liveout set for the function.
3178 // This isn't right, although it's probably harmless on x86; liveouts
3179 // should be computed from returns not tail calls. Consider a void
3180 // function making a tail call to a function returning int.
3181 MF.getFrameInfo()->setHasTailCall();
3182 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3185 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3186 InFlag = Chain.getValue(1);
3188 // Create the CALLSEQ_END node.
3189 unsigned NumBytesForCalleeToPop;
3190 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3191 DAG.getTarget().Options.GuaranteedTailCallOpt))
3192 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3193 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3194 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3195 SR == StackStructReturn)
3196 // If this is a call to a struct-return function, the callee
3197 // pops the hidden struct pointer, so we have to push it back.
3198 // This is common for Darwin/X86, Linux & Mingw32 targets.
3199 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3200 NumBytesForCalleeToPop = 4;
3202 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3204 // Returns a flag for retval copy to use.
3206 Chain = DAG.getCALLSEQ_END(Chain,
3207 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3208 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3211 InFlag = Chain.getValue(1);
3214 // Handle result values, copying them out of physregs into vregs that we
3216 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3217 Ins, dl, DAG, InVals);
3220 //===----------------------------------------------------------------------===//
3221 // Fast Calling Convention (tail call) implementation
3222 //===----------------------------------------------------------------------===//
3224 // Like std call, callee cleans arguments, convention except that ECX is
3225 // reserved for storing the tail called function address. Only 2 registers are
3226 // free for argument passing (inreg). Tail call optimization is performed
3228 // * tailcallopt is enabled
3229 // * caller/callee are fastcc
3230 // On X86_64 architecture with GOT-style position independent code only local
3231 // (within module) calls are supported at the moment.
3232 // To keep the stack aligned according to platform abi the function
3233 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3234 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3235 // If a tail called function callee has more arguments than the caller the
3236 // caller needs to make sure that there is room to move the RETADDR to. This is
3237 // achieved by reserving an area the size of the argument delta right after the
3238 // original RETADDR, but before the saved framepointer or the spilled registers
3239 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3251 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3252 /// for a 16 byte align requirement.
3254 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3255 SelectionDAG& DAG) const {
3256 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3257 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3258 unsigned StackAlignment = TFI.getStackAlignment();
3259 uint64_t AlignMask = StackAlignment - 1;
3260 int64_t Offset = StackSize;
3261 unsigned SlotSize = RegInfo->getSlotSize();
3262 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3263 // Number smaller than 12 so just add the difference.
3264 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3266 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3267 Offset = ((~AlignMask) & Offset) + StackAlignment +
3268 (StackAlignment-SlotSize);
3273 /// MatchingStackOffset - Return true if the given stack call argument is
3274 /// already available in the same position (relatively) of the caller's
3275 /// incoming argument stack.
3277 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3278 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3279 const X86InstrInfo *TII) {
3280 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3282 if (Arg.getOpcode() == ISD::CopyFromReg) {
3283 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3284 if (!TargetRegisterInfo::isVirtualRegister(VR))
3286 MachineInstr *Def = MRI->getVRegDef(VR);
3289 if (!Flags.isByVal()) {
3290 if (!TII->isLoadFromStackSlot(Def, FI))
3293 unsigned Opcode = Def->getOpcode();
3294 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3295 Opcode == X86::LEA64_32r) &&
3296 Def->getOperand(1).isFI()) {
3297 FI = Def->getOperand(1).getIndex();
3298 Bytes = Flags.getByValSize();
3302 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3303 if (Flags.isByVal())
3304 // ByVal argument is passed in as a pointer but it's now being
3305 // dereferenced. e.g.
3306 // define @foo(%struct.X* %A) {
3307 // tail call @bar(%struct.X* byval %A)
3310 SDValue Ptr = Ld->getBasePtr();
3311 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3314 FI = FINode->getIndex();
3315 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3316 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3317 FI = FINode->getIndex();
3318 Bytes = Flags.getByValSize();
3322 assert(FI != INT_MAX);
3323 if (!MFI->isFixedObjectIndex(FI))
3325 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3328 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3329 /// for tail call optimization. Targets which want to do tail call
3330 /// optimization should implement this function.
3332 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3333 CallingConv::ID CalleeCC,
3335 bool isCalleeStructRet,
3336 bool isCallerStructRet,
3338 const SmallVectorImpl<ISD::OutputArg> &Outs,
3339 const SmallVectorImpl<SDValue> &OutVals,
3340 const SmallVectorImpl<ISD::InputArg> &Ins,
3341 SelectionDAG &DAG) const {
3342 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3345 // If -tailcallopt is specified, make fastcc functions tail-callable.
3346 const MachineFunction &MF = DAG.getMachineFunction();
3347 const Function *CallerF = MF.getFunction();
3349 // If the function return type is x86_fp80 and the callee return type is not,
3350 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3351 // perform a tailcall optimization here.
3352 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3355 CallingConv::ID CallerCC = CallerF->getCallingConv();
3356 bool CCMatch = CallerCC == CalleeCC;
3357 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3358 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3360 // Win64 functions have extra shadow space for argument homing. Don't do the
3361 // sibcall if the caller and callee have mismatched expectations for this
3363 if (IsCalleeWin64 != IsCallerWin64)
3366 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3367 if (IsTailCallConvention(CalleeCC) && CCMatch)
3372 // Look for obvious safe cases to perform tail call optimization that do not
3373 // require ABI changes. This is what gcc calls sibcall.
3375 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3376 // emit a special epilogue.
3377 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3378 if (RegInfo->needsStackRealignment(MF))
3381 // Also avoid sibcall optimization if either caller or callee uses struct
3382 // return semantics.
3383 if (isCalleeStructRet || isCallerStructRet)
3386 // An stdcall/thiscall caller is expected to clean up its arguments; the
3387 // callee isn't going to do that.
3388 // FIXME: this is more restrictive than needed. We could produce a tailcall
3389 // when the stack adjustment matches. For example, with a thiscall that takes
3390 // only one argument.
3391 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3392 CallerCC == CallingConv::X86_ThisCall))
3395 // Do not sibcall optimize vararg calls unless all arguments are passed via
3397 if (isVarArg && !Outs.empty()) {
3399 // Optimizing for varargs on Win64 is unlikely to be safe without
3400 // additional testing.
3401 if (IsCalleeWin64 || IsCallerWin64)
3404 SmallVector<CCValAssign, 16> ArgLocs;
3405 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3408 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3409 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3410 if (!ArgLocs[i].isRegLoc())
3414 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3415 // stack. Therefore, if it's not used by the call it is not safe to optimize
3416 // this into a sibcall.
3417 bool Unused = false;
3418 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3425 SmallVector<CCValAssign, 16> RVLocs;
3426 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3428 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3429 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3430 CCValAssign &VA = RVLocs[i];
3431 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3436 // If the calling conventions do not match, then we'd better make sure the
3437 // results are returned in the same way as what the caller expects.
3439 SmallVector<CCValAssign, 16> RVLocs1;
3440 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3442 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3444 SmallVector<CCValAssign, 16> RVLocs2;
3445 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3447 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3449 if (RVLocs1.size() != RVLocs2.size())
3451 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3452 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3454 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3456 if (RVLocs1[i].isRegLoc()) {
3457 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3460 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3466 // If the callee takes no arguments then go on to check the results of the
3468 if (!Outs.empty()) {
3469 // Check if stack adjustment is needed. For now, do not do this if any
3470 // argument is passed on the stack.
3471 SmallVector<CCValAssign, 16> ArgLocs;
3472 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3475 // Allocate shadow area for Win64
3477 CCInfo.AllocateStack(32, 8);
3479 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3480 if (CCInfo.getNextStackOffset()) {
3481 MachineFunction &MF = DAG.getMachineFunction();
3482 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3485 // Check if the arguments are already laid out in the right way as
3486 // the caller's fixed stack objects.
3487 MachineFrameInfo *MFI = MF.getFrameInfo();
3488 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3489 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3490 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3491 CCValAssign &VA = ArgLocs[i];
3492 SDValue Arg = OutVals[i];
3493 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3494 if (VA.getLocInfo() == CCValAssign::Indirect)
3496 if (!VA.isRegLoc()) {
3497 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3504 // If the tailcall address may be in a register, then make sure it's
3505 // possible to register allocate for it. In 32-bit, the call address can
3506 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3507 // callee-saved registers are restored. These happen to be the same
3508 // registers used to pass 'inreg' arguments so watch out for those.
3509 if (!Subtarget->is64Bit() &&
3510 ((!isa<GlobalAddressSDNode>(Callee) &&
3511 !isa<ExternalSymbolSDNode>(Callee)) ||
3512 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3513 unsigned NumInRegs = 0;
3514 // In PIC we need an extra register to formulate the address computation
3516 unsigned MaxInRegs =
3517 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3519 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3520 CCValAssign &VA = ArgLocs[i];
3523 unsigned Reg = VA.getLocReg();
3526 case X86::EAX: case X86::EDX: case X86::ECX:
3527 if (++NumInRegs == MaxInRegs)
3539 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3540 const TargetLibraryInfo *libInfo) const {
3541 return X86::createFastISel(funcInfo, libInfo);
3544 //===----------------------------------------------------------------------===//
3545 // Other Lowering Hooks
3546 //===----------------------------------------------------------------------===//
3548 static bool MayFoldLoad(SDValue Op) {
3549 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3552 static bool MayFoldIntoStore(SDValue Op) {
3553 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3556 static bool isTargetShuffle(unsigned Opcode) {
3558 default: return false;
3559 case X86ISD::BLENDI:
3560 case X86ISD::PSHUFB:
3561 case X86ISD::PSHUFD:
3562 case X86ISD::PSHUFHW:
3563 case X86ISD::PSHUFLW:
3565 case X86ISD::PALIGNR:
3566 case X86ISD::MOVLHPS:
3567 case X86ISD::MOVLHPD:
3568 case X86ISD::MOVHLPS:
3569 case X86ISD::MOVLPS:
3570 case X86ISD::MOVLPD:
3571 case X86ISD::MOVSHDUP:
3572 case X86ISD::MOVSLDUP:
3573 case X86ISD::MOVDDUP:
3576 case X86ISD::UNPCKL:
3577 case X86ISD::UNPCKH:
3578 case X86ISD::VPERMILPI:
3579 case X86ISD::VPERM2X128:
3580 case X86ISD::VPERMI:
3585 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3586 SDValue V1, unsigned TargetMask,
3587 SelectionDAG &DAG) {
3589 default: llvm_unreachable("Unknown x86 shuffle node");
3590 case X86ISD::PSHUFD:
3591 case X86ISD::PSHUFHW:
3592 case X86ISD::PSHUFLW:
3593 case X86ISD::VPERMILPI:
3594 case X86ISD::VPERMI:
3595 return DAG.getNode(Opc, dl, VT, V1,
3596 DAG.getConstant(TargetMask, dl, MVT::i8));
3600 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3601 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3603 default: llvm_unreachable("Unknown x86 shuffle node");
3604 case X86ISD::MOVLHPS:
3605 case X86ISD::MOVLHPD:
3606 case X86ISD::MOVHLPS:
3607 case X86ISD::MOVLPS:
3608 case X86ISD::MOVLPD:
3611 case X86ISD::UNPCKL:
3612 case X86ISD::UNPCKH:
3613 return DAG.getNode(Opc, dl, VT, V1, V2);
3617 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3618 MachineFunction &MF = DAG.getMachineFunction();
3619 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3620 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3621 int ReturnAddrIndex = FuncInfo->getRAIndex();
3623 if (ReturnAddrIndex == 0) {
3624 // Set up a frame object for the return address.
3625 unsigned SlotSize = RegInfo->getSlotSize();
3626 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3629 FuncInfo->setRAIndex(ReturnAddrIndex);
3632 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3635 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3636 bool hasSymbolicDisplacement) {
3637 // Offset should fit into 32 bit immediate field.
3638 if (!isInt<32>(Offset))
3641 // If we don't have a symbolic displacement - we don't have any extra
3643 if (!hasSymbolicDisplacement)
3646 // FIXME: Some tweaks might be needed for medium code model.
3647 if (M != CodeModel::Small && M != CodeModel::Kernel)
3650 // For small code model we assume that latest object is 16MB before end of 31
3651 // bits boundary. We may also accept pretty large negative constants knowing
3652 // that all objects are in the positive half of address space.
3653 if (M == CodeModel::Small && Offset < 16*1024*1024)
3656 // For kernel code model we know that all object resist in the negative half
3657 // of 32bits address space. We may not accept negative offsets, since they may
3658 // be just off and we may accept pretty large positive ones.
3659 if (M == CodeModel::Kernel && Offset >= 0)
3665 /// isCalleePop - Determines whether the callee is required to pop its
3666 /// own arguments. Callee pop is necessary to support tail calls.
3667 bool X86::isCalleePop(CallingConv::ID CallingConv,
3668 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3669 switch (CallingConv) {
3672 case CallingConv::X86_StdCall:
3673 case CallingConv::X86_FastCall:
3674 case CallingConv::X86_ThisCall:
3676 case CallingConv::Fast:
3677 case CallingConv::GHC:
3678 case CallingConv::HiPE:
3685 /// \brief Return true if the condition is an unsigned comparison operation.
3686 static bool isX86CCUnsigned(unsigned X86CC) {
3688 default: llvm_unreachable("Invalid integer condition!");
3689 case X86::COND_E: return true;
3690 case X86::COND_G: return false;
3691 case X86::COND_GE: return false;
3692 case X86::COND_L: return false;
3693 case X86::COND_LE: return false;
3694 case X86::COND_NE: return true;
3695 case X86::COND_B: return true;
3696 case X86::COND_A: return true;
3697 case X86::COND_BE: return true;
3698 case X86::COND_AE: return true;
3700 llvm_unreachable("covered switch fell through?!");
3703 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3704 /// specific condition code, returning the condition code and the LHS/RHS of the
3705 /// comparison to make.
3706 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3707 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3709 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3710 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3711 // X > -1 -> X == 0, jump !sign.
3712 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3713 return X86::COND_NS;
3715 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3716 // X < 0 -> X == 0, jump on sign.
3719 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3721 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3722 return X86::COND_LE;
3726 switch (SetCCOpcode) {
3727 default: llvm_unreachable("Invalid integer condition!");
3728 case ISD::SETEQ: return X86::COND_E;
3729 case ISD::SETGT: return X86::COND_G;
3730 case ISD::SETGE: return X86::COND_GE;
3731 case ISD::SETLT: return X86::COND_L;
3732 case ISD::SETLE: return X86::COND_LE;
3733 case ISD::SETNE: return X86::COND_NE;
3734 case ISD::SETULT: return X86::COND_B;
3735 case ISD::SETUGT: return X86::COND_A;
3736 case ISD::SETULE: return X86::COND_BE;
3737 case ISD::SETUGE: return X86::COND_AE;
3741 // First determine if it is required or is profitable to flip the operands.
3743 // If LHS is a foldable load, but RHS is not, flip the condition.
3744 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3745 !ISD::isNON_EXTLoad(RHS.getNode())) {
3746 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3747 std::swap(LHS, RHS);
3750 switch (SetCCOpcode) {
3756 std::swap(LHS, RHS);
3760 // On a floating point condition, the flags are set as follows:
3762 // 0 | 0 | 0 | X > Y
3763 // 0 | 0 | 1 | X < Y
3764 // 1 | 0 | 0 | X == Y
3765 // 1 | 1 | 1 | unordered
3766 switch (SetCCOpcode) {
3767 default: llvm_unreachable("Condcode should be pre-legalized away");
3769 case ISD::SETEQ: return X86::COND_E;
3770 case ISD::SETOLT: // flipped
3772 case ISD::SETGT: return X86::COND_A;
3773 case ISD::SETOLE: // flipped
3775 case ISD::SETGE: return X86::COND_AE;
3776 case ISD::SETUGT: // flipped
3778 case ISD::SETLT: return X86::COND_B;
3779 case ISD::SETUGE: // flipped
3781 case ISD::SETLE: return X86::COND_BE;
3783 case ISD::SETNE: return X86::COND_NE;
3784 case ISD::SETUO: return X86::COND_P;
3785 case ISD::SETO: return X86::COND_NP;
3787 case ISD::SETUNE: return X86::COND_INVALID;
3791 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3792 /// code. Current x86 isa includes the following FP cmov instructions:
3793 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3794 static bool hasFPCMov(unsigned X86CC) {
3810 /// isFPImmLegal - Returns true if the target can instruction select the
3811 /// specified FP immediate natively. If false, the legalizer will
3812 /// materialize the FP immediate as a load from a constant pool.
3813 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3814 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3815 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3821 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3822 ISD::LoadExtType ExtTy,
3824 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3825 // relocation target a movq or addq instruction: don't let the load shrink.
3826 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3827 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3828 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3829 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3833 /// \brief Returns true if it is beneficial to convert a load of a constant
3834 /// to just the constant itself.
3835 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3837 assert(Ty->isIntegerTy());
3839 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3840 if (BitSize == 0 || BitSize > 64)
3845 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3846 unsigned Index) const {
3847 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3850 return (Index == 0 || Index == ResVT.getVectorNumElements());
3853 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3854 // Speculate cttz only if we can directly use TZCNT.
3855 return Subtarget->hasBMI();
3858 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3859 // Speculate ctlz only if we can directly use LZCNT.
3860 return Subtarget->hasLZCNT();
3863 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3864 /// the specified range (L, H].
3865 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3866 return (Val < 0) || (Val >= Low && Val < Hi);
3869 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3870 /// specified value.
3871 static bool isUndefOrEqual(int Val, int CmpVal) {
3872 return (Val < 0 || Val == CmpVal);
3875 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3876 /// from position Pos and ending in Pos+Size, falls within the specified
3877 /// sequential range (Low, Low+Size]. or is undef.
3878 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3879 unsigned Pos, unsigned Size, int Low) {
3880 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3881 if (!isUndefOrEqual(Mask[i], Low))
3886 /// isVEXTRACTIndex - Return true if the specified
3887 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3888 /// suitable for instruction that extract 128 or 256 bit vectors
3889 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3890 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3891 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3894 // The index should be aligned on a vecWidth-bit boundary.
3896 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3898 MVT VT = N->getSimpleValueType(0);
3899 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3900 bool Result = (Index * ElSize) % vecWidth == 0;
3905 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3906 /// operand specifies a subvector insert that is suitable for input to
3907 /// insertion of 128 or 256-bit subvectors
3908 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3909 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3910 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3912 // The index should be aligned on a vecWidth-bit boundary.
3914 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3916 MVT VT = N->getSimpleValueType(0);
3917 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3918 bool Result = (Index * ElSize) % vecWidth == 0;
3923 bool X86::isVINSERT128Index(SDNode *N) {
3924 return isVINSERTIndex(N, 128);
3927 bool X86::isVINSERT256Index(SDNode *N) {
3928 return isVINSERTIndex(N, 256);
3931 bool X86::isVEXTRACT128Index(SDNode *N) {
3932 return isVEXTRACTIndex(N, 128);
3935 bool X86::isVEXTRACT256Index(SDNode *N) {
3936 return isVEXTRACTIndex(N, 256);
3939 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3940 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3941 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3942 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3945 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3947 MVT VecVT = N->getOperand(0).getSimpleValueType();
3948 MVT ElVT = VecVT.getVectorElementType();
3950 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3951 return Index / NumElemsPerChunk;
3954 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3955 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3956 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3957 llvm_unreachable("Illegal insert subvector for VINSERT");
3960 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3962 MVT VecVT = N->getSimpleValueType(0);
3963 MVT ElVT = VecVT.getVectorElementType();
3965 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3966 return Index / NumElemsPerChunk;
3969 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3970 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3971 /// and VINSERTI128 instructions.
3972 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3973 return getExtractVEXTRACTImmediate(N, 128);
3976 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3977 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3978 /// and VINSERTI64x4 instructions.
3979 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3980 return getExtractVEXTRACTImmediate(N, 256);
3983 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3984 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3985 /// and VINSERTI128 instructions.
3986 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3987 return getInsertVINSERTImmediate(N, 128);
3990 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3991 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3992 /// and VINSERTI64x4 instructions.
3993 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3994 return getInsertVINSERTImmediate(N, 256);
3997 /// isZero - Returns true if Elt is a constant integer zero
3998 static bool isZero(SDValue V) {
3999 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4000 return C && C->isNullValue();
4003 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4005 bool X86::isZeroNode(SDValue Elt) {
4008 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4009 return CFP->getValueAPF().isPosZero();
4013 /// getZeroVector - Returns a vector of specified type with all zero elements.
4015 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4016 SelectionDAG &DAG, SDLoc dl) {
4017 assert(VT.isVector() && "Expected a vector type");
4019 // Always build SSE zero vectors as <4 x i32> bitcasted
4020 // to their dest type. This ensures they get CSE'd.
4022 if (VT.is128BitVector()) { // SSE
4023 if (Subtarget->hasSSE2()) { // SSE2
4024 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4025 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4027 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4028 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4030 } else if (VT.is256BitVector()) { // AVX
4031 if (Subtarget->hasInt256()) { // AVX2
4032 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4033 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4034 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4036 // 256-bit logic and arithmetic instructions in AVX are all
4037 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4038 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4039 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4040 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4042 } else if (VT.is512BitVector()) { // AVX-512
4043 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4044 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4045 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4046 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4047 } else if (VT.getScalarType() == MVT::i1) {
4049 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4050 && "Unexpected vector type");
4051 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4052 && "Unexpected vector type");
4053 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4054 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4055 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4057 llvm_unreachable("Unexpected vector type");
4059 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4062 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4063 SelectionDAG &DAG, SDLoc dl,
4064 unsigned vectorWidth) {
4065 assert((vectorWidth == 128 || vectorWidth == 256) &&
4066 "Unsupported vector width");
4067 EVT VT = Vec.getValueType();
4068 EVT ElVT = VT.getVectorElementType();
4069 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4070 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4071 VT.getVectorNumElements()/Factor);
4073 // Extract from UNDEF is UNDEF.
4074 if (Vec.getOpcode() == ISD::UNDEF)
4075 return DAG.getUNDEF(ResultVT);
4077 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4078 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4080 // This is the index of the first element of the vectorWidth-bit chunk
4082 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4085 // If the input is a buildvector just emit a smaller one.
4086 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4087 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4088 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4091 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4092 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4095 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4096 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4097 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4098 /// instructions or a simple subregister reference. Idx is an index in the
4099 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4100 /// lowering EXTRACT_VECTOR_ELT operations easier.
4101 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4102 SelectionDAG &DAG, SDLoc dl) {
4103 assert((Vec.getValueType().is256BitVector() ||
4104 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4105 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4108 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4109 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4110 SelectionDAG &DAG, SDLoc dl) {
4111 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4112 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4115 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4116 unsigned IdxVal, SelectionDAG &DAG,
4117 SDLoc dl, unsigned vectorWidth) {
4118 assert((vectorWidth == 128 || vectorWidth == 256) &&
4119 "Unsupported vector width");
4120 // Inserting UNDEF is Result
4121 if (Vec.getOpcode() == ISD::UNDEF)
4123 EVT VT = Vec.getValueType();
4124 EVT ElVT = VT.getVectorElementType();
4125 EVT ResultVT = Result.getValueType();
4127 // Insert the relevant vectorWidth bits.
4128 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4130 // This is the index of the first element of the vectorWidth-bit chunk
4132 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4135 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4136 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4139 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4140 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4141 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4142 /// simple superregister reference. Idx is an index in the 128 bits
4143 /// we want. It need not be aligned to a 128-bit boundary. That makes
4144 /// lowering INSERT_VECTOR_ELT operations easier.
4145 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4146 SelectionDAG &DAG, SDLoc dl) {
4147 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4149 // For insertion into the zero index (low half) of a 256-bit vector, it is
4150 // more efficient to generate a blend with immediate instead of an insert*128.
4151 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4152 // extend the subvector to the size of the result vector. Make sure that
4153 // we are not recursing on that node by checking for undef here.
4154 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4155 Result.getOpcode() != ISD::UNDEF) {
4156 EVT ResultVT = Result.getValueType();
4157 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4158 SDValue Undef = DAG.getUNDEF(ResultVT);
4159 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4162 // The blend instruction, and therefore its mask, depend on the data type.
4163 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4164 if (ScalarType.isFloatingPoint()) {
4165 // Choose either vblendps (float) or vblendpd (double).
4166 unsigned ScalarSize = ScalarType.getSizeInBits();
4167 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4168 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4169 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4170 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4173 const X86Subtarget &Subtarget =
4174 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4176 // AVX2 is needed for 256-bit integer blend support.
4177 // Integers must be cast to 32-bit because there is only vpblendd;
4178 // vpblendw can't be used for this because it has a handicapped mask.
4180 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4181 // is still more efficient than using the wrong domain vinsertf128 that
4182 // will be created by InsertSubVector().
4183 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4185 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4186 Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4187 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4188 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4191 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4194 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4195 SelectionDAG &DAG, SDLoc dl) {
4196 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4197 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4200 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4201 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4202 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4203 /// large BUILD_VECTORS.
4204 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4205 unsigned NumElems, SelectionDAG &DAG,
4207 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4208 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4211 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4212 unsigned NumElems, SelectionDAG &DAG,
4214 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4215 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4218 /// getOnesVector - Returns a vector of specified type with all bits set.
4219 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4220 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4221 /// Then bitcast to their original type, ensuring they get CSE'd.
4222 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4224 assert(VT.isVector() && "Expected a vector type");
4226 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4228 if (VT.is256BitVector()) {
4229 if (HasInt256) { // AVX2
4230 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4231 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4233 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4234 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4236 } else if (VT.is128BitVector()) {
4237 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4239 llvm_unreachable("Unexpected vector type");
4241 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4244 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4245 /// operation of specified width.
4246 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4248 unsigned NumElems = VT.getVectorNumElements();
4249 SmallVector<int, 8> Mask;
4250 Mask.push_back(NumElems);
4251 for (unsigned i = 1; i != NumElems; ++i)
4253 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4256 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4257 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4259 unsigned NumElems = VT.getVectorNumElements();
4260 SmallVector<int, 8> Mask;
4261 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4263 Mask.push_back(i + NumElems);
4265 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4268 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4269 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4271 unsigned NumElems = VT.getVectorNumElements();
4272 SmallVector<int, 8> Mask;
4273 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4274 Mask.push_back(i + Half);
4275 Mask.push_back(i + NumElems + Half);
4277 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4280 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4281 /// vector of zero or undef vector. This produces a shuffle where the low
4282 /// element of V2 is swizzled into the zero/undef vector, landing at element
4283 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4284 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4286 const X86Subtarget *Subtarget,
4287 SelectionDAG &DAG) {
4288 MVT VT = V2.getSimpleValueType();
4290 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4291 unsigned NumElems = VT.getVectorNumElements();
4292 SmallVector<int, 16> MaskVec;
4293 for (unsigned i = 0; i != NumElems; ++i)
4294 // If this is the insertion idx, put the low elt of V2 here.
4295 MaskVec.push_back(i == Idx ? NumElems : i);
4296 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4299 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4300 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4301 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4302 /// shuffles which use a single input multiple times, and in those cases it will
4303 /// adjust the mask to only have indices within that single input.
4304 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4305 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4306 unsigned NumElems = VT.getVectorNumElements();
4310 bool IsFakeUnary = false;
4311 switch(N->getOpcode()) {
4312 case X86ISD::BLENDI:
4313 ImmN = N->getOperand(N->getNumOperands()-1);
4314 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4317 ImmN = N->getOperand(N->getNumOperands()-1);
4318 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4319 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4321 case X86ISD::UNPCKH:
4322 DecodeUNPCKHMask(VT, Mask);
4323 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4325 case X86ISD::UNPCKL:
4326 DecodeUNPCKLMask(VT, Mask);
4327 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4329 case X86ISD::MOVHLPS:
4330 DecodeMOVHLPSMask(NumElems, Mask);
4331 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4333 case X86ISD::MOVLHPS:
4334 DecodeMOVLHPSMask(NumElems, Mask);
4335 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4337 case X86ISD::PALIGNR:
4338 ImmN = N->getOperand(N->getNumOperands()-1);
4339 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4341 case X86ISD::PSHUFD:
4342 case X86ISD::VPERMILPI:
4343 ImmN = N->getOperand(N->getNumOperands()-1);
4344 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4347 case X86ISD::PSHUFHW:
4348 ImmN = N->getOperand(N->getNumOperands()-1);
4349 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4352 case X86ISD::PSHUFLW:
4353 ImmN = N->getOperand(N->getNumOperands()-1);
4354 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4357 case X86ISD::PSHUFB: {
4359 SDValue MaskNode = N->getOperand(1);
4360 while (MaskNode->getOpcode() == ISD::BITCAST)
4361 MaskNode = MaskNode->getOperand(0);
4363 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4364 // If we have a build-vector, then things are easy.
4365 EVT VT = MaskNode.getValueType();
4366 assert(VT.isVector() &&
4367 "Can't produce a non-vector with a build_vector!");
4368 if (!VT.isInteger())
4371 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4373 SmallVector<uint64_t, 32> RawMask;
4374 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4375 SDValue Op = MaskNode->getOperand(i);
4376 if (Op->getOpcode() == ISD::UNDEF) {
4377 RawMask.push_back((uint64_t)SM_SentinelUndef);
4380 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4383 APInt MaskElement = CN->getAPIntValue();
4385 // We now have to decode the element which could be any integer size and
4386 // extract each byte of it.
4387 for (int j = 0; j < NumBytesPerElement; ++j) {
4388 // Note that this is x86 and so always little endian: the low byte is
4389 // the first byte of the mask.
4390 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4391 MaskElement = MaskElement.lshr(8);
4394 DecodePSHUFBMask(RawMask, Mask);
4398 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4402 SDValue Ptr = MaskLoad->getBasePtr();
4403 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4404 Ptr->getOpcode() == X86ISD::WrapperRIP)
4405 Ptr = Ptr->getOperand(0);
4407 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4408 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4411 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4412 DecodePSHUFBMask(C, Mask);
4420 case X86ISD::VPERMI:
4421 ImmN = N->getOperand(N->getNumOperands()-1);
4422 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4427 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4429 case X86ISD::VPERM2X128:
4430 ImmN = N->getOperand(N->getNumOperands()-1);
4431 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4432 if (Mask.empty()) return false;
4434 case X86ISD::MOVSLDUP:
4435 DecodeMOVSLDUPMask(VT, Mask);
4438 case X86ISD::MOVSHDUP:
4439 DecodeMOVSHDUPMask(VT, Mask);
4442 case X86ISD::MOVDDUP:
4443 DecodeMOVDDUPMask(VT, Mask);
4446 case X86ISD::MOVLHPD:
4447 case X86ISD::MOVLPD:
4448 case X86ISD::MOVLPS:
4449 // Not yet implemented
4451 default: llvm_unreachable("unknown target shuffle node");
4454 // If we have a fake unary shuffle, the shuffle mask is spread across two
4455 // inputs that are actually the same node. Re-map the mask to always point
4456 // into the first input.
4459 if (M >= (int)Mask.size())
4465 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4466 /// element of the result of the vector shuffle.
4467 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4470 return SDValue(); // Limit search depth.
4472 SDValue V = SDValue(N, 0);
4473 EVT VT = V.getValueType();
4474 unsigned Opcode = V.getOpcode();
4476 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4477 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4478 int Elt = SV->getMaskElt(Index);
4481 return DAG.getUNDEF(VT.getVectorElementType());
4483 unsigned NumElems = VT.getVectorNumElements();
4484 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4485 : SV->getOperand(1);
4486 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4489 // Recurse into target specific vector shuffles to find scalars.
4490 if (isTargetShuffle(Opcode)) {
4491 MVT ShufVT = V.getSimpleValueType();
4492 unsigned NumElems = ShufVT.getVectorNumElements();
4493 SmallVector<int, 16> ShuffleMask;
4496 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4499 int Elt = ShuffleMask[Index];
4501 return DAG.getUNDEF(ShufVT.getVectorElementType());
4503 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4505 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4509 // Actual nodes that may contain scalar elements
4510 if (Opcode == ISD::BITCAST) {
4511 V = V.getOperand(0);
4512 EVT SrcVT = V.getValueType();
4513 unsigned NumElems = VT.getVectorNumElements();
4515 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4519 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4520 return (Index == 0) ? V.getOperand(0)
4521 : DAG.getUNDEF(VT.getVectorElementType());
4523 if (V.getOpcode() == ISD::BUILD_VECTOR)
4524 return V.getOperand(Index);
4529 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4531 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4532 unsigned NumNonZero, unsigned NumZero,
4534 const X86Subtarget* Subtarget,
4535 const TargetLowering &TLI) {
4543 // SSE4.1 - use PINSRB to insert each byte directly.
4544 if (Subtarget->hasSSE41()) {
4545 for (unsigned i = 0; i < 16; ++i) {
4546 bool isNonZero = (NonZeros & (1 << i)) != 0;
4550 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4552 V = DAG.getUNDEF(MVT::v16i8);
4555 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4556 MVT::v16i8, V, Op.getOperand(i),
4557 DAG.getIntPtrConstant(i, dl));
4564 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4565 for (unsigned i = 0; i < 16; ++i) {
4566 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4567 if (ThisIsNonZero && First) {
4569 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4571 V = DAG.getUNDEF(MVT::v8i16);
4576 SDValue ThisElt, LastElt;
4577 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4578 if (LastIsNonZero) {
4579 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4580 MVT::i16, Op.getOperand(i-1));
4582 if (ThisIsNonZero) {
4583 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4584 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4585 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4587 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4591 if (ThisElt.getNode())
4592 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4593 DAG.getIntPtrConstant(i/2, dl));
4597 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4600 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4602 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4603 unsigned NumNonZero, unsigned NumZero,
4605 const X86Subtarget* Subtarget,
4606 const TargetLowering &TLI) {
4613 for (unsigned i = 0; i < 8; ++i) {
4614 bool isNonZero = (NonZeros & (1 << i)) != 0;
4618 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4620 V = DAG.getUNDEF(MVT::v8i16);
4623 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4624 MVT::v8i16, V, Op.getOperand(i),
4625 DAG.getIntPtrConstant(i, dl));
4632 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4633 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4634 const X86Subtarget *Subtarget,
4635 const TargetLowering &TLI) {
4636 // Find all zeroable elements.
4637 std::bitset<4> Zeroable;
4638 for (int i=0; i < 4; ++i) {
4639 SDValue Elt = Op->getOperand(i);
4640 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4642 assert(Zeroable.size() - Zeroable.count() > 1 &&
4643 "We expect at least two non-zero elements!");
4645 // We only know how to deal with build_vector nodes where elements are either
4646 // zeroable or extract_vector_elt with constant index.
4647 SDValue FirstNonZero;
4648 unsigned FirstNonZeroIdx;
4649 for (unsigned i=0; i < 4; ++i) {
4652 SDValue Elt = Op->getOperand(i);
4653 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4654 !isa<ConstantSDNode>(Elt.getOperand(1)))
4656 // Make sure that this node is extracting from a 128-bit vector.
4657 MVT VT = Elt.getOperand(0).getSimpleValueType();
4658 if (!VT.is128BitVector())
4660 if (!FirstNonZero.getNode()) {
4662 FirstNonZeroIdx = i;
4666 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4667 SDValue V1 = FirstNonZero.getOperand(0);
4668 MVT VT = V1.getSimpleValueType();
4670 // See if this build_vector can be lowered as a blend with zero.
4672 unsigned EltMaskIdx, EltIdx;
4674 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4675 if (Zeroable[EltIdx]) {
4676 // The zero vector will be on the right hand side.
4677 Mask[EltIdx] = EltIdx+4;
4681 Elt = Op->getOperand(EltIdx);
4682 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4683 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4684 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4686 Mask[EltIdx] = EltIdx;
4690 // Let the shuffle legalizer deal with blend operations.
4691 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4692 if (V1.getSimpleValueType() != VT)
4693 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4694 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4697 // See if we can lower this build_vector to a INSERTPS.
4698 if (!Subtarget->hasSSE41())
4701 SDValue V2 = Elt.getOperand(0);
4702 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4705 bool CanFold = true;
4706 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4710 SDValue Current = Op->getOperand(i);
4711 SDValue SrcVector = Current->getOperand(0);
4714 CanFold = SrcVector == V1 &&
4715 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4721 assert(V1.getNode() && "Expected at least two non-zero elements!");
4722 if (V1.getSimpleValueType() != MVT::v4f32)
4723 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4724 if (V2.getSimpleValueType() != MVT::v4f32)
4725 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4727 // Ok, we can emit an INSERTPS instruction.
4728 unsigned ZMask = Zeroable.to_ulong();
4730 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4731 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4733 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4734 DAG.getIntPtrConstant(InsertPSMask, DL));
4735 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4738 /// Return a vector logical shift node.
4739 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4740 unsigned NumBits, SelectionDAG &DAG,
4741 const TargetLowering &TLI, SDLoc dl) {
4742 assert(VT.is128BitVector() && "Unknown type for VShift");
4743 MVT ShVT = MVT::v2i64;
4744 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4745 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4746 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4747 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4748 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4749 return DAG.getNode(ISD::BITCAST, dl, VT,
4750 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4754 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4756 // Check if the scalar load can be widened into a vector load. And if
4757 // the address is "base + cst" see if the cst can be "absorbed" into
4758 // the shuffle mask.
4759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4760 SDValue Ptr = LD->getBasePtr();
4761 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4763 EVT PVT = LD->getValueType(0);
4764 if (PVT != MVT::i32 && PVT != MVT::f32)
4769 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4770 FI = FINode->getIndex();
4772 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4773 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4774 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4775 Offset = Ptr.getConstantOperandVal(1);
4776 Ptr = Ptr.getOperand(0);
4781 // FIXME: 256-bit vector instructions don't require a strict alignment,
4782 // improve this code to support it better.
4783 unsigned RequiredAlign = VT.getSizeInBits()/8;
4784 SDValue Chain = LD->getChain();
4785 // Make sure the stack object alignment is at least 16 or 32.
4786 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4787 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4788 if (MFI->isFixedObjectIndex(FI)) {
4789 // Can't change the alignment. FIXME: It's possible to compute
4790 // the exact stack offset and reference FI + adjust offset instead.
4791 // If someone *really* cares about this. That's the way to implement it.
4794 MFI->setObjectAlignment(FI, RequiredAlign);
4798 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4799 // Ptr + (Offset & ~15).
4802 if ((Offset % RequiredAlign) & 3)
4804 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4807 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4808 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4811 int EltNo = (Offset - StartOffset) >> 2;
4812 unsigned NumElems = VT.getVectorNumElements();
4814 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4815 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4816 LD->getPointerInfo().getWithOffset(StartOffset),
4817 false, false, false, 0);
4819 SmallVector<int, 8> Mask(NumElems, EltNo);
4821 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4827 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4828 /// elements can be replaced by a single large load which has the same value as
4829 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4831 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4833 /// FIXME: we'd also like to handle the case where the last elements are zero
4834 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4835 /// There's even a handy isZeroNode for that purpose.
4836 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4837 SDLoc &DL, SelectionDAG &DAG,
4838 bool isAfterLegalize) {
4839 unsigned NumElems = Elts.size();
4841 LoadSDNode *LDBase = nullptr;
4842 unsigned LastLoadedElt = -1U;
4844 // For each element in the initializer, see if we've found a load or an undef.
4845 // If we don't find an initial load element, or later load elements are
4846 // non-consecutive, bail out.
4847 for (unsigned i = 0; i < NumElems; ++i) {
4848 SDValue Elt = Elts[i];
4849 // Look through a bitcast.
4850 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4851 Elt = Elt.getOperand(0);
4852 if (!Elt.getNode() ||
4853 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4856 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4858 LDBase = cast<LoadSDNode>(Elt.getNode());
4862 if (Elt.getOpcode() == ISD::UNDEF)
4865 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4866 EVT LdVT = Elt.getValueType();
4867 // Each loaded element must be the correct fractional portion of the
4868 // requested vector load.
4869 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4871 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4876 // If we have found an entire vector of loads and undefs, then return a large
4877 // load of the entire vector width starting at the base pointer. If we found
4878 // consecutive loads for the low half, generate a vzext_load node.
4879 if (LastLoadedElt == NumElems - 1) {
4880 assert(LDBase && "Did not find base load for merging consecutive loads");
4881 EVT EltVT = LDBase->getValueType(0);
4882 // Ensure that the input vector size for the merged loads matches the
4883 // cumulative size of the input elements.
4884 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4887 if (isAfterLegalize &&
4888 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4891 SDValue NewLd = SDValue();
4893 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4894 LDBase->getPointerInfo(), LDBase->isVolatile(),
4895 LDBase->isNonTemporal(), LDBase->isInvariant(),
4896 LDBase->getAlignment());
4898 if (LDBase->hasAnyUseOfValue(1)) {
4899 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4901 SDValue(NewLd.getNode(), 1));
4902 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4903 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4904 SDValue(NewLd.getNode(), 1));
4910 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4911 //of a v4i32 / v4f32. It's probably worth generalizing.
4912 EVT EltVT = VT.getVectorElementType();
4913 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4914 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4915 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4916 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4918 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4919 LDBase->getPointerInfo(),
4920 LDBase->getAlignment(),
4921 false/*isVolatile*/, true/*ReadMem*/,
4924 // Make sure the newly-created LOAD is in the same position as LDBase in
4925 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4926 // update uses of LDBase's output chain to use the TokenFactor.
4927 if (LDBase->hasAnyUseOfValue(1)) {
4928 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4929 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4930 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4931 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4932 SDValue(ResNode.getNode(), 1));
4935 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4940 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4941 /// to generate a splat value for the following cases:
4942 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4943 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4944 /// a scalar load, or a constant.
4945 /// The VBROADCAST node is returned when a pattern is found,
4946 /// or SDValue() otherwise.
4947 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4948 SelectionDAG &DAG) {
4949 // VBROADCAST requires AVX.
4950 // TODO: Splats could be generated for non-AVX CPUs using SSE
4951 // instructions, but there's less potential gain for only 128-bit vectors.
4952 if (!Subtarget->hasAVX())
4955 MVT VT = Op.getSimpleValueType();
4958 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4959 "Unsupported vector type for broadcast.");
4964 switch (Op.getOpcode()) {
4966 // Unknown pattern found.
4969 case ISD::BUILD_VECTOR: {
4970 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4971 BitVector UndefElements;
4972 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4974 // We need a splat of a single value to use broadcast, and it doesn't
4975 // make any sense if the value is only in one element of the vector.
4976 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4980 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4981 Ld.getOpcode() == ISD::ConstantFP);
4983 // Make sure that all of the users of a non-constant load are from the
4984 // BUILD_VECTOR node.
4985 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4990 case ISD::VECTOR_SHUFFLE: {
4991 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4993 // Shuffles must have a splat mask where the first element is
4995 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4998 SDValue Sc = Op.getOperand(0);
4999 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5000 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5002 if (!Subtarget->hasInt256())
5005 // Use the register form of the broadcast instruction available on AVX2.
5006 if (VT.getSizeInBits() >= 256)
5007 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5008 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5011 Ld = Sc.getOperand(0);
5012 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5013 Ld.getOpcode() == ISD::ConstantFP);
5015 // The scalar_to_vector node and the suspected
5016 // load node must have exactly one user.
5017 // Constants may have multiple users.
5019 // AVX-512 has register version of the broadcast
5020 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5021 Ld.getValueType().getSizeInBits() >= 32;
5022 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5029 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5030 bool IsGE256 = (VT.getSizeInBits() >= 256);
5032 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5033 // instruction to save 8 or more bytes of constant pool data.
5034 // TODO: If multiple splats are generated to load the same constant,
5035 // it may be detrimental to overall size. There needs to be a way to detect
5036 // that condition to know if this is truly a size win.
5037 const Function *F = DAG.getMachineFunction().getFunction();
5038 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5040 // Handle broadcasting a single constant scalar from the constant pool
5042 // On Sandybridge (no AVX2), it is still better to load a constant vector
5043 // from the constant pool and not to broadcast it from a scalar.
5044 // But override that restriction when optimizing for size.
5045 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5046 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5047 EVT CVT = Ld.getValueType();
5048 assert(!CVT.isVector() && "Must not broadcast a vector type");
5050 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5051 // For size optimization, also splat v2f64 and v2i64, and for size opt
5052 // with AVX2, also splat i8 and i16.
5053 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5054 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5055 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5056 const Constant *C = nullptr;
5057 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5058 C = CI->getConstantIntValue();
5059 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5060 C = CF->getConstantFPValue();
5062 assert(C && "Invalid constant type");
5064 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5065 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5066 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5067 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5068 MachinePointerInfo::getConstantPool(),
5069 false, false, false, Alignment);
5071 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5075 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5077 // Handle AVX2 in-register broadcasts.
5078 if (!IsLoad && Subtarget->hasInt256() &&
5079 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5080 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5082 // The scalar source must be a normal load.
5086 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5087 (Subtarget->hasVLX() && ScalarSize == 64))
5088 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5090 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5091 // double since there is no vbroadcastsd xmm
5092 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5093 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5094 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5097 // Unsupported broadcast.
5101 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5102 /// underlying vector and index.
5104 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5106 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5108 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5109 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5112 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5114 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5116 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5117 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5120 // In this case the vector is the extract_subvector expression and the index
5121 // is 2, as specified by the shuffle.
5122 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5123 SDValue ShuffleVec = SVOp->getOperand(0);
5124 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5125 assert(ShuffleVecVT.getVectorElementType() ==
5126 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5128 int ShuffleIdx = SVOp->getMaskElt(Idx);
5129 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5130 ExtractedFromVec = ShuffleVec;
5136 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5137 MVT VT = Op.getSimpleValueType();
5139 // Skip if insert_vec_elt is not supported.
5140 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5141 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5145 unsigned NumElems = Op.getNumOperands();
5149 SmallVector<unsigned, 4> InsertIndices;
5150 SmallVector<int, 8> Mask(NumElems, -1);
5152 for (unsigned i = 0; i != NumElems; ++i) {
5153 unsigned Opc = Op.getOperand(i).getOpcode();
5155 if (Opc == ISD::UNDEF)
5158 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5159 // Quit if more than 1 elements need inserting.
5160 if (InsertIndices.size() > 1)
5163 InsertIndices.push_back(i);
5167 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5168 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5169 // Quit if non-constant index.
5170 if (!isa<ConstantSDNode>(ExtIdx))
5172 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5174 // Quit if extracted from vector of different type.
5175 if (ExtractedFromVec.getValueType() != VT)
5178 if (!VecIn1.getNode())
5179 VecIn1 = ExtractedFromVec;
5180 else if (VecIn1 != ExtractedFromVec) {
5181 if (!VecIn2.getNode())
5182 VecIn2 = ExtractedFromVec;
5183 else if (VecIn2 != ExtractedFromVec)
5184 // Quit if more than 2 vectors to shuffle
5188 if (ExtractedFromVec == VecIn1)
5190 else if (ExtractedFromVec == VecIn2)
5191 Mask[i] = Idx + NumElems;
5194 if (!VecIn1.getNode())
5197 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5198 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5199 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5200 unsigned Idx = InsertIndices[i];
5201 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5202 DAG.getIntPtrConstant(Idx, DL));
5208 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5209 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5210 Op.getScalarValueSizeInBits() == 1 &&
5211 "Can not convert non-constant vector");
5212 uint64_t Immediate = 0;
5213 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5214 SDValue In = Op.getOperand(idx);
5215 if (In.getOpcode() != ISD::UNDEF)
5216 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5220 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5221 return DAG.getConstant(Immediate, dl, VT);
5223 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5225 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5227 MVT VT = Op.getSimpleValueType();
5228 assert((VT.getVectorElementType() == MVT::i1) &&
5229 "Unexpected type in LowerBUILD_VECTORvXi1!");
5232 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5233 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5234 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5235 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5238 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5239 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5240 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5241 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5244 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5245 SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5246 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5247 return DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5248 SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5249 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5250 DAG.getIntPtrConstant(0, dl));
5253 // Vector has one or more non-const elements
5254 uint64_t Immediate = 0;
5255 SmallVector<unsigned, 16> NonConstIdx;
5256 bool IsSplat = true;
5257 bool HasConstElts = false;
5259 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5260 SDValue In = Op.getOperand(idx);
5261 if (In.getOpcode() == ISD::UNDEF)
5263 if (!isa<ConstantSDNode>(In))
5264 NonConstIdx.push_back(idx);
5266 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5267 HasConstElts = true;
5271 else if (In != Op.getOperand(SplatIdx))
5275 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5277 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5278 DAG.getConstant(1, dl, VT),
5279 DAG.getConstant(0, dl, VT));
5281 // insert elements one by one
5285 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5286 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5288 else if (HasConstElts)
5289 Imm = DAG.getConstant(0, dl, VT);
5291 Imm = DAG.getUNDEF(VT);
5292 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5293 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5295 SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5296 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5297 DAG.getIntPtrConstant(0, dl));
5300 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5301 unsigned InsertIdx = NonConstIdx[i];
5302 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5303 Op.getOperand(InsertIdx),
5304 DAG.getIntPtrConstant(InsertIdx, dl));
5309 /// \brief Return true if \p N implements a horizontal binop and return the
5310 /// operands for the horizontal binop into V0 and V1.
5312 /// This is a helper function of LowerToHorizontalOp().
5313 /// This function checks that the build_vector \p N in input implements a
5314 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5315 /// operation to match.
5316 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5317 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5318 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5321 /// This function only analyzes elements of \p N whose indices are
5322 /// in range [BaseIdx, LastIdx).
5323 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5325 unsigned BaseIdx, unsigned LastIdx,
5326 SDValue &V0, SDValue &V1) {
5327 EVT VT = N->getValueType(0);
5329 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5330 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5331 "Invalid Vector in input!");
5333 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5334 bool CanFold = true;
5335 unsigned ExpectedVExtractIdx = BaseIdx;
5336 unsigned NumElts = LastIdx - BaseIdx;
5337 V0 = DAG.getUNDEF(VT);
5338 V1 = DAG.getUNDEF(VT);
5340 // Check if N implements a horizontal binop.
5341 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5342 SDValue Op = N->getOperand(i + BaseIdx);
5345 if (Op->getOpcode() == ISD::UNDEF) {
5346 // Update the expected vector extract index.
5347 if (i * 2 == NumElts)
5348 ExpectedVExtractIdx = BaseIdx;
5349 ExpectedVExtractIdx += 2;
5353 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5358 SDValue Op0 = Op.getOperand(0);
5359 SDValue Op1 = Op.getOperand(1);
5361 // Try to match the following pattern:
5362 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5363 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5364 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5365 Op0.getOperand(0) == Op1.getOperand(0) &&
5366 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5367 isa<ConstantSDNode>(Op1.getOperand(1)));
5371 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5372 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5374 if (i * 2 < NumElts) {
5375 if (V0.getOpcode() == ISD::UNDEF) {
5376 V0 = Op0.getOperand(0);
5377 if (V0.getValueType() != VT)
5381 if (V1.getOpcode() == ISD::UNDEF) {
5382 V1 = Op0.getOperand(0);
5383 if (V1.getValueType() != VT)
5386 if (i * 2 == NumElts)
5387 ExpectedVExtractIdx = BaseIdx;
5390 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5391 if (I0 == ExpectedVExtractIdx)
5392 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5393 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5394 // Try to match the following dag sequence:
5395 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5396 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5400 ExpectedVExtractIdx += 2;
5406 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5407 /// a concat_vector.
5409 /// This is a helper function of LowerToHorizontalOp().
5410 /// This function expects two 256-bit vectors called V0 and V1.
5411 /// At first, each vector is split into two separate 128-bit vectors.
5412 /// Then, the resulting 128-bit vectors are used to implement two
5413 /// horizontal binary operations.
5415 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5417 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5418 /// the two new horizontal binop.
5419 /// When Mode is set, the first horizontal binop dag node would take as input
5420 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5421 /// horizontal binop dag node would take as input the lower 128-bit of V1
5422 /// and the upper 128-bit of V1.
5424 /// HADD V0_LO, V0_HI
5425 /// HADD V1_LO, V1_HI
5427 /// Otherwise, the first horizontal binop dag node takes as input the lower
5428 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5429 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5431 /// HADD V0_LO, V1_LO
5432 /// HADD V0_HI, V1_HI
5434 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5435 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5436 /// the upper 128-bits of the result.
5437 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5438 SDLoc DL, SelectionDAG &DAG,
5439 unsigned X86Opcode, bool Mode,
5440 bool isUndefLO, bool isUndefHI) {
5441 EVT VT = V0.getValueType();
5442 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5443 "Invalid nodes in input!");
5445 unsigned NumElts = VT.getVectorNumElements();
5446 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5447 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5448 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5449 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5450 EVT NewVT = V0_LO.getValueType();
5452 SDValue LO = DAG.getUNDEF(NewVT);
5453 SDValue HI = DAG.getUNDEF(NewVT);
5456 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5457 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5458 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5459 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5460 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5462 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5463 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5464 V1_LO->getOpcode() != ISD::UNDEF))
5465 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5467 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5468 V1_HI->getOpcode() != ISD::UNDEF))
5469 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5472 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5475 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5477 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5478 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5479 EVT VT = BV->getValueType(0);
5480 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5481 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5485 unsigned NumElts = VT.getVectorNumElements();
5486 SDValue InVec0 = DAG.getUNDEF(VT);
5487 SDValue InVec1 = DAG.getUNDEF(VT);
5489 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5490 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5492 // Odd-numbered elements in the input build vector are obtained from
5493 // adding two integer/float elements.
5494 // Even-numbered elements in the input build vector are obtained from
5495 // subtracting two integer/float elements.
5496 unsigned ExpectedOpcode = ISD::FSUB;
5497 unsigned NextExpectedOpcode = ISD::FADD;
5498 bool AddFound = false;
5499 bool SubFound = false;
5501 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5502 SDValue Op = BV->getOperand(i);
5504 // Skip 'undef' values.
5505 unsigned Opcode = Op.getOpcode();
5506 if (Opcode == ISD::UNDEF) {
5507 std::swap(ExpectedOpcode, NextExpectedOpcode);
5511 // Early exit if we found an unexpected opcode.
5512 if (Opcode != ExpectedOpcode)
5515 SDValue Op0 = Op.getOperand(0);
5516 SDValue Op1 = Op.getOperand(1);
5518 // Try to match the following pattern:
5519 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5520 // Early exit if we cannot match that sequence.
5521 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5522 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5523 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5524 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5525 Op0.getOperand(1) != Op1.getOperand(1))
5528 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5532 // We found a valid add/sub node. Update the information accordingly.
5538 // Update InVec0 and InVec1.
5539 if (InVec0.getOpcode() == ISD::UNDEF) {
5540 InVec0 = Op0.getOperand(0);
5541 if (InVec0.getValueType() != VT)
5544 if (InVec1.getOpcode() == ISD::UNDEF) {
5545 InVec1 = Op1.getOperand(0);
5546 if (InVec1.getValueType() != VT)
5550 // Make sure that operands in input to each add/sub node always
5551 // come from a same pair of vectors.
5552 if (InVec0 != Op0.getOperand(0)) {
5553 if (ExpectedOpcode == ISD::FSUB)
5556 // FADD is commutable. Try to commute the operands
5557 // and then test again.
5558 std::swap(Op0, Op1);
5559 if (InVec0 != Op0.getOperand(0))
5563 if (InVec1 != Op1.getOperand(0))
5566 // Update the pair of expected opcodes.
5567 std::swap(ExpectedOpcode, NextExpectedOpcode);
5570 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5571 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5572 InVec1.getOpcode() != ISD::UNDEF)
5573 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5578 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5579 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5580 const X86Subtarget *Subtarget,
5581 SelectionDAG &DAG) {
5582 EVT VT = BV->getValueType(0);
5583 unsigned NumElts = VT.getVectorNumElements();
5584 unsigned NumUndefsLO = 0;
5585 unsigned NumUndefsHI = 0;
5586 unsigned Half = NumElts/2;
5588 // Count the number of UNDEF operands in the build_vector in input.
5589 for (unsigned i = 0, e = Half; i != e; ++i)
5590 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5593 for (unsigned i = Half, e = NumElts; i != e; ++i)
5594 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5597 // Early exit if this is either a build_vector of all UNDEFs or all the
5598 // operands but one are UNDEF.
5599 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5603 SDValue InVec0, InVec1;
5604 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5605 // Try to match an SSE3 float HADD/HSUB.
5606 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5607 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5609 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5610 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5611 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5612 // Try to match an SSSE3 integer HADD/HSUB.
5613 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5614 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5616 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5617 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5620 if (!Subtarget->hasAVX())
5623 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5624 // Try to match an AVX horizontal add/sub of packed single/double
5625 // precision floating point values from 256-bit vectors.
5626 SDValue InVec2, InVec3;
5627 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5628 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5629 ((InVec0.getOpcode() == ISD::UNDEF ||
5630 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5631 ((InVec1.getOpcode() == ISD::UNDEF ||
5632 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5633 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5635 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5636 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5637 ((InVec0.getOpcode() == ISD::UNDEF ||
5638 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5639 ((InVec1.getOpcode() == ISD::UNDEF ||
5640 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5641 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5642 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5643 // Try to match an AVX2 horizontal add/sub of signed integers.
5644 SDValue InVec2, InVec3;
5646 bool CanFold = true;
5648 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5649 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5650 ((InVec0.getOpcode() == ISD::UNDEF ||
5651 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5652 ((InVec1.getOpcode() == ISD::UNDEF ||
5653 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5654 X86Opcode = X86ISD::HADD;
5655 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5656 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5657 ((InVec0.getOpcode() == ISD::UNDEF ||
5658 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5659 ((InVec1.getOpcode() == ISD::UNDEF ||
5660 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5661 X86Opcode = X86ISD::HSUB;
5666 // Fold this build_vector into a single horizontal add/sub.
5667 // Do this only if the target has AVX2.
5668 if (Subtarget->hasAVX2())
5669 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5671 // Do not try to expand this build_vector into a pair of horizontal
5672 // add/sub if we can emit a pair of scalar add/sub.
5673 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5676 // Convert this build_vector into a pair of horizontal binop followed by
5678 bool isUndefLO = NumUndefsLO == Half;
5679 bool isUndefHI = NumUndefsHI == Half;
5680 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5681 isUndefLO, isUndefHI);
5685 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5686 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5688 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5689 X86Opcode = X86ISD::HADD;
5690 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5691 X86Opcode = X86ISD::HSUB;
5692 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5693 X86Opcode = X86ISD::FHADD;
5694 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5695 X86Opcode = X86ISD::FHSUB;
5699 // Don't try to expand this build_vector into a pair of horizontal add/sub
5700 // if we can simply emit a pair of scalar add/sub.
5701 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5704 // Convert this build_vector into two horizontal add/sub followed by
5706 bool isUndefLO = NumUndefsLO == Half;
5707 bool isUndefHI = NumUndefsHI == Half;
5708 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5709 isUndefLO, isUndefHI);
5716 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5719 MVT VT = Op.getSimpleValueType();
5720 MVT ExtVT = VT.getVectorElementType();
5721 unsigned NumElems = Op.getNumOperands();
5723 // Generate vectors for predicate vectors.
5724 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5725 return LowerBUILD_VECTORvXi1(Op, DAG);
5727 // Vectors containing all zeros can be matched by pxor and xorps later
5728 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5729 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5730 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5731 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5734 return getZeroVector(VT, Subtarget, DAG, dl);
5737 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5738 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5739 // vpcmpeqd on 256-bit vectors.
5740 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5741 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5744 if (!VT.is512BitVector())
5745 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5748 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5749 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5751 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5752 return HorizontalOp;
5753 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5756 unsigned EVTBits = ExtVT.getSizeInBits();
5758 unsigned NumZero = 0;
5759 unsigned NumNonZero = 0;
5760 unsigned NonZeros = 0;
5761 bool IsAllConstants = true;
5762 SmallSet<SDValue, 8> Values;
5763 for (unsigned i = 0; i < NumElems; ++i) {
5764 SDValue Elt = Op.getOperand(i);
5765 if (Elt.getOpcode() == ISD::UNDEF)
5768 if (Elt.getOpcode() != ISD::Constant &&
5769 Elt.getOpcode() != ISD::ConstantFP)
5770 IsAllConstants = false;
5771 if (X86::isZeroNode(Elt))
5774 NonZeros |= (1 << i);
5779 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5780 if (NumNonZero == 0)
5781 return DAG.getUNDEF(VT);
5783 // Special case for single non-zero, non-undef, element.
5784 if (NumNonZero == 1) {
5785 unsigned Idx = countTrailingZeros(NonZeros);
5786 SDValue Item = Op.getOperand(Idx);
5788 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5789 // the value are obviously zero, truncate the value to i32 and do the
5790 // insertion that way. Only do this if the value is non-constant or if the
5791 // value is a constant being inserted into element 0. It is cheaper to do
5792 // a constant pool load than it is to do a movd + shuffle.
5793 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5794 (!IsAllConstants || Idx == 0)) {
5795 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5797 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5798 EVT VecVT = MVT::v4i32;
5800 // Truncate the value (which may itself be a constant) to i32, and
5801 // convert it to a vector with movd (S2V+shuffle to zero extend).
5802 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5803 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5805 ISD::BITCAST, dl, VT,
5806 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5810 // If we have a constant or non-constant insertion into the low element of
5811 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5812 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5813 // depending on what the source datatype is.
5816 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5818 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5819 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5820 if (VT.is512BitVector()) {
5821 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5822 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5823 Item, DAG.getIntPtrConstant(0, dl));
5825 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5826 "Expected an SSE value type!");
5827 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5828 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5829 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5832 // We can't directly insert an i8 or i16 into a vector, so zero extend
5834 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5835 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5836 if (VT.is256BitVector()) {
5837 if (Subtarget->hasAVX()) {
5838 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5839 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5841 // Without AVX, we need to extend to a 128-bit vector and then
5842 // insert into the 256-bit vector.
5843 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5844 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5845 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5848 assert(VT.is128BitVector() && "Expected an SSE value type!");
5849 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5850 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5852 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5856 // Is it a vector logical left shift?
5857 if (NumElems == 2 && Idx == 1 &&
5858 X86::isZeroNode(Op.getOperand(0)) &&
5859 !X86::isZeroNode(Op.getOperand(1))) {
5860 unsigned NumBits = VT.getSizeInBits();
5861 return getVShift(true, VT,
5862 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5863 VT, Op.getOperand(1)),
5864 NumBits/2, DAG, *this, dl);
5867 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5870 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5871 // is a non-constant being inserted into an element other than the low one,
5872 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5873 // movd/movss) to move this into the low element, then shuffle it into
5875 if (EVTBits == 32) {
5876 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5877 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5881 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5882 if (Values.size() == 1) {
5883 if (EVTBits == 32) {
5884 // Instead of a shuffle like this:
5885 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5886 // Check if it's possible to issue this instead.
5887 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5888 unsigned Idx = countTrailingZeros(NonZeros);
5889 SDValue Item = Op.getOperand(Idx);
5890 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5891 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5896 // A vector full of immediates; various special cases are already
5897 // handled, so this is best done with a single constant-pool load.
5901 // For AVX-length vectors, see if we can use a vector load to get all of the
5902 // elements, otherwise build the individual 128-bit pieces and use
5903 // shuffles to put them in place.
5904 if (VT.is256BitVector() || VT.is512BitVector()) {
5905 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5907 // Check for a build vector of consecutive loads.
5908 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5911 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5913 // Build both the lower and upper subvector.
5914 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5915 makeArrayRef(&V[0], NumElems/2));
5916 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5917 makeArrayRef(&V[NumElems / 2], NumElems/2));
5919 // Recreate the wider vector with the lower and upper part.
5920 if (VT.is256BitVector())
5921 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5922 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5925 // Let legalizer expand 2-wide build_vectors.
5926 if (EVTBits == 64) {
5927 if (NumNonZero == 1) {
5928 // One half is zero or undef.
5929 unsigned Idx = countTrailingZeros(NonZeros);
5930 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5931 Op.getOperand(Idx));
5932 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5937 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5938 if (EVTBits == 8 && NumElems == 16)
5939 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5943 if (EVTBits == 16 && NumElems == 8)
5944 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5948 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5949 if (EVTBits == 32 && NumElems == 4)
5950 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5953 // If element VT is == 32 bits, turn it into a number of shuffles.
5954 SmallVector<SDValue, 8> V(NumElems);
5955 if (NumElems == 4 && NumZero > 0) {
5956 for (unsigned i = 0; i < 4; ++i) {
5957 bool isZero = !(NonZeros & (1 << i));
5959 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5961 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5964 for (unsigned i = 0; i < 2; ++i) {
5965 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5968 V[i] = V[i*2]; // Must be a zero vector.
5971 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5974 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5977 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5982 bool Reverse1 = (NonZeros & 0x3) == 2;
5983 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5987 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5988 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5990 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5993 if (Values.size() > 1 && VT.is128BitVector()) {
5994 // Check for a build vector of consecutive loads.
5995 for (unsigned i = 0; i < NumElems; ++i)
5996 V[i] = Op.getOperand(i);
5998 // Check for elements which are consecutive loads.
5999 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6002 // Check for a build vector from mostly shuffle plus few inserting.
6003 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6006 // For SSE 4.1, use insertps to put the high elements into the low element.
6007 if (Subtarget->hasSSE41()) {
6009 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6010 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6012 Result = DAG.getUNDEF(VT);
6014 for (unsigned i = 1; i < NumElems; ++i) {
6015 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6016 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6017 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6022 // Otherwise, expand into a number of unpckl*, start by extending each of
6023 // our (non-undef) elements to the full vector width with the element in the
6024 // bottom slot of the vector (which generates no code for SSE).
6025 for (unsigned i = 0; i < NumElems; ++i) {
6026 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6027 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6029 V[i] = DAG.getUNDEF(VT);
6032 // Next, we iteratively mix elements, e.g. for v4f32:
6033 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6034 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6035 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6036 unsigned EltStride = NumElems >> 1;
6037 while (EltStride != 0) {
6038 for (unsigned i = 0; i < EltStride; ++i) {
6039 // If V[i+EltStride] is undef and this is the first round of mixing,
6040 // then it is safe to just drop this shuffle: V[i] is already in the
6041 // right place, the one element (since it's the first round) being
6042 // inserted as undef can be dropped. This isn't safe for successive
6043 // rounds because they will permute elements within both vectors.
6044 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6045 EltStride == NumElems/2)
6048 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6057 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6058 // to create 256-bit vectors from two other 128-bit ones.
6059 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6061 MVT ResVT = Op.getSimpleValueType();
6063 assert((ResVT.is256BitVector() ||
6064 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6066 SDValue V1 = Op.getOperand(0);
6067 SDValue V2 = Op.getOperand(1);
6068 unsigned NumElems = ResVT.getVectorNumElements();
6069 if (ResVT.is256BitVector())
6070 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6072 if (Op.getNumOperands() == 4) {
6073 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6074 ResVT.getVectorNumElements()/2);
6075 SDValue V3 = Op.getOperand(2);
6076 SDValue V4 = Op.getOperand(3);
6077 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6078 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6080 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6083 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6084 const X86Subtarget *Subtarget,
6085 SelectionDAG & DAG) {
6087 MVT ResVT = Op.getSimpleValueType();
6088 unsigned NumOfOperands = Op.getNumOperands();
6090 assert(isPowerOf2_32(NumOfOperands) &&
6091 "Unexpected number of operands in CONCAT_VECTORS");
6093 if (NumOfOperands > 2) {
6094 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6095 ResVT.getVectorNumElements()/2);
6096 SmallVector<SDValue, 2> Ops;
6097 for (unsigned i = 0; i < NumOfOperands/2; i++)
6098 Ops.push_back(Op.getOperand(i));
6099 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6101 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6102 Ops.push_back(Op.getOperand(i));
6103 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6104 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6107 SDValue V1 = Op.getOperand(0);
6108 SDValue V2 = Op.getOperand(1);
6109 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6110 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6112 if (IsZeroV1 && IsZeroV2)
6113 return getZeroVector(ResVT, Subtarget, DAG, dl);
6115 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6116 SDValue Undef = DAG.getUNDEF(ResVT);
6117 unsigned NumElems = ResVT.getVectorNumElements();
6118 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6120 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6121 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6125 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6126 // Zero the upper bits of V1
6127 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6128 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6131 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6134 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6135 const X86Subtarget *Subtarget,
6136 SelectionDAG &DAG) {
6137 MVT VT = Op.getSimpleValueType();
6138 if (VT.getVectorElementType() == MVT::i1)
6139 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6141 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6142 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6143 Op.getNumOperands() == 4)));
6145 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6146 // from two other 128-bit ones.
6148 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6149 return LowerAVXCONCAT_VECTORS(Op, DAG);
6153 //===----------------------------------------------------------------------===//
6154 // Vector shuffle lowering
6156 // This is an experimental code path for lowering vector shuffles on x86. It is
6157 // designed to handle arbitrary vector shuffles and blends, gracefully
6158 // degrading performance as necessary. It works hard to recognize idiomatic
6159 // shuffles and lower them to optimal instruction patterns without leaving
6160 // a framework that allows reasonably efficient handling of all vector shuffle
6162 //===----------------------------------------------------------------------===//
6164 /// \brief Tiny helper function to identify a no-op mask.
6166 /// This is a somewhat boring predicate function. It checks whether the mask
6167 /// array input, which is assumed to be a single-input shuffle mask of the kind
6168 /// used by the X86 shuffle instructions (not a fully general
6169 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6170 /// in-place shuffle are 'no-op's.
6171 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6172 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6173 if (Mask[i] != -1 && Mask[i] != i)
6178 /// \brief Helper function to classify a mask as a single-input mask.
6180 /// This isn't a generic single-input test because in the vector shuffle
6181 /// lowering we canonicalize single inputs to be the first input operand. This
6182 /// means we can more quickly test for a single input by only checking whether
6183 /// an input from the second operand exists. We also assume that the size of
6184 /// mask corresponds to the size of the input vectors which isn't true in the
6185 /// fully general case.
6186 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6188 if (M >= (int)Mask.size())
6193 /// \brief Test whether there are elements crossing 128-bit lanes in this
6196 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6197 /// and we routinely test for these.
6198 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6199 int LaneSize = 128 / VT.getScalarSizeInBits();
6200 int Size = Mask.size();
6201 for (int i = 0; i < Size; ++i)
6202 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6207 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6209 /// This checks a shuffle mask to see if it is performing the same
6210 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6211 /// that it is also not lane-crossing. It may however involve a blend from the
6212 /// same lane of a second vector.
6214 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6215 /// non-trivial to compute in the face of undef lanes. The representation is
6216 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6217 /// entries from both V1 and V2 inputs to the wider mask.
6219 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6220 SmallVectorImpl<int> &RepeatedMask) {
6221 int LaneSize = 128 / VT.getScalarSizeInBits();
6222 RepeatedMask.resize(LaneSize, -1);
6223 int Size = Mask.size();
6224 for (int i = 0; i < Size; ++i) {
6227 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6228 // This entry crosses lanes, so there is no way to model this shuffle.
6231 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6232 if (RepeatedMask[i % LaneSize] == -1)
6233 // This is the first non-undef entry in this slot of a 128-bit lane.
6234 RepeatedMask[i % LaneSize] =
6235 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6236 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6237 // Found a mismatch with the repeated mask.
6243 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6246 /// This is a fast way to test a shuffle mask against a fixed pattern:
6248 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6250 /// It returns true if the mask is exactly as wide as the argument list, and
6251 /// each element of the mask is either -1 (signifying undef) or the value given
6252 /// in the argument.
6253 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6254 ArrayRef<int> ExpectedMask) {
6255 if (Mask.size() != ExpectedMask.size())
6258 int Size = Mask.size();
6260 // If the values are build vectors, we can look through them to find
6261 // equivalent inputs that make the shuffles equivalent.
6262 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6263 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6265 for (int i = 0; i < Size; ++i)
6266 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6267 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6268 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6269 if (!MaskBV || !ExpectedBV ||
6270 MaskBV->getOperand(Mask[i] % Size) !=
6271 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6278 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6280 /// This helper function produces an 8-bit shuffle immediate corresponding to
6281 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6282 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6285 /// NB: We rely heavily on "undef" masks preserving the input lane.
6286 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6287 SelectionDAG &DAG) {
6288 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6289 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6290 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6291 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6292 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6295 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6296 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6297 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6298 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6299 return DAG.getConstant(Imm, DL, MVT::i8);
6302 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6304 /// This is used as a fallback approach when first class blend instructions are
6305 /// unavailable. Currently it is only suitable for integer vectors, but could
6306 /// be generalized for floating point vectors if desirable.
6307 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6308 SDValue V2, ArrayRef<int> Mask,
6309 SelectionDAG &DAG) {
6310 assert(VT.isInteger() && "Only supports integer vector types!");
6311 MVT EltVT = VT.getScalarType();
6312 int NumEltBits = EltVT.getSizeInBits();
6313 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6314 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6316 SmallVector<SDValue, 16> MaskOps;
6317 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6318 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6319 return SDValue(); // Shuffled input!
6320 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6323 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6324 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6325 // We have to cast V2 around.
6326 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6327 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6328 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6329 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6330 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6331 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6334 /// \brief Try to emit a blend instruction for a shuffle.
6336 /// This doesn't do any checks for the availability of instructions for blending
6337 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6338 /// be matched in the backend with the type given. What it does check for is
6339 /// that the shuffle mask is in fact a blend.
6340 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6341 SDValue V2, ArrayRef<int> Mask,
6342 const X86Subtarget *Subtarget,
6343 SelectionDAG &DAG) {
6344 unsigned BlendMask = 0;
6345 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6346 if (Mask[i] >= Size) {
6347 if (Mask[i] != i + Size)
6348 return SDValue(); // Shuffled V2 input!
6349 BlendMask |= 1u << i;
6352 if (Mask[i] >= 0 && Mask[i] != i)
6353 return SDValue(); // Shuffled V1 input!
6355 switch (VT.SimpleTy) {
6360 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6361 DAG.getConstant(BlendMask, DL, MVT::i8));
6365 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6369 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6370 // that instruction.
6371 if (Subtarget->hasAVX2()) {
6372 // Scale the blend by the number of 32-bit dwords per element.
6373 int Scale = VT.getScalarSizeInBits() / 32;
6375 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6376 if (Mask[i] >= Size)
6377 for (int j = 0; j < Scale; ++j)
6378 BlendMask |= 1u << (i * Scale + j);
6380 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6381 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6382 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6383 return DAG.getNode(ISD::BITCAST, DL, VT,
6384 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6385 DAG.getConstant(BlendMask, DL, MVT::i8)));
6389 // For integer shuffles we need to expand the mask and cast the inputs to
6390 // v8i16s prior to blending.
6391 int Scale = 8 / VT.getVectorNumElements();
6393 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6394 if (Mask[i] >= Size)
6395 for (int j = 0; j < Scale; ++j)
6396 BlendMask |= 1u << (i * Scale + j);
6398 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6399 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6400 return DAG.getNode(ISD::BITCAST, DL, VT,
6401 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6402 DAG.getConstant(BlendMask, DL, MVT::i8)));
6406 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6407 SmallVector<int, 8> RepeatedMask;
6408 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6409 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6410 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6412 for (int i = 0; i < 8; ++i)
6413 if (RepeatedMask[i] >= 16)
6414 BlendMask |= 1u << i;
6415 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6416 DAG.getConstant(BlendMask, DL, MVT::i8));
6422 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6423 "256-bit byte-blends require AVX2 support!");
6425 // Scale the blend by the number of bytes per element.
6426 int Scale = VT.getScalarSizeInBits() / 8;
6428 // This form of blend is always done on bytes. Compute the byte vector
6430 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6432 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6433 // mix of LLVM's code generator and the x86 backend. We tell the code
6434 // generator that boolean values in the elements of an x86 vector register
6435 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6436 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6437 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6438 // of the element (the remaining are ignored) and 0 in that high bit would
6439 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6440 // the LLVM model for boolean values in vector elements gets the relevant
6441 // bit set, it is set backwards and over constrained relative to x86's
6443 SmallVector<SDValue, 32> VSELECTMask;
6444 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6445 for (int j = 0; j < Scale; ++j)
6446 VSELECTMask.push_back(
6447 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6448 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6451 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6452 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6454 ISD::BITCAST, DL, VT,
6455 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6456 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6461 llvm_unreachable("Not a supported integer vector type!");
6465 /// \brief Try to lower as a blend of elements from two inputs followed by
6466 /// a single-input permutation.
6468 /// This matches the pattern where we can blend elements from two inputs and
6469 /// then reduce the shuffle to a single-input permutation.
6470 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6473 SelectionDAG &DAG) {
6474 // We build up the blend mask while checking whether a blend is a viable way
6475 // to reduce the shuffle.
6476 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6477 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6479 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6483 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6485 if (BlendMask[Mask[i] % Size] == -1)
6486 BlendMask[Mask[i] % Size] = Mask[i];
6487 else if (BlendMask[Mask[i] % Size] != Mask[i])
6488 return SDValue(); // Can't blend in the needed input!
6490 PermuteMask[i] = Mask[i] % Size;
6493 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6494 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6497 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6498 /// blends and permutes.
6500 /// This matches the extremely common pattern for handling combined
6501 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6502 /// operations. It will try to pick the best arrangement of shuffles and
6504 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6508 SelectionDAG &DAG) {
6509 // Shuffle the input elements into the desired positions in V1 and V2 and
6510 // blend them together.
6511 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6512 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6513 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6514 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6515 if (Mask[i] >= 0 && Mask[i] < Size) {
6516 V1Mask[i] = Mask[i];
6518 } else if (Mask[i] >= Size) {
6519 V2Mask[i] = Mask[i] - Size;
6520 BlendMask[i] = i + Size;
6523 // Try to lower with the simpler initial blend strategy unless one of the
6524 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6525 // shuffle may be able to fold with a load or other benefit. However, when
6526 // we'll have to do 2x as many shuffles in order to achieve this, blending
6527 // first is a better strategy.
6528 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6529 if (SDValue BlendPerm =
6530 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6533 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6534 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6535 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6538 /// \brief Try to lower a vector shuffle as a byte rotation.
6540 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6541 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6542 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6543 /// try to generically lower a vector shuffle through such an pattern. It
6544 /// does not check for the profitability of lowering either as PALIGNR or
6545 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6546 /// This matches shuffle vectors that look like:
6548 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6550 /// Essentially it concatenates V1 and V2, shifts right by some number of
6551 /// elements, and takes the low elements as the result. Note that while this is
6552 /// specified as a *right shift* because x86 is little-endian, it is a *left
6553 /// rotate* of the vector lanes.
6554 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6557 const X86Subtarget *Subtarget,
6558 SelectionDAG &DAG) {
6559 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6561 int NumElts = Mask.size();
6562 int NumLanes = VT.getSizeInBits() / 128;
6563 int NumLaneElts = NumElts / NumLanes;
6565 // We need to detect various ways of spelling a rotation:
6566 // [11, 12, 13, 14, 15, 0, 1, 2]
6567 // [-1, 12, 13, 14, -1, -1, 1, -1]
6568 // [-1, -1, -1, -1, -1, -1, 1, 2]
6569 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6570 // [-1, 4, 5, 6, -1, -1, 9, -1]
6571 // [-1, 4, 5, 6, -1, -1, -1, -1]
6574 for (int l = 0; l < NumElts; l += NumLaneElts) {
6575 for (int i = 0; i < NumLaneElts; ++i) {
6576 if (Mask[l + i] == -1)
6578 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6580 // Get the mod-Size index and lane correct it.
6581 int LaneIdx = (Mask[l + i] % NumElts) - l;
6582 // Make sure it was in this lane.
6583 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6586 // Determine where a rotated vector would have started.
6587 int StartIdx = i - LaneIdx;
6589 // The identity rotation isn't interesting, stop.
6592 // If we found the tail of a vector the rotation must be the missing
6593 // front. If we found the head of a vector, it must be how much of the
6595 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6598 Rotation = CandidateRotation;
6599 else if (Rotation != CandidateRotation)
6600 // The rotations don't match, so we can't match this mask.
6603 // Compute which value this mask is pointing at.
6604 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6606 // Compute which of the two target values this index should be assigned
6607 // to. This reflects whether the high elements are remaining or the low
6608 // elements are remaining.
6609 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6611 // Either set up this value if we've not encountered it before, or check
6612 // that it remains consistent.
6615 else if (TargetV != MaskV)
6616 // This may be a rotation, but it pulls from the inputs in some
6617 // unsupported interleaving.
6622 // Check that we successfully analyzed the mask, and normalize the results.
6623 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6624 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6630 // The actual rotate instruction rotates bytes, so we need to scale the
6631 // rotation based on how many bytes are in the vector lane.
6632 int Scale = 16 / NumLaneElts;
6634 // SSSE3 targets can use the palignr instruction.
6635 if (Subtarget->hasSSSE3()) {
6636 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6637 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6638 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6639 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6641 return DAG.getNode(ISD::BITCAST, DL, VT,
6642 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6643 DAG.getConstant(Rotation * Scale, DL,
6647 assert(VT.getSizeInBits() == 128 &&
6648 "Rotate-based lowering only supports 128-bit lowering!");
6649 assert(Mask.size() <= 16 &&
6650 "Can shuffle at most 16 bytes in a 128-bit vector!");
6652 // Default SSE2 implementation
6653 int LoByteShift = 16 - Rotation * Scale;
6654 int HiByteShift = Rotation * Scale;
6656 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6657 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6658 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6660 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6661 DAG.getConstant(LoByteShift, DL, MVT::i8));
6662 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6663 DAG.getConstant(HiByteShift, DL, MVT::i8));
6664 return DAG.getNode(ISD::BITCAST, DL, VT,
6665 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6668 /// \brief Compute whether each element of a shuffle is zeroable.
6670 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6671 /// Either it is an undef element in the shuffle mask, the element of the input
6672 /// referenced is undef, or the element of the input referenced is known to be
6673 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6674 /// as many lanes with this technique as possible to simplify the remaining
6676 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6677 SDValue V1, SDValue V2) {
6678 SmallBitVector Zeroable(Mask.size(), false);
6680 while (V1.getOpcode() == ISD::BITCAST)
6681 V1 = V1->getOperand(0);
6682 while (V2.getOpcode() == ISD::BITCAST)
6683 V2 = V2->getOperand(0);
6685 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6686 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6688 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6690 // Handle the easy cases.
6691 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6696 // If this is an index into a build_vector node (which has the same number
6697 // of elements), dig out the input value and use it.
6698 SDValue V = M < Size ? V1 : V2;
6699 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6702 SDValue Input = V.getOperand(M % Size);
6703 // The UNDEF opcode check really should be dead code here, but not quite
6704 // worth asserting on (it isn't invalid, just unexpected).
6705 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6712 /// \brief Try to emit a bitmask instruction for a shuffle.
6714 /// This handles cases where we can model a blend exactly as a bitmask due to
6715 /// one of the inputs being zeroable.
6716 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6717 SDValue V2, ArrayRef<int> Mask,
6718 SelectionDAG &DAG) {
6719 MVT EltVT = VT.getScalarType();
6720 int NumEltBits = EltVT.getSizeInBits();
6721 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6722 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6723 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6725 if (EltVT.isFloatingPoint()) {
6726 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6727 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6729 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6730 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6732 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6735 if (Mask[i] % Size != i)
6736 return SDValue(); // Not a blend.
6738 V = Mask[i] < Size ? V1 : V2;
6739 else if (V != (Mask[i] < Size ? V1 : V2))
6740 return SDValue(); // Can only let one input through the mask.
6742 VMaskOps[i] = AllOnes;
6745 return SDValue(); // No non-zeroable elements!
6747 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6748 V = DAG.getNode(VT.isFloatingPoint()
6749 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6754 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6756 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6757 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6758 /// matches elements from one of the input vectors shuffled to the left or
6759 /// right with zeroable elements 'shifted in'. It handles both the strictly
6760 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6763 /// PSHL : (little-endian) left bit shift.
6764 /// [ zz, 0, zz, 2 ]
6765 /// [ -1, 4, zz, -1 ]
6766 /// PSRL : (little-endian) right bit shift.
6768 /// [ -1, -1, 7, zz]
6769 /// PSLLDQ : (little-endian) left byte shift
6770 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6771 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6772 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6773 /// PSRLDQ : (little-endian) right byte shift
6774 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6775 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6776 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6777 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6778 SDValue V2, ArrayRef<int> Mask,
6779 SelectionDAG &DAG) {
6780 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6782 int Size = Mask.size();
6783 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6785 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6786 for (int i = 0; i < Size; i += Scale)
6787 for (int j = 0; j < Shift; ++j)
6788 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6794 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6795 for (int i = 0; i != Size; i += Scale) {
6796 unsigned Pos = Left ? i + Shift : i;
6797 unsigned Low = Left ? i : i + Shift;
6798 unsigned Len = Scale - Shift;
6799 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6800 Low + (V == V1 ? 0 : Size)))
6804 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6805 bool ByteShift = ShiftEltBits > 64;
6806 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6807 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6808 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6810 // Normalize the scale for byte shifts to still produce an i64 element
6812 Scale = ByteShift ? Scale / 2 : Scale;
6814 // We need to round trip through the appropriate type for the shift.
6815 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6816 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6817 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6818 "Illegal integer vector type");
6819 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6821 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6822 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6823 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6826 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6827 // keep doubling the size of the integer elements up to that. We can
6828 // then shift the elements of the integer vector by whole multiples of
6829 // their width within the elements of the larger integer vector. Test each
6830 // multiple to see if we can find a match with the moved element indices
6831 // and that the shifted in elements are all zeroable.
6832 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6833 for (int Shift = 1; Shift != Scale; ++Shift)
6834 for (bool Left : {true, false})
6835 if (CheckZeros(Shift, Scale, Left))
6836 for (SDValue V : {V1, V2})
6837 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6844 /// \brief Lower a vector shuffle as a zero or any extension.
6846 /// Given a specific number of elements, element bit width, and extension
6847 /// stride, produce either a zero or any extension based on the available
6848 /// features of the subtarget.
6849 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6850 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6851 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6852 assert(Scale > 1 && "Need a scale to extend.");
6853 int NumElements = VT.getVectorNumElements();
6854 int EltBits = VT.getScalarSizeInBits();
6855 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6856 "Only 8, 16, and 32 bit elements can be extended.");
6857 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6859 // Found a valid zext mask! Try various lowering strategies based on the
6860 // input type and available ISA extensions.
6861 if (Subtarget->hasSSE41()) {
6862 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6863 NumElements / Scale);
6864 return DAG.getNode(ISD::BITCAST, DL, VT,
6865 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6868 // For any extends we can cheat for larger element sizes and use shuffle
6869 // instructions that can fold with a load and/or copy.
6870 if (AnyExt && EltBits == 32) {
6871 int PSHUFDMask[4] = {0, -1, 1, -1};
6873 ISD::BITCAST, DL, VT,
6874 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6875 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6876 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6878 if (AnyExt && EltBits == 16 && Scale > 2) {
6879 int PSHUFDMask[4] = {0, -1, 0, -1};
6880 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6881 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6882 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6883 int PSHUFHWMask[4] = {1, -1, -1, -1};
6885 ISD::BITCAST, DL, VT,
6886 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6887 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6888 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6891 // If this would require more than 2 unpack instructions to expand, use
6892 // pshufb when available. We can only use more than 2 unpack instructions
6893 // when zero extending i8 elements which also makes it easier to use pshufb.
6894 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6895 assert(NumElements == 16 && "Unexpected byte vector width!");
6896 SDValue PSHUFBMask[16];
6897 for (int i = 0; i < 16; ++i)
6899 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6900 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6901 return DAG.getNode(ISD::BITCAST, DL, VT,
6902 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6903 DAG.getNode(ISD::BUILD_VECTOR, DL,
6904 MVT::v16i8, PSHUFBMask)));
6907 // Otherwise emit a sequence of unpacks.
6909 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6910 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6911 : getZeroVector(InputVT, Subtarget, DAG, DL);
6912 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6913 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6917 } while (Scale > 1);
6918 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6921 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6923 /// This routine will try to do everything in its power to cleverly lower
6924 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6925 /// check for the profitability of this lowering, it tries to aggressively
6926 /// match this pattern. It will use all of the micro-architectural details it
6927 /// can to emit an efficient lowering. It handles both blends with all-zero
6928 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6929 /// masking out later).
6931 /// The reason we have dedicated lowering for zext-style shuffles is that they
6932 /// are both incredibly common and often quite performance sensitive.
6933 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6934 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6935 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6936 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6938 int Bits = VT.getSizeInBits();
6939 int NumElements = VT.getVectorNumElements();
6940 assert(VT.getScalarSizeInBits() <= 32 &&
6941 "Exceeds 32-bit integer zero extension limit");
6942 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6944 // Define a helper function to check a particular ext-scale and lower to it if
6946 auto Lower = [&](int Scale) -> SDValue {
6949 for (int i = 0; i < NumElements; ++i) {
6951 continue; // Valid anywhere but doesn't tell us anything.
6952 if (i % Scale != 0) {
6953 // Each of the extended elements need to be zeroable.
6957 // We no longer are in the anyext case.
6962 // Each of the base elements needs to be consecutive indices into the
6963 // same input vector.
6964 SDValue V = Mask[i] < NumElements ? V1 : V2;
6967 else if (InputV != V)
6968 return SDValue(); // Flip-flopping inputs.
6970 if (Mask[i] % NumElements != i / Scale)
6971 return SDValue(); // Non-consecutive strided elements.
6974 // If we fail to find an input, we have a zero-shuffle which should always
6975 // have already been handled.
6976 // FIXME: Maybe handle this here in case during blending we end up with one?
6980 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6981 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6984 // The widest scale possible for extending is to a 64-bit integer.
6985 assert(Bits % 64 == 0 &&
6986 "The number of bits in a vector must be divisible by 64 on x86!");
6987 int NumExtElements = Bits / 64;
6989 // Each iteration, try extending the elements half as much, but into twice as
6991 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6992 assert(NumElements % NumExtElements == 0 &&
6993 "The input vector size must be divisible by the extended size.");
6994 if (SDValue V = Lower(NumElements / NumExtElements))
6998 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7002 // Returns one of the source operands if the shuffle can be reduced to a
7003 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7004 auto CanZExtLowHalf = [&]() {
7005 for (int i = NumElements / 2; i != NumElements; ++i)
7008 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7010 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7015 if (SDValue V = CanZExtLowHalf()) {
7016 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
7017 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7018 return DAG.getNode(ISD::BITCAST, DL, VT, V);
7021 // No viable ext lowering found.
7025 /// \brief Try to get a scalar value for a specific element of a vector.
7027 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7028 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7029 SelectionDAG &DAG) {
7030 MVT VT = V.getSimpleValueType();
7031 MVT EltVT = VT.getVectorElementType();
7032 while (V.getOpcode() == ISD::BITCAST)
7033 V = V.getOperand(0);
7034 // If the bitcasts shift the element size, we can't extract an equivalent
7036 MVT NewVT = V.getSimpleValueType();
7037 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7040 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7041 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7042 // Ensure the scalar operand is the same size as the destination.
7043 // FIXME: Add support for scalar truncation where possible.
7044 SDValue S = V.getOperand(Idx);
7045 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7046 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7052 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7054 /// This is particularly important because the set of instructions varies
7055 /// significantly based on whether the operand is a load or not.
7056 static bool isShuffleFoldableLoad(SDValue V) {
7057 while (V.getOpcode() == ISD::BITCAST)
7058 V = V.getOperand(0);
7060 return ISD::isNON_EXTLoad(V.getNode());
7063 /// \brief Try to lower insertion of a single element into a zero vector.
7065 /// This is a common pattern that we have especially efficient patterns to lower
7066 /// across all subtarget feature sets.
7067 static SDValue lowerVectorShuffleAsElementInsertion(
7068 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7069 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7070 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7072 MVT EltVT = VT.getVectorElementType();
7074 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7075 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7077 bool IsV1Zeroable = true;
7078 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7079 if (i != V2Index && !Zeroable[i]) {
7080 IsV1Zeroable = false;
7084 // Check for a single input from a SCALAR_TO_VECTOR node.
7085 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7086 // all the smarts here sunk into that routine. However, the current
7087 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7088 // vector shuffle lowering is dead.
7089 if (SDValue V2S = getScalarValueForVectorElement(
7090 V2, Mask[V2Index] - Mask.size(), DAG)) {
7091 // We need to zext the scalar if it is smaller than an i32.
7092 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7093 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7094 // Using zext to expand a narrow element won't work for non-zero
7099 // Zero-extend directly to i32.
7101 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7103 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7104 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7105 EltVT == MVT::i16) {
7106 // Either not inserting from the low element of the input or the input
7107 // element size is too small to use VZEXT_MOVL to clear the high bits.
7111 if (!IsV1Zeroable) {
7112 // If V1 can't be treated as a zero vector we have fewer options to lower
7113 // this. We can't support integer vectors or non-zero targets cheaply, and
7114 // the V1 elements can't be permuted in any way.
7115 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7116 if (!VT.isFloatingPoint() || V2Index != 0)
7118 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7119 V1Mask[V2Index] = -1;
7120 if (!isNoopShuffleMask(V1Mask))
7122 // This is essentially a special case blend operation, but if we have
7123 // general purpose blend operations, they are always faster. Bail and let
7124 // the rest of the lowering handle these as blends.
7125 if (Subtarget->hasSSE41())
7128 // Otherwise, use MOVSD or MOVSS.
7129 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7130 "Only two types of floating point element types to handle!");
7131 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7135 // This lowering only works for the low element with floating point vectors.
7136 if (VT.isFloatingPoint() && V2Index != 0)
7139 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7141 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7144 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7145 // the desired position. Otherwise it is more efficient to do a vector
7146 // shift left. We know that we can do a vector shift left because all
7147 // the inputs are zero.
7148 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7149 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7150 V2Shuffle[V2Index] = 0;
7151 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7153 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7155 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7157 V2Index * EltVT.getSizeInBits()/8, DL,
7158 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7159 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7165 /// \brief Try to lower broadcast of a single element.
7167 /// For convenience, this code also bundles all of the subtarget feature set
7168 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7169 /// a convenient way to factor it out.
7170 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7172 const X86Subtarget *Subtarget,
7173 SelectionDAG &DAG) {
7174 if (!Subtarget->hasAVX())
7176 if (VT.isInteger() && !Subtarget->hasAVX2())
7179 // Check that the mask is a broadcast.
7180 int BroadcastIdx = -1;
7182 if (M >= 0 && BroadcastIdx == -1)
7184 else if (M >= 0 && M != BroadcastIdx)
7187 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7188 "a sorted mask where the broadcast "
7191 // Go up the chain of (vector) values to find a scalar load that we can
7192 // combine with the broadcast.
7194 switch (V.getOpcode()) {
7195 case ISD::CONCAT_VECTORS: {
7196 int OperandSize = Mask.size() / V.getNumOperands();
7197 V = V.getOperand(BroadcastIdx / OperandSize);
7198 BroadcastIdx %= OperandSize;
7202 case ISD::INSERT_SUBVECTOR: {
7203 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7204 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7208 int BeginIdx = (int)ConstantIdx->getZExtValue();
7210 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7211 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7212 BroadcastIdx -= BeginIdx;
7223 // Check if this is a broadcast of a scalar. We special case lowering
7224 // for scalars so that we can more effectively fold with loads.
7225 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7226 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7227 V = V.getOperand(BroadcastIdx);
7229 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7230 // Only AVX2 has register broadcasts.
7231 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7233 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7234 // We can't broadcast from a vector register without AVX2, and we can only
7235 // broadcast from the zero-element of a vector register.
7239 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7242 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7243 // INSERTPS when the V1 elements are already in the correct locations
7244 // because otherwise we can just always use two SHUFPS instructions which
7245 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7246 // perform INSERTPS if a single V1 element is out of place and all V2
7247 // elements are zeroable.
7248 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7250 SelectionDAG &DAG) {
7251 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7252 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7253 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7254 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7256 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7259 int V1DstIndex = -1;
7260 int V2DstIndex = -1;
7261 bool V1UsedInPlace = false;
7263 for (int i = 0; i < 4; ++i) {
7264 // Synthesize a zero mask from the zeroable elements (includes undefs).
7270 // Flag if we use any V1 inputs in place.
7272 V1UsedInPlace = true;
7276 // We can only insert a single non-zeroable element.
7277 if (V1DstIndex != -1 || V2DstIndex != -1)
7281 // V1 input out of place for insertion.
7284 // V2 input for insertion.
7289 // Don't bother if we have no (non-zeroable) element for insertion.
7290 if (V1DstIndex == -1 && V2DstIndex == -1)
7293 // Determine element insertion src/dst indices. The src index is from the
7294 // start of the inserted vector, not the start of the concatenated vector.
7295 unsigned V2SrcIndex = 0;
7296 if (V1DstIndex != -1) {
7297 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7298 // and don't use the original V2 at all.
7299 V2SrcIndex = Mask[V1DstIndex];
7300 V2DstIndex = V1DstIndex;
7303 V2SrcIndex = Mask[V2DstIndex] - 4;
7306 // If no V1 inputs are used in place, then the result is created only from
7307 // the zero mask and the V2 insertion - so remove V1 dependency.
7309 V1 = DAG.getUNDEF(MVT::v4f32);
7311 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7312 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7314 // Insert the V2 element into the desired position.
7316 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7317 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7320 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7321 /// UNPCK instruction.
7323 /// This specifically targets cases where we end up with alternating between
7324 /// the two inputs, and so can permute them into something that feeds a single
7325 /// UNPCK instruction. Note that this routine only targets integer vectors
7326 /// because for floating point vectors we have a generalized SHUFPS lowering
7327 /// strategy that handles everything that doesn't *exactly* match an unpack,
7328 /// making this clever lowering unnecessary.
7329 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7330 SDValue V2, ArrayRef<int> Mask,
7331 SelectionDAG &DAG) {
7332 assert(!VT.isFloatingPoint() &&
7333 "This routine only supports integer vectors.");
7334 assert(!isSingleInputShuffleMask(Mask) &&
7335 "This routine should only be used when blending two inputs.");
7336 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7338 int Size = Mask.size();
7340 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7341 return M >= 0 && M % Size < Size / 2;
7343 int NumHiInputs = std::count_if(
7344 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7346 bool UnpackLo = NumLoInputs >= NumHiInputs;
7348 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7349 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7350 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7352 for (int i = 0; i < Size; ++i) {
7356 // Each element of the unpack contains Scale elements from this mask.
7357 int UnpackIdx = i / Scale;
7359 // We only handle the case where V1 feeds the first slots of the unpack.
7360 // We rely on canonicalization to ensure this is the case.
7361 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7364 // Setup the mask for this input. The indexing is tricky as we have to
7365 // handle the unpack stride.
7366 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7367 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7371 // If we will have to shuffle both inputs to use the unpack, check whether
7372 // we can just unpack first and shuffle the result. If so, skip this unpack.
7373 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7374 !isNoopShuffleMask(V2Mask))
7377 // Shuffle the inputs into place.
7378 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7379 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7381 // Cast the inputs to the type we will use to unpack them.
7382 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7383 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7385 // Unpack the inputs and cast the result back to the desired type.
7386 return DAG.getNode(ISD::BITCAST, DL, VT,
7387 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7388 DL, UnpackVT, V1, V2));
7391 // We try each unpack from the largest to the smallest to try and find one
7392 // that fits this mask.
7393 int OrigNumElements = VT.getVectorNumElements();
7394 int OrigScalarSize = VT.getScalarSizeInBits();
7395 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7396 int Scale = ScalarSize / OrigScalarSize;
7397 int NumElements = OrigNumElements / Scale;
7398 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7399 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7403 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7405 if (NumLoInputs == 0 || NumHiInputs == 0) {
7406 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7407 "We have to have *some* inputs!");
7408 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7410 // FIXME: We could consider the total complexity of the permute of each
7411 // possible unpacking. Or at the least we should consider how many
7412 // half-crossings are created.
7413 // FIXME: We could consider commuting the unpacks.
7415 SmallVector<int, 32> PermMask;
7416 PermMask.assign(Size, -1);
7417 for (int i = 0; i < Size; ++i) {
7421 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7424 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7426 return DAG.getVectorShuffle(
7427 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7429 DAG.getUNDEF(VT), PermMask);
7435 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7437 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7438 /// support for floating point shuffles but not integer shuffles. These
7439 /// instructions will incur a domain crossing penalty on some chips though so
7440 /// it is better to avoid lowering through this for integer vectors where
7442 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7443 const X86Subtarget *Subtarget,
7444 SelectionDAG &DAG) {
7446 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7447 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7448 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7449 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7450 ArrayRef<int> Mask = SVOp->getMask();
7451 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7453 if (isSingleInputShuffleMask(Mask)) {
7454 // Use low duplicate instructions for masks that match their pattern.
7455 if (Subtarget->hasSSE3())
7456 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7457 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7459 // Straight shuffle of a single input vector. Simulate this by using the
7460 // single input as both of the "inputs" to this instruction..
7461 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7463 if (Subtarget->hasAVX()) {
7464 // If we have AVX, we can use VPERMILPS which will allow folding a load
7465 // into the shuffle.
7466 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7467 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7470 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7471 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7473 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7474 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7476 // If we have a single input, insert that into V1 if we can do so cheaply.
7477 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7478 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7479 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7481 // Try inverting the insertion since for v2 masks it is easy to do and we
7482 // can't reliably sort the mask one way or the other.
7483 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7484 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7485 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7486 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7490 // Try to use one of the special instruction patterns to handle two common
7491 // blend patterns if a zero-blend above didn't work.
7492 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7493 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7494 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7495 // We can either use a special instruction to load over the low double or
7496 // to move just the low double.
7498 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7500 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7502 if (Subtarget->hasSSE41())
7503 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7507 // Use dedicated unpack instructions for masks that match their pattern.
7508 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7509 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7510 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7511 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7513 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7514 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7515 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7518 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7520 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7521 /// the integer unit to minimize domain crossing penalties. However, for blends
7522 /// it falls back to the floating point shuffle operation with appropriate bit
7524 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7525 const X86Subtarget *Subtarget,
7526 SelectionDAG &DAG) {
7528 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7529 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7530 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7531 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7532 ArrayRef<int> Mask = SVOp->getMask();
7533 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7535 if (isSingleInputShuffleMask(Mask)) {
7536 // Check for being able to broadcast a single element.
7537 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7538 Mask, Subtarget, DAG))
7541 // Straight shuffle of a single input vector. For everything from SSE2
7542 // onward this has a single fast instruction with no scary immediates.
7543 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7544 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7545 int WidenedMask[4] = {
7546 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7547 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7549 ISD::BITCAST, DL, MVT::v2i64,
7550 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7551 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7553 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7554 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7555 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7556 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7558 // If we have a blend of two PACKUS operations an the blend aligns with the
7559 // low and half halves, we can just merge the PACKUS operations. This is
7560 // particularly important as it lets us merge shuffles that this routine itself
7562 auto GetPackNode = [](SDValue V) {
7563 while (V.getOpcode() == ISD::BITCAST)
7564 V = V.getOperand(0);
7566 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7568 if (SDValue V1Pack = GetPackNode(V1))
7569 if (SDValue V2Pack = GetPackNode(V2))
7570 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7571 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7572 Mask[0] == 0 ? V1Pack.getOperand(0)
7573 : V1Pack.getOperand(1),
7574 Mask[1] == 2 ? V2Pack.getOperand(0)
7575 : V2Pack.getOperand(1)));
7577 // Try to use shift instructions.
7579 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7582 // When loading a scalar and then shuffling it into a vector we can often do
7583 // the insertion cheaply.
7584 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7585 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7587 // Try inverting the insertion since for v2 masks it is easy to do and we
7588 // can't reliably sort the mask one way or the other.
7589 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7590 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7591 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7594 // We have different paths for blend lowering, but they all must use the
7595 // *exact* same predicate.
7596 bool IsBlendSupported = Subtarget->hasSSE41();
7597 if (IsBlendSupported)
7598 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7602 // Use dedicated unpack instructions for masks that match their pattern.
7603 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7604 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7605 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7606 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7608 // Try to use byte rotation instructions.
7609 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7610 if (Subtarget->hasSSSE3())
7611 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7612 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7615 // If we have direct support for blends, we should lower by decomposing into
7616 // a permute. That will be faster than the domain cross.
7617 if (IsBlendSupported)
7618 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7621 // We implement this with SHUFPD which is pretty lame because it will likely
7622 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7623 // However, all the alternatives are still more cycles and newer chips don't
7624 // have this problem. It would be really nice if x86 had better shuffles here.
7625 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7626 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7627 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7628 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7631 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7633 /// This is used to disable more specialized lowerings when the shufps lowering
7634 /// will happen to be efficient.
7635 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7636 // This routine only handles 128-bit shufps.
7637 assert(Mask.size() == 4 && "Unsupported mask size!");
7639 // To lower with a single SHUFPS we need to have the low half and high half
7640 // each requiring a single input.
7641 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7643 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7649 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7651 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7652 /// It makes no assumptions about whether this is the *best* lowering, it simply
7654 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7655 ArrayRef<int> Mask, SDValue V1,
7656 SDValue V2, SelectionDAG &DAG) {
7657 SDValue LowV = V1, HighV = V2;
7658 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7661 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7663 if (NumV2Elements == 1) {
7665 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7668 // Compute the index adjacent to V2Index and in the same half by toggling
7670 int V2AdjIndex = V2Index ^ 1;
7672 if (Mask[V2AdjIndex] == -1) {
7673 // Handles all the cases where we have a single V2 element and an undef.
7674 // This will only ever happen in the high lanes because we commute the
7675 // vector otherwise.
7677 std::swap(LowV, HighV);
7678 NewMask[V2Index] -= 4;
7680 // Handle the case where the V2 element ends up adjacent to a V1 element.
7681 // To make this work, blend them together as the first step.
7682 int V1Index = V2AdjIndex;
7683 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7684 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7685 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7687 // Now proceed to reconstruct the final blend as we have the necessary
7688 // high or low half formed.
7695 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7696 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7698 } else if (NumV2Elements == 2) {
7699 if (Mask[0] < 4 && Mask[1] < 4) {
7700 // Handle the easy case where we have V1 in the low lanes and V2 in the
7704 } else if (Mask[2] < 4 && Mask[3] < 4) {
7705 // We also handle the reversed case because this utility may get called
7706 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7707 // arrange things in the right direction.
7713 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7714 // trying to place elements directly, just blend them and set up the final
7715 // shuffle to place them.
7717 // The first two blend mask elements are for V1, the second two are for
7719 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7720 Mask[2] < 4 ? Mask[2] : Mask[3],
7721 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7722 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7723 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7724 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7726 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7729 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7730 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7731 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7732 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7735 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7736 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7739 /// \brief Lower 4-lane 32-bit floating point shuffles.
7741 /// Uses instructions exclusively from the floating point unit to minimize
7742 /// domain crossing penalties, as these are sufficient to implement all v4f32
7744 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7745 const X86Subtarget *Subtarget,
7746 SelectionDAG &DAG) {
7748 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7749 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7750 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7751 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7752 ArrayRef<int> Mask = SVOp->getMask();
7753 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7756 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7758 if (NumV2Elements == 0) {
7759 // Check for being able to broadcast a single element.
7760 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7761 Mask, Subtarget, DAG))
7764 // Use even/odd duplicate instructions for masks that match their pattern.
7765 if (Subtarget->hasSSE3()) {
7766 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7767 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7768 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7769 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7772 if (Subtarget->hasAVX()) {
7773 // If we have AVX, we can use VPERMILPS which will allow folding a load
7774 // into the shuffle.
7775 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7776 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7779 // Otherwise, use a straight shuffle of a single input vector. We pass the
7780 // input vector to both operands to simulate this with a SHUFPS.
7781 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7782 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7785 // There are special ways we can lower some single-element blends. However, we
7786 // have custom ways we can lower more complex single-element blends below that
7787 // we defer to if both this and BLENDPS fail to match, so restrict this to
7788 // when the V2 input is targeting element 0 of the mask -- that is the fast
7790 if (NumV2Elements == 1 && Mask[0] >= 4)
7791 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7792 Mask, Subtarget, DAG))
7795 if (Subtarget->hasSSE41()) {
7796 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7800 // Use INSERTPS if we can complete the shuffle efficiently.
7801 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7804 if (!isSingleSHUFPSMask(Mask))
7805 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7806 DL, MVT::v4f32, V1, V2, Mask, DAG))
7810 // Use dedicated unpack instructions for masks that match their pattern.
7811 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7812 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7813 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7814 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7815 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7816 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7817 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7818 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7820 // Otherwise fall back to a SHUFPS lowering strategy.
7821 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7824 /// \brief Lower 4-lane i32 vector shuffles.
7826 /// We try to handle these with integer-domain shuffles where we can, but for
7827 /// blends we use the floating point domain blend instructions.
7828 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7829 const X86Subtarget *Subtarget,
7830 SelectionDAG &DAG) {
7832 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7833 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7834 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7835 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7836 ArrayRef<int> Mask = SVOp->getMask();
7837 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7839 // Whenever we can lower this as a zext, that instruction is strictly faster
7840 // than any alternative. It also allows us to fold memory operands into the
7841 // shuffle in many cases.
7842 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7843 Mask, Subtarget, DAG))
7847 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7849 if (NumV2Elements == 0) {
7850 // Check for being able to broadcast a single element.
7851 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7852 Mask, Subtarget, DAG))
7855 // Straight shuffle of a single input vector. For everything from SSE2
7856 // onward this has a single fast instruction with no scary immediates.
7857 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7858 // but we aren't actually going to use the UNPCK instruction because doing
7859 // so prevents folding a load into this instruction or making a copy.
7860 const int UnpackLoMask[] = {0, 0, 1, 1};
7861 const int UnpackHiMask[] = {2, 2, 3, 3};
7862 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7863 Mask = UnpackLoMask;
7864 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7865 Mask = UnpackHiMask;
7867 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7868 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7871 // Try to use shift instructions.
7873 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7876 // There are special ways we can lower some single-element blends.
7877 if (NumV2Elements == 1)
7878 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7879 Mask, Subtarget, DAG))
7882 // We have different paths for blend lowering, but they all must use the
7883 // *exact* same predicate.
7884 bool IsBlendSupported = Subtarget->hasSSE41();
7885 if (IsBlendSupported)
7886 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7890 if (SDValue Masked =
7891 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7894 // Use dedicated unpack instructions for masks that match their pattern.
7895 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7896 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7897 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7898 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7899 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7900 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7901 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7902 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7904 // Try to use byte rotation instructions.
7905 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7906 if (Subtarget->hasSSSE3())
7907 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7908 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7911 // If we have direct support for blends, we should lower by decomposing into
7912 // a permute. That will be faster than the domain cross.
7913 if (IsBlendSupported)
7914 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7917 // Try to lower by permuting the inputs into an unpack instruction.
7918 if (SDValue Unpack =
7919 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7922 // We implement this with SHUFPS because it can blend from two vectors.
7923 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7924 // up the inputs, bypassing domain shift penalties that we would encur if we
7925 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7927 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7928 DAG.getVectorShuffle(
7930 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7931 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7934 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7935 /// shuffle lowering, and the most complex part.
7937 /// The lowering strategy is to try to form pairs of input lanes which are
7938 /// targeted at the same half of the final vector, and then use a dword shuffle
7939 /// to place them onto the right half, and finally unpack the paired lanes into
7940 /// their final position.
7942 /// The exact breakdown of how to form these dword pairs and align them on the
7943 /// correct sides is really tricky. See the comments within the function for
7944 /// more of the details.
7946 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7947 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7948 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7949 /// vector, form the analogous 128-bit 8-element Mask.
7950 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7951 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7952 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7953 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7954 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7956 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7957 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7958 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7960 SmallVector<int, 4> LoInputs;
7961 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7962 [](int M) { return M >= 0; });
7963 std::sort(LoInputs.begin(), LoInputs.end());
7964 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7965 SmallVector<int, 4> HiInputs;
7966 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7967 [](int M) { return M >= 0; });
7968 std::sort(HiInputs.begin(), HiInputs.end());
7969 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7971 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7972 int NumHToL = LoInputs.size() - NumLToL;
7974 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7975 int NumHToH = HiInputs.size() - NumLToH;
7976 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7977 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7978 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7979 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7981 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7982 // such inputs we can swap two of the dwords across the half mark and end up
7983 // with <=2 inputs to each half in each half. Once there, we can fall through
7984 // to the generic code below. For example:
7986 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7987 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7989 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7990 // and an existing 2-into-2 on the other half. In this case we may have to
7991 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7992 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7993 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7994 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7995 // half than the one we target for fixing) will be fixed when we re-enter this
7996 // path. We will also combine away any sequence of PSHUFD instructions that
7997 // result into a single instruction. Here is an example of the tricky case:
7999 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8000 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8002 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8004 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8005 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8007 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8008 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8010 // The result is fine to be handled by the generic logic.
8011 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8012 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8013 int AOffset, int BOffset) {
8014 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8015 "Must call this with A having 3 or 1 inputs from the A half.");
8016 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8017 "Must call this with B having 1 or 3 inputs from the B half.");
8018 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8019 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8021 // Compute the index of dword with only one word among the three inputs in
8022 // a half by taking the sum of the half with three inputs and subtracting
8023 // the sum of the actual three inputs. The difference is the remaining
8026 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8027 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8028 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8029 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8030 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8031 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8032 int TripleNonInputIdx =
8033 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8034 TripleDWord = TripleNonInputIdx / 2;
8036 // We use xor with one to compute the adjacent DWord to whichever one the
8038 OneInputDWord = (OneInput / 2) ^ 1;
8040 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8041 // and BToA inputs. If there is also such a problem with the BToB and AToB
8042 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8043 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8044 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8045 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8046 // Compute how many inputs will be flipped by swapping these DWords. We
8048 // to balance this to ensure we don't form a 3-1 shuffle in the other
8050 int NumFlippedAToBInputs =
8051 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8052 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8053 int NumFlippedBToBInputs =
8054 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8055 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8056 if ((NumFlippedAToBInputs == 1 &&
8057 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8058 (NumFlippedBToBInputs == 1 &&
8059 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8060 // We choose whether to fix the A half or B half based on whether that
8061 // half has zero flipped inputs. At zero, we may not be able to fix it
8062 // with that half. We also bias towards fixing the B half because that
8063 // will more commonly be the high half, and we have to bias one way.
8064 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8065 ArrayRef<int> Inputs) {
8066 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8067 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8068 PinnedIdx ^ 1) != Inputs.end();
8069 // Determine whether the free index is in the flipped dword or the
8070 // unflipped dword based on where the pinned index is. We use this bit
8071 // in an xor to conditionally select the adjacent dword.
8072 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8073 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8074 FixFreeIdx) != Inputs.end();
8075 if (IsFixIdxInput == IsFixFreeIdxInput)
8077 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8078 FixFreeIdx) != Inputs.end();
8079 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8080 "We need to be changing the number of flipped inputs!");
8081 int PSHUFHalfMask[] = {0, 1, 2, 3};
8082 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8083 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8085 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8088 if (M != -1 && M == FixIdx)
8090 else if (M != -1 && M == FixFreeIdx)
8093 if (NumFlippedBToBInputs != 0) {
8095 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8096 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8098 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8100 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8101 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8106 int PSHUFDMask[] = {0, 1, 2, 3};
8107 PSHUFDMask[ADWord] = BDWord;
8108 PSHUFDMask[BDWord] = ADWord;
8109 V = DAG.getNode(ISD::BITCAST, DL, VT,
8110 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8111 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8112 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8115 // Adjust the mask to match the new locations of A and B.
8117 if (M != -1 && M/2 == ADWord)
8118 M = 2 * BDWord + M % 2;
8119 else if (M != -1 && M/2 == BDWord)
8120 M = 2 * ADWord + M % 2;
8122 // Recurse back into this routine to re-compute state now that this isn't
8123 // a 3 and 1 problem.
8124 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8127 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8128 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8129 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8130 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8132 // At this point there are at most two inputs to the low and high halves from
8133 // each half. That means the inputs can always be grouped into dwords and
8134 // those dwords can then be moved to the correct half with a dword shuffle.
8135 // We use at most one low and one high word shuffle to collect these paired
8136 // inputs into dwords, and finally a dword shuffle to place them.
8137 int PSHUFLMask[4] = {-1, -1, -1, -1};
8138 int PSHUFHMask[4] = {-1, -1, -1, -1};
8139 int PSHUFDMask[4] = {-1, -1, -1, -1};
8141 // First fix the masks for all the inputs that are staying in their
8142 // original halves. This will then dictate the targets of the cross-half
8144 auto fixInPlaceInputs =
8145 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8146 MutableArrayRef<int> SourceHalfMask,
8147 MutableArrayRef<int> HalfMask, int HalfOffset) {
8148 if (InPlaceInputs.empty())
8150 if (InPlaceInputs.size() == 1) {
8151 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8152 InPlaceInputs[0] - HalfOffset;
8153 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8156 if (IncomingInputs.empty()) {
8157 // Just fix all of the in place inputs.
8158 for (int Input : InPlaceInputs) {
8159 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8160 PSHUFDMask[Input / 2] = Input / 2;
8165 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8166 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8167 InPlaceInputs[0] - HalfOffset;
8168 // Put the second input next to the first so that they are packed into
8169 // a dword. We find the adjacent index by toggling the low bit.
8170 int AdjIndex = InPlaceInputs[0] ^ 1;
8171 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8172 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8173 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8175 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8176 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8178 // Now gather the cross-half inputs and place them into a free dword of
8179 // their target half.
8180 // FIXME: This operation could almost certainly be simplified dramatically to
8181 // look more like the 3-1 fixing operation.
8182 auto moveInputsToRightHalf = [&PSHUFDMask](
8183 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8184 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8185 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8187 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8188 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8190 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8192 int LowWord = Word & ~1;
8193 int HighWord = Word | 1;
8194 return isWordClobbered(SourceHalfMask, LowWord) ||
8195 isWordClobbered(SourceHalfMask, HighWord);
8198 if (IncomingInputs.empty())
8201 if (ExistingInputs.empty()) {
8202 // Map any dwords with inputs from them into the right half.
8203 for (int Input : IncomingInputs) {
8204 // If the source half mask maps over the inputs, turn those into
8205 // swaps and use the swapped lane.
8206 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8207 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8208 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8209 Input - SourceOffset;
8210 // We have to swap the uses in our half mask in one sweep.
8211 for (int &M : HalfMask)
8212 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8214 else if (M == Input)
8215 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8217 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8218 Input - SourceOffset &&
8219 "Previous placement doesn't match!");
8221 // Note that this correctly re-maps both when we do a swap and when
8222 // we observe the other side of the swap above. We rely on that to
8223 // avoid swapping the members of the input list directly.
8224 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8227 // Map the input's dword into the correct half.
8228 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8229 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8231 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8233 "Previous placement doesn't match!");
8236 // And just directly shift any other-half mask elements to be same-half
8237 // as we will have mirrored the dword containing the element into the
8238 // same position within that half.
8239 for (int &M : HalfMask)
8240 if (M >= SourceOffset && M < SourceOffset + 4) {
8241 M = M - SourceOffset + DestOffset;
8242 assert(M >= 0 && "This should never wrap below zero!");
8247 // Ensure we have the input in a viable dword of its current half. This
8248 // is particularly tricky because the original position may be clobbered
8249 // by inputs being moved and *staying* in that half.
8250 if (IncomingInputs.size() == 1) {
8251 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8252 int InputFixed = std::find(std::begin(SourceHalfMask),
8253 std::end(SourceHalfMask), -1) -
8254 std::begin(SourceHalfMask) + SourceOffset;
8255 SourceHalfMask[InputFixed - SourceOffset] =
8256 IncomingInputs[0] - SourceOffset;
8257 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8259 IncomingInputs[0] = InputFixed;
8261 } else if (IncomingInputs.size() == 2) {
8262 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8263 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8264 // We have two non-adjacent or clobbered inputs we need to extract from
8265 // the source half. To do this, we need to map them into some adjacent
8266 // dword slot in the source mask.
8267 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8268 IncomingInputs[1] - SourceOffset};
8270 // If there is a free slot in the source half mask adjacent to one of
8271 // the inputs, place the other input in it. We use (Index XOR 1) to
8272 // compute an adjacent index.
8273 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8274 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8275 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8276 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8277 InputsFixed[1] = InputsFixed[0] ^ 1;
8278 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8279 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8280 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8281 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8282 InputsFixed[0] = InputsFixed[1] ^ 1;
8283 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8284 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8285 // The two inputs are in the same DWord but it is clobbered and the
8286 // adjacent DWord isn't used at all. Move both inputs to the free
8288 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8289 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8290 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8291 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8293 // The only way we hit this point is if there is no clobbering
8294 // (because there are no off-half inputs to this half) and there is no
8295 // free slot adjacent to one of the inputs. In this case, we have to
8296 // swap an input with a non-input.
8297 for (int i = 0; i < 4; ++i)
8298 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8299 "We can't handle any clobbers here!");
8300 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8301 "Cannot have adjacent inputs here!");
8303 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8304 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8306 // We also have to update the final source mask in this case because
8307 // it may need to undo the above swap.
8308 for (int &M : FinalSourceHalfMask)
8309 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8310 M = InputsFixed[1] + SourceOffset;
8311 else if (M == InputsFixed[1] + SourceOffset)
8312 M = (InputsFixed[0] ^ 1) + SourceOffset;
8314 InputsFixed[1] = InputsFixed[0] ^ 1;
8317 // Point everything at the fixed inputs.
8318 for (int &M : HalfMask)
8319 if (M == IncomingInputs[0])
8320 M = InputsFixed[0] + SourceOffset;
8321 else if (M == IncomingInputs[1])
8322 M = InputsFixed[1] + SourceOffset;
8324 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8325 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8328 llvm_unreachable("Unhandled input size!");
8331 // Now hoist the DWord down to the right half.
8332 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8333 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8334 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8335 for (int &M : HalfMask)
8336 for (int Input : IncomingInputs)
8338 M = FreeDWord * 2 + Input % 2;
8340 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8341 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8342 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8343 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8345 // Now enact all the shuffles we've computed to move the inputs into their
8347 if (!isNoopShuffleMask(PSHUFLMask))
8348 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8349 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8350 if (!isNoopShuffleMask(PSHUFHMask))
8351 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8352 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8353 if (!isNoopShuffleMask(PSHUFDMask))
8354 V = DAG.getNode(ISD::BITCAST, DL, VT,
8355 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8356 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8357 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8360 // At this point, each half should contain all its inputs, and we can then
8361 // just shuffle them into their final position.
8362 assert(std::count_if(LoMask.begin(), LoMask.end(),
8363 [](int M) { return M >= 4; }) == 0 &&
8364 "Failed to lift all the high half inputs to the low mask!");
8365 assert(std::count_if(HiMask.begin(), HiMask.end(),
8366 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8367 "Failed to lift all the low half inputs to the high mask!");
8369 // Do a half shuffle for the low mask.
8370 if (!isNoopShuffleMask(LoMask))
8371 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8372 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8374 // Do a half shuffle with the high mask after shifting its values down.
8375 for (int &M : HiMask)
8378 if (!isNoopShuffleMask(HiMask))
8379 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8380 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8385 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8386 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8387 SDValue V2, ArrayRef<int> Mask,
8388 SelectionDAG &DAG, bool &V1InUse,
8390 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8396 int Size = Mask.size();
8397 int Scale = 16 / Size;
8398 for (int i = 0; i < 16; ++i) {
8399 if (Mask[i / Scale] == -1) {
8400 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8402 const int ZeroMask = 0x80;
8403 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8405 int V2Idx = Mask[i / Scale] < Size
8407 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8408 if (Zeroable[i / Scale])
8409 V1Idx = V2Idx = ZeroMask;
8410 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8411 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8412 V1InUse |= (ZeroMask != V1Idx);
8413 V2InUse |= (ZeroMask != V2Idx);
8418 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8419 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8420 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8422 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8423 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8424 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8426 // If we need shuffled inputs from both, blend the two.
8428 if (V1InUse && V2InUse)
8429 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8431 V = V1InUse ? V1 : V2;
8433 // Cast the result back to the correct type.
8434 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8437 /// \brief Generic lowering of 8-lane i16 shuffles.
8439 /// This handles both single-input shuffles and combined shuffle/blends with
8440 /// two inputs. The single input shuffles are immediately delegated to
8441 /// a dedicated lowering routine.
8443 /// The blends are lowered in one of three fundamental ways. If there are few
8444 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8445 /// of the input is significantly cheaper when lowered as an interleaving of
8446 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8447 /// halves of the inputs separately (making them have relatively few inputs)
8448 /// and then concatenate them.
8449 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8450 const X86Subtarget *Subtarget,
8451 SelectionDAG &DAG) {
8453 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8454 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8455 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8456 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8457 ArrayRef<int> OrigMask = SVOp->getMask();
8458 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8459 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8460 MutableArrayRef<int> Mask(MaskStorage);
8462 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8464 // Whenever we can lower this as a zext, that instruction is strictly faster
8465 // than any alternative.
8466 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8467 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8470 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8472 auto isV2 = [](int M) { return M >= 8; };
8474 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8476 if (NumV2Inputs == 0) {
8477 // Check for being able to broadcast a single element.
8478 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8479 Mask, Subtarget, DAG))
8482 // Try to use shift instructions.
8484 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8487 // Use dedicated unpack instructions for masks that match their pattern.
8488 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8489 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8490 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8491 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8493 // Try to use byte rotation instructions.
8494 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8495 Mask, Subtarget, DAG))
8498 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8502 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8503 "All single-input shuffles should be canonicalized to be V1-input "
8506 // Try to use shift instructions.
8508 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8511 // There are special ways we can lower some single-element blends.
8512 if (NumV2Inputs == 1)
8513 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8514 Mask, Subtarget, DAG))
8517 // We have different paths for blend lowering, but they all must use the
8518 // *exact* same predicate.
8519 bool IsBlendSupported = Subtarget->hasSSE41();
8520 if (IsBlendSupported)
8521 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8525 if (SDValue Masked =
8526 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8529 // Use dedicated unpack instructions for masks that match their pattern.
8530 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8531 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8532 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8533 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8535 // Try to use byte rotation instructions.
8536 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8537 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8540 if (SDValue BitBlend =
8541 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8544 if (SDValue Unpack =
8545 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8548 // If we can't directly blend but can use PSHUFB, that will be better as it
8549 // can both shuffle and set up the inefficient blend.
8550 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8551 bool V1InUse, V2InUse;
8552 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8556 // We can always bit-blend if we have to so the fallback strategy is to
8557 // decompose into single-input permutes and blends.
8558 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8562 /// \brief Check whether a compaction lowering can be done by dropping even
8563 /// elements and compute how many times even elements must be dropped.
8565 /// This handles shuffles which take every Nth element where N is a power of
8566 /// two. Example shuffle masks:
8568 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8569 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8570 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8571 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8572 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8573 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8575 /// Any of these lanes can of course be undef.
8577 /// This routine only supports N <= 3.
8578 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8581 /// \returns N above, or the number of times even elements must be dropped if
8582 /// there is such a number. Otherwise returns zero.
8583 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8584 // Figure out whether we're looping over two inputs or just one.
8585 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8587 // The modulus for the shuffle vector entries is based on whether this is
8588 // a single input or not.
8589 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8590 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8591 "We should only be called with masks with a power-of-2 size!");
8593 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8595 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8596 // and 2^3 simultaneously. This is because we may have ambiguity with
8597 // partially undef inputs.
8598 bool ViableForN[3] = {true, true, true};
8600 for (int i = 0, e = Mask.size(); i < e; ++i) {
8601 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8606 bool IsAnyViable = false;
8607 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8608 if (ViableForN[j]) {
8611 // The shuffle mask must be equal to (i * 2^N) % M.
8612 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8615 ViableForN[j] = false;
8617 // Early exit if we exhaust the possible powers of two.
8622 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8626 // Return 0 as there is no viable power of two.
8630 /// \brief Generic lowering of v16i8 shuffles.
8632 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8633 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8634 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8635 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8637 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8638 const X86Subtarget *Subtarget,
8639 SelectionDAG &DAG) {
8641 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8642 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8643 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8644 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8645 ArrayRef<int> Mask = SVOp->getMask();
8646 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8648 // Try to use shift instructions.
8650 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8653 // Try to use byte rotation instructions.
8654 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8655 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8658 // Try to use a zext lowering.
8659 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8660 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8664 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8666 // For single-input shuffles, there are some nicer lowering tricks we can use.
8667 if (NumV2Elements == 0) {
8668 // Check for being able to broadcast a single element.
8669 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8670 Mask, Subtarget, DAG))
8673 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8674 // Notably, this handles splat and partial-splat shuffles more efficiently.
8675 // However, it only makes sense if the pre-duplication shuffle simplifies
8676 // things significantly. Currently, this means we need to be able to
8677 // express the pre-duplication shuffle as an i16 shuffle.
8679 // FIXME: We should check for other patterns which can be widened into an
8680 // i16 shuffle as well.
8681 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8682 for (int i = 0; i < 16; i += 2)
8683 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8688 auto tryToWidenViaDuplication = [&]() -> SDValue {
8689 if (!canWidenViaDuplication(Mask))
8691 SmallVector<int, 4> LoInputs;
8692 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8693 [](int M) { return M >= 0 && M < 8; });
8694 std::sort(LoInputs.begin(), LoInputs.end());
8695 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8697 SmallVector<int, 4> HiInputs;
8698 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8699 [](int M) { return M >= 8; });
8700 std::sort(HiInputs.begin(), HiInputs.end());
8701 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8704 bool TargetLo = LoInputs.size() >= HiInputs.size();
8705 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8706 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8708 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8709 SmallDenseMap<int, int, 8> LaneMap;
8710 for (int I : InPlaceInputs) {
8711 PreDupI16Shuffle[I/2] = I/2;
8714 int j = TargetLo ? 0 : 4, je = j + 4;
8715 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8716 // Check if j is already a shuffle of this input. This happens when
8717 // there are two adjacent bytes after we move the low one.
8718 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8719 // If we haven't yet mapped the input, search for a slot into which
8721 while (j < je && PreDupI16Shuffle[j] != -1)
8725 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8728 // Map this input with the i16 shuffle.
8729 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8732 // Update the lane map based on the mapping we ended up with.
8733 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8736 ISD::BITCAST, DL, MVT::v16i8,
8737 DAG.getVectorShuffle(MVT::v8i16, DL,
8738 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8739 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8741 // Unpack the bytes to form the i16s that will be shuffled into place.
8742 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8743 MVT::v16i8, V1, V1);
8745 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8746 for (int i = 0; i < 16; ++i)
8747 if (Mask[i] != -1) {
8748 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8749 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8750 if (PostDupI16Shuffle[i / 2] == -1)
8751 PostDupI16Shuffle[i / 2] = MappedMask;
8753 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8754 "Conflicting entrties in the original shuffle!");
8757 ISD::BITCAST, DL, MVT::v16i8,
8758 DAG.getVectorShuffle(MVT::v8i16, DL,
8759 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8760 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8762 if (SDValue V = tryToWidenViaDuplication())
8766 // Use dedicated unpack instructions for masks that match their pattern.
8767 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8768 0, 16, 1, 17, 2, 18, 3, 19,
8770 4, 20, 5, 21, 6, 22, 7, 23}))
8771 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8772 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8773 8, 24, 9, 25, 10, 26, 11, 27,
8775 12, 28, 13, 29, 14, 30, 15, 31}))
8776 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8778 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8779 // with PSHUFB. It is important to do this before we attempt to generate any
8780 // blends but after all of the single-input lowerings. If the single input
8781 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8782 // want to preserve that and we can DAG combine any longer sequences into
8783 // a PSHUFB in the end. But once we start blending from multiple inputs,
8784 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8785 // and there are *very* few patterns that would actually be faster than the
8786 // PSHUFB approach because of its ability to zero lanes.
8788 // FIXME: The only exceptions to the above are blends which are exact
8789 // interleavings with direct instructions supporting them. We currently don't
8790 // handle those well here.
8791 if (Subtarget->hasSSSE3()) {
8792 bool V1InUse = false;
8793 bool V2InUse = false;
8795 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8796 DAG, V1InUse, V2InUse);
8798 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8799 // do so. This avoids using them to handle blends-with-zero which is
8800 // important as a single pshufb is significantly faster for that.
8801 if (V1InUse && V2InUse) {
8802 if (Subtarget->hasSSE41())
8803 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8804 Mask, Subtarget, DAG))
8807 // We can use an unpack to do the blending rather than an or in some
8808 // cases. Even though the or may be (very minorly) more efficient, we
8809 // preference this lowering because there are common cases where part of
8810 // the complexity of the shuffles goes away when we do the final blend as
8812 // FIXME: It might be worth trying to detect if the unpack-feeding
8813 // shuffles will both be pshufb, in which case we shouldn't bother with
8815 if (SDValue Unpack =
8816 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8823 // There are special ways we can lower some single-element blends.
8824 if (NumV2Elements == 1)
8825 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8826 Mask, Subtarget, DAG))
8829 if (SDValue BitBlend =
8830 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8833 // Check whether a compaction lowering can be done. This handles shuffles
8834 // which take every Nth element for some even N. See the helper function for
8837 // We special case these as they can be particularly efficiently handled with
8838 // the PACKUSB instruction on x86 and they show up in common patterns of
8839 // rearranging bytes to truncate wide elements.
8840 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8841 // NumEvenDrops is the power of two stride of the elements. Another way of
8842 // thinking about it is that we need to drop the even elements this many
8843 // times to get the original input.
8844 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8846 // First we need to zero all the dropped bytes.
8847 assert(NumEvenDrops <= 3 &&
8848 "No support for dropping even elements more than 3 times.");
8849 // We use the mask type to pick which bytes are preserved based on how many
8850 // elements are dropped.
8851 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8852 SDValue ByteClearMask =
8853 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8854 DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8855 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8857 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8859 // Now pack things back together.
8860 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8861 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8862 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8863 for (int i = 1; i < NumEvenDrops; ++i) {
8864 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8865 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8871 // Handle multi-input cases by blending single-input shuffles.
8872 if (NumV2Elements > 0)
8873 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8876 // The fallback path for single-input shuffles widens this into two v8i16
8877 // vectors with unpacks, shuffles those, and then pulls them back together
8881 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8882 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8883 for (int i = 0; i < 16; ++i)
8885 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8887 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8889 SDValue VLoHalf, VHiHalf;
8890 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8891 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8893 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8894 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8895 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8896 [](int M) { return M >= 0 && M % 2 == 1; })) {
8897 // Use a mask to drop the high bytes.
8898 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8899 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8900 DAG.getConstant(0x00FF, DL, MVT::v8i16));
8902 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8903 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8905 // Squash the masks to point directly into VLoHalf.
8906 for (int &M : LoBlendMask)
8909 for (int &M : HiBlendMask)
8913 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8914 // VHiHalf so that we can blend them as i16s.
8915 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8916 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8917 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8918 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8921 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8922 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8924 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8927 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8929 /// This routine breaks down the specific type of 128-bit shuffle and
8930 /// dispatches to the lowering routines accordingly.
8931 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8932 MVT VT, const X86Subtarget *Subtarget,
8933 SelectionDAG &DAG) {
8934 switch (VT.SimpleTy) {
8936 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8938 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8940 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8942 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8944 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8946 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8949 llvm_unreachable("Unimplemented!");
8953 /// \brief Helper function to test whether a shuffle mask could be
8954 /// simplified by widening the elements being shuffled.
8956 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8957 /// leaves it in an unspecified state.
8959 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8960 /// shuffle masks. The latter have the special property of a '-2' representing
8961 /// a zero-ed lane of a vector.
8962 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8963 SmallVectorImpl<int> &WidenedMask) {
8964 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8965 // If both elements are undef, its trivial.
8966 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8967 WidenedMask.push_back(SM_SentinelUndef);
8971 // Check for an undef mask and a mask value properly aligned to fit with
8972 // a pair of values. If we find such a case, use the non-undef mask's value.
8973 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8974 WidenedMask.push_back(Mask[i + 1] / 2);
8977 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8978 WidenedMask.push_back(Mask[i] / 2);
8982 // When zeroing, we need to spread the zeroing across both lanes to widen.
8983 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8984 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8985 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8986 WidenedMask.push_back(SM_SentinelZero);
8992 // Finally check if the two mask values are adjacent and aligned with
8994 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8995 WidenedMask.push_back(Mask[i] / 2);
8999 // Otherwise we can't safely widen the elements used in this shuffle.
9002 assert(WidenedMask.size() == Mask.size() / 2 &&
9003 "Incorrect size of mask after widening the elements!");
9008 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9010 /// This routine just extracts two subvectors, shuffles them independently, and
9011 /// then concatenates them back together. This should work effectively with all
9012 /// AVX vector shuffle types.
9013 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9014 SDValue V2, ArrayRef<int> Mask,
9015 SelectionDAG &DAG) {
9016 assert(VT.getSizeInBits() >= 256 &&
9017 "Only for 256-bit or wider vector shuffles!");
9018 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9019 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9021 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9022 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9024 int NumElements = VT.getVectorNumElements();
9025 int SplitNumElements = NumElements / 2;
9026 MVT ScalarVT = VT.getScalarType();
9027 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9029 // Rather than splitting build-vectors, just build two narrower build
9030 // vectors. This helps shuffling with splats and zeros.
9031 auto SplitVector = [&](SDValue V) {
9032 while (V.getOpcode() == ISD::BITCAST)
9033 V = V->getOperand(0);
9035 MVT OrigVT = V.getSimpleValueType();
9036 int OrigNumElements = OrigVT.getVectorNumElements();
9037 int OrigSplitNumElements = OrigNumElements / 2;
9038 MVT OrigScalarVT = OrigVT.getScalarType();
9039 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9043 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9045 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9046 DAG.getIntPtrConstant(0, DL));
9047 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9048 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9051 SmallVector<SDValue, 16> LoOps, HiOps;
9052 for (int i = 0; i < OrigSplitNumElements; ++i) {
9053 LoOps.push_back(BV->getOperand(i));
9054 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9056 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9057 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9059 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9060 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9063 SDValue LoV1, HiV1, LoV2, HiV2;
9064 std::tie(LoV1, HiV1) = SplitVector(V1);
9065 std::tie(LoV2, HiV2) = SplitVector(V2);
9067 // Now create two 4-way blends of these half-width vectors.
9068 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9069 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9070 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9071 for (int i = 0; i < SplitNumElements; ++i) {
9072 int M = HalfMask[i];
9073 if (M >= NumElements) {
9074 if (M >= NumElements + SplitNumElements)
9078 V2BlendMask.push_back(M - NumElements);
9079 V1BlendMask.push_back(-1);
9080 BlendMask.push_back(SplitNumElements + i);
9081 } else if (M >= 0) {
9082 if (M >= SplitNumElements)
9086 V2BlendMask.push_back(-1);
9087 V1BlendMask.push_back(M);
9088 BlendMask.push_back(i);
9090 V2BlendMask.push_back(-1);
9091 V1BlendMask.push_back(-1);
9092 BlendMask.push_back(-1);
9096 // Because the lowering happens after all combining takes place, we need to
9097 // manually combine these blend masks as much as possible so that we create
9098 // a minimal number of high-level vector shuffle nodes.
9100 // First try just blending the halves of V1 or V2.
9101 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9102 return DAG.getUNDEF(SplitVT);
9103 if (!UseLoV2 && !UseHiV2)
9104 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9105 if (!UseLoV1 && !UseHiV1)
9106 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9108 SDValue V1Blend, V2Blend;
9109 if (UseLoV1 && UseHiV1) {
9111 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9113 // We only use half of V1 so map the usage down into the final blend mask.
9114 V1Blend = UseLoV1 ? LoV1 : HiV1;
9115 for (int i = 0; i < SplitNumElements; ++i)
9116 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9117 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9119 if (UseLoV2 && UseHiV2) {
9121 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9123 // We only use half of V2 so map the usage down into the final blend mask.
9124 V2Blend = UseLoV2 ? LoV2 : HiV2;
9125 for (int i = 0; i < SplitNumElements; ++i)
9126 if (BlendMask[i] >= SplitNumElements)
9127 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9129 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9131 SDValue Lo = HalfBlend(LoMask);
9132 SDValue Hi = HalfBlend(HiMask);
9133 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9136 /// \brief Either split a vector in halves or decompose the shuffles and the
9139 /// This is provided as a good fallback for many lowerings of non-single-input
9140 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9141 /// between splitting the shuffle into 128-bit components and stitching those
9142 /// back together vs. extracting the single-input shuffles and blending those
9144 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9145 SDValue V2, ArrayRef<int> Mask,
9146 SelectionDAG &DAG) {
9147 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9148 "lower single-input shuffles as it "
9149 "could then recurse on itself.");
9150 int Size = Mask.size();
9152 // If this can be modeled as a broadcast of two elements followed by a blend,
9153 // prefer that lowering. This is especially important because broadcasts can
9154 // often fold with memory operands.
9155 auto DoBothBroadcast = [&] {
9156 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9159 if (V2BroadcastIdx == -1)
9160 V2BroadcastIdx = M - Size;
9161 else if (M - Size != V2BroadcastIdx)
9163 } else if (M >= 0) {
9164 if (V1BroadcastIdx == -1)
9166 else if (M != V1BroadcastIdx)
9171 if (DoBothBroadcast())
9172 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9175 // If the inputs all stem from a single 128-bit lane of each input, then we
9176 // split them rather than blending because the split will decompose to
9177 // unusually few instructions.
9178 int LaneCount = VT.getSizeInBits() / 128;
9179 int LaneSize = Size / LaneCount;
9180 SmallBitVector LaneInputs[2];
9181 LaneInputs[0].resize(LaneCount, false);
9182 LaneInputs[1].resize(LaneCount, false);
9183 for (int i = 0; i < Size; ++i)
9185 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9186 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9187 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9189 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9190 // that the decomposed single-input shuffles don't end up here.
9191 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9194 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9195 /// a permutation and blend of those lanes.
9197 /// This essentially blends the out-of-lane inputs to each lane into the lane
9198 /// from a permuted copy of the vector. This lowering strategy results in four
9199 /// instructions in the worst case for a single-input cross lane shuffle which
9200 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9201 /// of. Special cases for each particular shuffle pattern should be handled
9202 /// prior to trying this lowering.
9203 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9204 SDValue V1, SDValue V2,
9206 SelectionDAG &DAG) {
9207 // FIXME: This should probably be generalized for 512-bit vectors as well.
9208 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9209 int LaneSize = Mask.size() / 2;
9211 // If there are only inputs from one 128-bit lane, splitting will in fact be
9212 // less expensive. The flags track whether the given lane contains an element
9213 // that crosses to another lane.
9214 bool LaneCrossing[2] = {false, false};
9215 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9216 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9217 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9218 if (!LaneCrossing[0] || !LaneCrossing[1])
9219 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9221 if (isSingleInputShuffleMask(Mask)) {
9222 SmallVector<int, 32> FlippedBlendMask;
9223 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9224 FlippedBlendMask.push_back(
9225 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9227 : Mask[i] % LaneSize +
9228 (i / LaneSize) * LaneSize + Size));
9230 // Flip the vector, and blend the results which should now be in-lane. The
9231 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9232 // 5 for the high source. The value 3 selects the high half of source 2 and
9233 // the value 2 selects the low half of source 2. We only use source 2 to
9234 // allow folding it into a memory operand.
9235 unsigned PERMMask = 3 | 2 << 4;
9236 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9237 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9238 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9241 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9242 // will be handled by the above logic and a blend of the results, much like
9243 // other patterns in AVX.
9244 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9247 /// \brief Handle lowering 2-lane 128-bit shuffles.
9248 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9249 SDValue V2, ArrayRef<int> Mask,
9250 const X86Subtarget *Subtarget,
9251 SelectionDAG &DAG) {
9252 // TODO: If minimizing size and one of the inputs is a zero vector and the
9253 // the zero vector has only one use, we could use a VPERM2X128 to save the
9254 // instruction bytes needed to explicitly generate the zero vector.
9256 // Blends are faster and handle all the non-lane-crossing cases.
9257 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9261 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9262 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9264 // If either input operand is a zero vector, use VPERM2X128 because its mask
9265 // allows us to replace the zero input with an implicit zero.
9266 if (!IsV1Zero && !IsV2Zero) {
9267 // Check for patterns which can be matched with a single insert of a 128-bit
9269 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9270 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9271 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9272 VT.getVectorNumElements() / 2);
9273 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9274 DAG.getIntPtrConstant(0, DL));
9275 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9276 OnlyUsesV1 ? V1 : V2,
9277 DAG.getIntPtrConstant(0, DL));
9278 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9282 // Otherwise form a 128-bit permutation. After accounting for undefs,
9283 // convert the 64-bit shuffle mask selection values into 128-bit
9284 // selection bits by dividing the indexes by 2 and shifting into positions
9285 // defined by a vperm2*128 instruction's immediate control byte.
9287 // The immediate permute control byte looks like this:
9288 // [1:0] - select 128 bits from sources for low half of destination
9290 // [3] - zero low half of destination
9291 // [5:4] - select 128 bits from sources for high half of destination
9293 // [7] - zero high half of destination
9295 int MaskLO = Mask[0];
9296 if (MaskLO == SM_SentinelUndef)
9297 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9299 int MaskHI = Mask[2];
9300 if (MaskHI == SM_SentinelUndef)
9301 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9303 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9305 // If either input is a zero vector, replace it with an undef input.
9306 // Shuffle mask values < 4 are selecting elements of V1.
9307 // Shuffle mask values >= 4 are selecting elements of V2.
9308 // Adjust each half of the permute mask by clearing the half that was
9309 // selecting the zero vector and setting the zero mask bit.
9311 V1 = DAG.getUNDEF(VT);
9313 PermMask = (PermMask & 0xf0) | 0x08;
9315 PermMask = (PermMask & 0x0f) | 0x80;
9318 V2 = DAG.getUNDEF(VT);
9320 PermMask = (PermMask & 0xf0) | 0x08;
9322 PermMask = (PermMask & 0x0f) | 0x80;
9325 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9326 DAG.getConstant(PermMask, DL, MVT::i8));
9329 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9330 /// shuffling each lane.
9332 /// This will only succeed when the result of fixing the 128-bit lanes results
9333 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9334 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9335 /// the lane crosses early and then use simpler shuffles within each lane.
9337 /// FIXME: It might be worthwhile at some point to support this without
9338 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9339 /// in x86 only floating point has interesting non-repeating shuffles, and even
9340 /// those are still *marginally* more expensive.
9341 static SDValue lowerVectorShuffleByMerging128BitLanes(
9342 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9343 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9344 assert(!isSingleInputShuffleMask(Mask) &&
9345 "This is only useful with multiple inputs.");
9347 int Size = Mask.size();
9348 int LaneSize = 128 / VT.getScalarSizeInBits();
9349 int NumLanes = Size / LaneSize;
9350 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9352 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9353 // check whether the in-128-bit lane shuffles share a repeating pattern.
9354 SmallVector<int, 4> Lanes;
9355 Lanes.resize(NumLanes, -1);
9356 SmallVector<int, 4> InLaneMask;
9357 InLaneMask.resize(LaneSize, -1);
9358 for (int i = 0; i < Size; ++i) {
9362 int j = i / LaneSize;
9365 // First entry we've seen for this lane.
9366 Lanes[j] = Mask[i] / LaneSize;
9367 } else if (Lanes[j] != Mask[i] / LaneSize) {
9368 // This doesn't match the lane selected previously!
9372 // Check that within each lane we have a consistent shuffle mask.
9373 int k = i % LaneSize;
9374 if (InLaneMask[k] < 0) {
9375 InLaneMask[k] = Mask[i] % LaneSize;
9376 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9377 // This doesn't fit a repeating in-lane mask.
9382 // First shuffle the lanes into place.
9383 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9384 VT.getSizeInBits() / 64);
9385 SmallVector<int, 8> LaneMask;
9386 LaneMask.resize(NumLanes * 2, -1);
9387 for (int i = 0; i < NumLanes; ++i)
9388 if (Lanes[i] >= 0) {
9389 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9390 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9393 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9394 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9395 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9397 // Cast it back to the type we actually want.
9398 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9400 // Now do a simple shuffle that isn't lane crossing.
9401 SmallVector<int, 8> NewMask;
9402 NewMask.resize(Size, -1);
9403 for (int i = 0; i < Size; ++i)
9405 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9406 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9407 "Must not introduce lane crosses at this point!");
9409 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9412 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9415 /// This returns true if the elements from a particular input are already in the
9416 /// slot required by the given mask and require no permutation.
9417 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9418 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9419 int Size = Mask.size();
9420 for (int i = 0; i < Size; ++i)
9421 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9427 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9429 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9430 /// isn't available.
9431 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9432 const X86Subtarget *Subtarget,
9433 SelectionDAG &DAG) {
9435 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9436 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9437 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9438 ArrayRef<int> Mask = SVOp->getMask();
9439 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9441 SmallVector<int, 4> WidenedMask;
9442 if (canWidenShuffleElements(Mask, WidenedMask))
9443 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9446 if (isSingleInputShuffleMask(Mask)) {
9447 // Check for being able to broadcast a single element.
9448 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9449 Mask, Subtarget, DAG))
9452 // Use low duplicate instructions for masks that match their pattern.
9453 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9454 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9456 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9457 // Non-half-crossing single input shuffles can be lowerid with an
9458 // interleaved permutation.
9459 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9460 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9461 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9462 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9465 // With AVX2 we have direct support for this permutation.
9466 if (Subtarget->hasAVX2())
9467 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9468 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9470 // Otherwise, fall back.
9471 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9475 // X86 has dedicated unpack instructions that can handle specific blend
9476 // operations: UNPCKH and UNPCKL.
9477 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9478 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9479 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9480 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9481 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9482 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9483 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9484 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9486 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9490 // Check if the blend happens to exactly fit that of SHUFPD.
9491 if ((Mask[0] == -1 || Mask[0] < 2) &&
9492 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9493 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9494 (Mask[3] == -1 || Mask[3] >= 6)) {
9495 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9496 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9497 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9498 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9500 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9501 (Mask[1] == -1 || Mask[1] < 2) &&
9502 (Mask[2] == -1 || Mask[2] >= 6) &&
9503 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9504 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9505 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9506 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9507 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9510 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9511 // shuffle. However, if we have AVX2 and either inputs are already in place,
9512 // we will be able to shuffle even across lanes the other input in a single
9513 // instruction so skip this pattern.
9514 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9515 isShuffleMaskInputInPlace(1, Mask))))
9516 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9517 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9520 // If we have AVX2 then we always want to lower with a blend because an v4 we
9521 // can fully permute the elements.
9522 if (Subtarget->hasAVX2())
9523 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9526 // Otherwise fall back on generic lowering.
9527 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9530 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9532 /// This routine is only called when we have AVX2 and thus a reasonable
9533 /// instruction set for v4i64 shuffling..
9534 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9535 const X86Subtarget *Subtarget,
9536 SelectionDAG &DAG) {
9538 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9539 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9540 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9541 ArrayRef<int> Mask = SVOp->getMask();
9542 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9543 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9545 SmallVector<int, 4> WidenedMask;
9546 if (canWidenShuffleElements(Mask, WidenedMask))
9547 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9550 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9554 // Check for being able to broadcast a single element.
9555 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9556 Mask, Subtarget, DAG))
9559 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9560 // use lower latency instructions that will operate on both 128-bit lanes.
9561 SmallVector<int, 2> RepeatedMask;
9562 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9563 if (isSingleInputShuffleMask(Mask)) {
9564 int PSHUFDMask[] = {-1, -1, -1, -1};
9565 for (int i = 0; i < 2; ++i)
9566 if (RepeatedMask[i] >= 0) {
9567 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9568 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9571 ISD::BITCAST, DL, MVT::v4i64,
9572 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9573 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9574 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9578 // AVX2 provides a direct instruction for permuting a single input across
9580 if (isSingleInputShuffleMask(Mask))
9581 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9582 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9584 // Try to use shift instructions.
9586 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9589 // Use dedicated unpack instructions for masks that match their pattern.
9590 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9591 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9592 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9593 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9594 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9595 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9596 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9597 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9599 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9600 // shuffle. However, if we have AVX2 and either inputs are already in place,
9601 // we will be able to shuffle even across lanes the other input in a single
9602 // instruction so skip this pattern.
9603 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9604 isShuffleMaskInputInPlace(1, Mask))))
9605 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9606 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9609 // Otherwise fall back on generic blend lowering.
9610 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9614 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9616 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9617 /// isn't available.
9618 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9619 const X86Subtarget *Subtarget,
9620 SelectionDAG &DAG) {
9622 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9623 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9624 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9625 ArrayRef<int> Mask = SVOp->getMask();
9626 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9628 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9632 // Check for being able to broadcast a single element.
9633 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9634 Mask, Subtarget, DAG))
9637 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9638 // options to efficiently lower the shuffle.
9639 SmallVector<int, 4> RepeatedMask;
9640 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9641 assert(RepeatedMask.size() == 4 &&
9642 "Repeated masks must be half the mask width!");
9644 // Use even/odd duplicate instructions for masks that match their pattern.
9645 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9646 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9647 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9648 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9650 if (isSingleInputShuffleMask(Mask))
9651 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9652 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9654 // Use dedicated unpack instructions for masks that match their pattern.
9655 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9656 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9657 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9658 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9659 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9660 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9661 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9662 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9664 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9665 // have already handled any direct blends. We also need to squash the
9666 // repeated mask into a simulated v4f32 mask.
9667 for (int i = 0; i < 4; ++i)
9668 if (RepeatedMask[i] >= 8)
9669 RepeatedMask[i] -= 4;
9670 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9673 // If we have a single input shuffle with different shuffle patterns in the
9674 // two 128-bit lanes use the variable mask to VPERMILPS.
9675 if (isSingleInputShuffleMask(Mask)) {
9676 SDValue VPermMask[8];
9677 for (int i = 0; i < 8; ++i)
9678 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9679 : DAG.getConstant(Mask[i], DL, MVT::i32);
9680 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9682 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9683 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9685 if (Subtarget->hasAVX2())
9686 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9687 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9688 DAG.getNode(ISD::BUILD_VECTOR, DL,
9689 MVT::v8i32, VPermMask)),
9692 // Otherwise, fall back.
9693 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9697 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9699 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9700 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9703 // If we have AVX2 then we always want to lower with a blend because at v8 we
9704 // can fully permute the elements.
9705 if (Subtarget->hasAVX2())
9706 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9709 // Otherwise fall back on generic lowering.
9710 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9713 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9715 /// This routine is only called when we have AVX2 and thus a reasonable
9716 /// instruction set for v8i32 shuffling..
9717 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9718 const X86Subtarget *Subtarget,
9719 SelectionDAG &DAG) {
9721 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9722 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9723 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9724 ArrayRef<int> Mask = SVOp->getMask();
9725 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9726 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9728 // Whenever we can lower this as a zext, that instruction is strictly faster
9729 // than any alternative. It also allows us to fold memory operands into the
9730 // shuffle in many cases.
9731 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9732 Mask, Subtarget, DAG))
9735 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9739 // Check for being able to broadcast a single element.
9740 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9741 Mask, Subtarget, DAG))
9744 // If the shuffle mask is repeated in each 128-bit lane we can use more
9745 // efficient instructions that mirror the shuffles across the two 128-bit
9747 SmallVector<int, 4> RepeatedMask;
9748 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9749 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9750 if (isSingleInputShuffleMask(Mask))
9751 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9752 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9754 // Use dedicated unpack instructions for masks that match their pattern.
9755 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9756 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9757 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9758 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9759 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9760 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9761 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9762 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9765 // Try to use shift instructions.
9767 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9770 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9771 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9774 // If the shuffle patterns aren't repeated but it is a single input, directly
9775 // generate a cross-lane VPERMD instruction.
9776 if (isSingleInputShuffleMask(Mask)) {
9777 SDValue VPermMask[8];
9778 for (int i = 0; i < 8; ++i)
9779 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9780 : DAG.getConstant(Mask[i], DL, MVT::i32);
9782 X86ISD::VPERMV, DL, MVT::v8i32,
9783 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9786 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9788 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9789 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9792 // Otherwise fall back on generic blend lowering.
9793 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9797 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9799 /// This routine is only called when we have AVX2 and thus a reasonable
9800 /// instruction set for v16i16 shuffling..
9801 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9802 const X86Subtarget *Subtarget,
9803 SelectionDAG &DAG) {
9805 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9806 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9807 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9808 ArrayRef<int> Mask = SVOp->getMask();
9809 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9810 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9812 // Whenever we can lower this as a zext, that instruction is strictly faster
9813 // than any alternative. It also allows us to fold memory operands into the
9814 // shuffle in many cases.
9815 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9816 Mask, Subtarget, DAG))
9819 // Check for being able to broadcast a single element.
9820 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9821 Mask, Subtarget, DAG))
9824 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9828 // Use dedicated unpack instructions for masks that match their pattern.
9829 if (isShuffleEquivalent(V1, V2, Mask,
9830 {// First 128-bit lane:
9831 0, 16, 1, 17, 2, 18, 3, 19,
9832 // Second 128-bit lane:
9833 8, 24, 9, 25, 10, 26, 11, 27}))
9834 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9835 if (isShuffleEquivalent(V1, V2, Mask,
9836 {// First 128-bit lane:
9837 4, 20, 5, 21, 6, 22, 7, 23,
9838 // Second 128-bit lane:
9839 12, 28, 13, 29, 14, 30, 15, 31}))
9840 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9842 // Try to use shift instructions.
9844 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9847 // Try to use byte rotation instructions.
9848 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9849 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9852 if (isSingleInputShuffleMask(Mask)) {
9853 // There are no generalized cross-lane shuffle operations available on i16
9855 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9856 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9859 SmallVector<int, 8> RepeatedMask;
9860 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9861 // As this is a single-input shuffle, the repeated mask should be
9862 // a strictly valid v8i16 mask that we can pass through to the v8i16
9863 // lowering to handle even the v16 case.
9864 return lowerV8I16GeneralSingleInputVectorShuffle(
9865 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9868 SDValue PSHUFBMask[32];
9869 for (int i = 0; i < 16; ++i) {
9870 if (Mask[i] == -1) {
9871 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9875 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9876 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9877 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9878 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9881 ISD::BITCAST, DL, MVT::v16i16,
9883 X86ISD::PSHUFB, DL, MVT::v32i8,
9884 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9885 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9888 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9890 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9891 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9894 // Otherwise fall back on generic lowering.
9895 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9898 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9900 /// This routine is only called when we have AVX2 and thus a reasonable
9901 /// instruction set for v32i8 shuffling..
9902 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9903 const X86Subtarget *Subtarget,
9904 SelectionDAG &DAG) {
9906 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9907 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9908 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9909 ArrayRef<int> Mask = SVOp->getMask();
9910 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9911 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9913 // Whenever we can lower this as a zext, that instruction is strictly faster
9914 // than any alternative. It also allows us to fold memory operands into the
9915 // shuffle in many cases.
9916 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9917 Mask, Subtarget, DAG))
9920 // Check for being able to broadcast a single element.
9921 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9922 Mask, Subtarget, DAG))
9925 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9929 // Use dedicated unpack instructions for masks that match their pattern.
9930 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9932 if (isShuffleEquivalent(
9934 {// First 128-bit lane:
9935 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9936 // Second 128-bit lane:
9937 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9938 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9939 if (isShuffleEquivalent(
9941 {// First 128-bit lane:
9942 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9943 // Second 128-bit lane:
9944 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9945 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9947 // Try to use shift instructions.
9949 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9952 // Try to use byte rotation instructions.
9953 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9954 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9957 if (isSingleInputShuffleMask(Mask)) {
9958 // There are no generalized cross-lane shuffle operations available on i8
9960 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9961 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9964 SDValue PSHUFBMask[32];
9965 for (int i = 0; i < 32; ++i)
9968 ? DAG.getUNDEF(MVT::i8)
9969 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9973 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9974 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9977 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9979 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9980 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9983 // Otherwise fall back on generic lowering.
9984 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9987 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9989 /// This routine either breaks down the specific type of a 256-bit x86 vector
9990 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9991 /// together based on the available instructions.
9992 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9993 MVT VT, const X86Subtarget *Subtarget,
9994 SelectionDAG &DAG) {
9996 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9997 ArrayRef<int> Mask = SVOp->getMask();
9999 // If we have a single input to the zero element, insert that into V1 if we
10000 // can do so cheaply.
10001 int NumElts = VT.getVectorNumElements();
10002 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10003 return M >= NumElts;
10006 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10007 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10008 DL, VT, V1, V2, Mask, Subtarget, DAG))
10011 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10012 // check for those subtargets here and avoid much of the subtarget querying in
10013 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10014 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10015 // floating point types there eventually, just immediately cast everything to
10016 // a float and operate entirely in that domain.
10017 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10018 int ElementBits = VT.getScalarSizeInBits();
10019 if (ElementBits < 32)
10020 // No floating point type available, decompose into 128-bit vectors.
10021 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10023 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10024 VT.getVectorNumElements());
10025 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10026 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10027 return DAG.getNode(ISD::BITCAST, DL, VT,
10028 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10031 switch (VT.SimpleTy) {
10033 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10035 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10037 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10039 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10041 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10043 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10046 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10050 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10051 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10052 const X86Subtarget *Subtarget,
10053 SelectionDAG &DAG) {
10055 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10056 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10057 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10058 ArrayRef<int> Mask = SVOp->getMask();
10059 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10061 // X86 has dedicated unpack instructions that can handle specific blend
10062 // operations: UNPCKH and UNPCKL.
10063 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10064 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10065 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10066 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10068 // FIXME: Implement direct support for this type!
10069 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10072 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10073 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10074 const X86Subtarget *Subtarget,
10075 SelectionDAG &DAG) {
10077 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10078 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10079 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10080 ArrayRef<int> Mask = SVOp->getMask();
10081 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10083 // Use dedicated unpack instructions for masks that match their pattern.
10084 if (isShuffleEquivalent(V1, V2, Mask,
10085 {// First 128-bit lane.
10086 0, 16, 1, 17, 4, 20, 5, 21,
10087 // Second 128-bit lane.
10088 8, 24, 9, 25, 12, 28, 13, 29}))
10089 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10090 if (isShuffleEquivalent(V1, V2, Mask,
10091 {// First 128-bit lane.
10092 2, 18, 3, 19, 6, 22, 7, 23,
10093 // Second 128-bit lane.
10094 10, 26, 11, 27, 14, 30, 15, 31}))
10095 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10097 // FIXME: Implement direct support for this type!
10098 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10101 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10102 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10103 const X86Subtarget *Subtarget,
10104 SelectionDAG &DAG) {
10106 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10107 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10108 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10109 ArrayRef<int> Mask = SVOp->getMask();
10110 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10112 // X86 has dedicated unpack instructions that can handle specific blend
10113 // operations: UNPCKH and UNPCKL.
10114 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10115 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10116 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10117 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10119 // FIXME: Implement direct support for this type!
10120 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10123 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10124 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10125 const X86Subtarget *Subtarget,
10126 SelectionDAG &DAG) {
10128 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10129 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10130 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10131 ArrayRef<int> Mask = SVOp->getMask();
10132 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10134 // Use dedicated unpack instructions for masks that match their pattern.
10135 if (isShuffleEquivalent(V1, V2, Mask,
10136 {// First 128-bit lane.
10137 0, 16, 1, 17, 4, 20, 5, 21,
10138 // Second 128-bit lane.
10139 8, 24, 9, 25, 12, 28, 13, 29}))
10140 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10141 if (isShuffleEquivalent(V1, V2, Mask,
10142 {// First 128-bit lane.
10143 2, 18, 3, 19, 6, 22, 7, 23,
10144 // Second 128-bit lane.
10145 10, 26, 11, 27, 14, 30, 15, 31}))
10146 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10148 // FIXME: Implement direct support for this type!
10149 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10152 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10153 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10154 const X86Subtarget *Subtarget,
10155 SelectionDAG &DAG) {
10157 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10158 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10159 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10160 ArrayRef<int> Mask = SVOp->getMask();
10161 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10162 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10164 // FIXME: Implement direct support for this type!
10165 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10168 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10169 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10170 const X86Subtarget *Subtarget,
10171 SelectionDAG &DAG) {
10173 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10174 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10175 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10176 ArrayRef<int> Mask = SVOp->getMask();
10177 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10178 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10180 // FIXME: Implement direct support for this type!
10181 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10184 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10186 /// This routine either breaks down the specific type of a 512-bit x86 vector
10187 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10188 /// together based on the available instructions.
10189 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10190 MVT VT, const X86Subtarget *Subtarget,
10191 SelectionDAG &DAG) {
10193 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10194 ArrayRef<int> Mask = SVOp->getMask();
10195 assert(Subtarget->hasAVX512() &&
10196 "Cannot lower 512-bit vectors w/ basic ISA!");
10198 // Check for being able to broadcast a single element.
10199 if (SDValue Broadcast =
10200 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10203 // Dispatch to each element type for lowering. If we don't have supprot for
10204 // specific element type shuffles at 512 bits, immediately split them and
10205 // lower them. Each lowering routine of a given type is allowed to assume that
10206 // the requisite ISA extensions for that element type are available.
10207 switch (VT.SimpleTy) {
10209 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10211 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10213 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10215 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10217 if (Subtarget->hasBWI())
10218 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10221 if (Subtarget->hasBWI())
10222 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10226 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10229 // Otherwise fall back on splitting.
10230 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10233 /// \brief Top-level lowering for x86 vector shuffles.
10235 /// This handles decomposition, canonicalization, and lowering of all x86
10236 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10237 /// above in helper routines. The canonicalization attempts to widen shuffles
10238 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10239 /// s.t. only one of the two inputs needs to be tested, etc.
10240 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10241 SelectionDAG &DAG) {
10242 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10243 ArrayRef<int> Mask = SVOp->getMask();
10244 SDValue V1 = Op.getOperand(0);
10245 SDValue V2 = Op.getOperand(1);
10246 MVT VT = Op.getSimpleValueType();
10247 int NumElements = VT.getVectorNumElements();
10250 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10252 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10253 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10254 if (V1IsUndef && V2IsUndef)
10255 return DAG.getUNDEF(VT);
10257 // When we create a shuffle node we put the UNDEF node to second operand,
10258 // but in some cases the first operand may be transformed to UNDEF.
10259 // In this case we should just commute the node.
10261 return DAG.getCommutedVectorShuffle(*SVOp);
10263 // Check for non-undef masks pointing at an undef vector and make the masks
10264 // undef as well. This makes it easier to match the shuffle based solely on
10268 if (M >= NumElements) {
10269 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10270 for (int &M : NewMask)
10271 if (M >= NumElements)
10273 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10276 // We actually see shuffles that are entirely re-arrangements of a set of
10277 // zero inputs. This mostly happens while decomposing complex shuffles into
10278 // simple ones. Directly lower these as a buildvector of zeros.
10279 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10280 if (Zeroable.all())
10281 return getZeroVector(VT, Subtarget, DAG, dl);
10283 // Try to collapse shuffles into using a vector type with fewer elements but
10284 // wider element types. We cap this to not form integers or floating point
10285 // elements wider than 64 bits, but it might be interesting to form i128
10286 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10287 SmallVector<int, 16> WidenedMask;
10288 if (VT.getScalarSizeInBits() < 64 &&
10289 canWidenShuffleElements(Mask, WidenedMask)) {
10290 MVT NewEltVT = VT.isFloatingPoint()
10291 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10292 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10293 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10294 // Make sure that the new vector type is legal. For example, v2f64 isn't
10296 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10297 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10298 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10299 return DAG.getNode(ISD::BITCAST, dl, VT,
10300 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10304 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10305 for (int M : SVOp->getMask())
10307 ++NumUndefElements;
10308 else if (M < NumElements)
10313 // Commute the shuffle as needed such that more elements come from V1 than
10314 // V2. This allows us to match the shuffle pattern strictly on how many
10315 // elements come from V1 without handling the symmetric cases.
10316 if (NumV2Elements > NumV1Elements)
10317 return DAG.getCommutedVectorShuffle(*SVOp);
10319 // When the number of V1 and V2 elements are the same, try to minimize the
10320 // number of uses of V2 in the low half of the vector. When that is tied,
10321 // ensure that the sum of indices for V1 is equal to or lower than the sum
10322 // indices for V2. When those are equal, try to ensure that the number of odd
10323 // indices for V1 is lower than the number of odd indices for V2.
10324 if (NumV1Elements == NumV2Elements) {
10325 int LowV1Elements = 0, LowV2Elements = 0;
10326 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10327 if (M >= NumElements)
10331 if (LowV2Elements > LowV1Elements) {
10332 return DAG.getCommutedVectorShuffle(*SVOp);
10333 } else if (LowV2Elements == LowV1Elements) {
10334 int SumV1Indices = 0, SumV2Indices = 0;
10335 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10336 if (SVOp->getMask()[i] >= NumElements)
10338 else if (SVOp->getMask()[i] >= 0)
10340 if (SumV2Indices < SumV1Indices) {
10341 return DAG.getCommutedVectorShuffle(*SVOp);
10342 } else if (SumV2Indices == SumV1Indices) {
10343 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10344 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10345 if (SVOp->getMask()[i] >= NumElements)
10346 NumV2OddIndices += i % 2;
10347 else if (SVOp->getMask()[i] >= 0)
10348 NumV1OddIndices += i % 2;
10349 if (NumV2OddIndices < NumV1OddIndices)
10350 return DAG.getCommutedVectorShuffle(*SVOp);
10355 // For each vector width, delegate to a specialized lowering routine.
10356 if (VT.getSizeInBits() == 128)
10357 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10359 if (VT.getSizeInBits() == 256)
10360 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10362 // Force AVX-512 vectors to be scalarized for now.
10363 // FIXME: Implement AVX-512 support!
10364 if (VT.getSizeInBits() == 512)
10365 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10367 llvm_unreachable("Unimplemented!");
10370 // This function assumes its argument is a BUILD_VECTOR of constants or
10371 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10373 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10374 unsigned &MaskValue) {
10376 unsigned NumElems = BuildVector->getNumOperands();
10377 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10378 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10379 unsigned NumElemsInLane = NumElems / NumLanes;
10381 // Blend for v16i16 should be symetric for the both lanes.
10382 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10383 SDValue EltCond = BuildVector->getOperand(i);
10384 SDValue SndLaneEltCond =
10385 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10387 int Lane1Cond = -1, Lane2Cond = -1;
10388 if (isa<ConstantSDNode>(EltCond))
10389 Lane1Cond = !isZero(EltCond);
10390 if (isa<ConstantSDNode>(SndLaneEltCond))
10391 Lane2Cond = !isZero(SndLaneEltCond);
10393 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10394 // Lane1Cond != 0, means we want the first argument.
10395 // Lane1Cond == 0, means we want the second argument.
10396 // The encoding of this argument is 0 for the first argument, 1
10397 // for the second. Therefore, invert the condition.
10398 MaskValue |= !Lane1Cond << i;
10399 else if (Lane1Cond < 0)
10400 MaskValue |= !Lane2Cond << i;
10407 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10408 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10409 const X86Subtarget *Subtarget,
10410 SelectionDAG &DAG) {
10411 SDValue Cond = Op.getOperand(0);
10412 SDValue LHS = Op.getOperand(1);
10413 SDValue RHS = Op.getOperand(2);
10415 MVT VT = Op.getSimpleValueType();
10417 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10419 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10421 // Only non-legal VSELECTs reach this lowering, convert those into generic
10422 // shuffles and re-use the shuffle lowering path for blends.
10423 SmallVector<int, 32> Mask;
10424 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10425 SDValue CondElt = CondBV->getOperand(i);
10427 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10429 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10432 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10433 // A vselect where all conditions and data are constants can be optimized into
10434 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10435 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10436 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10437 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10440 // Try to lower this to a blend-style vector shuffle. This can handle all
10441 // constant condition cases.
10442 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10445 // Variable blends are only legal from SSE4.1 onward.
10446 if (!Subtarget->hasSSE41())
10449 // Only some types will be legal on some subtargets. If we can emit a legal
10450 // VSELECT-matching blend, return Op, and but if we need to expand, return
10452 switch (Op.getSimpleValueType().SimpleTy) {
10454 // Most of the vector types have blends past SSE4.1.
10458 // The byte blends for AVX vectors were introduced only in AVX2.
10459 if (Subtarget->hasAVX2())
10466 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10467 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10470 // FIXME: We should custom lower this by fixing the condition and using i8
10476 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10477 MVT VT = Op.getSimpleValueType();
10480 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10483 if (VT.getSizeInBits() == 8) {
10484 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10485 Op.getOperand(0), Op.getOperand(1));
10486 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10487 DAG.getValueType(VT));
10488 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10491 if (VT.getSizeInBits() == 16) {
10492 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10493 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10495 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10496 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10497 DAG.getNode(ISD::BITCAST, dl,
10500 Op.getOperand(1)));
10501 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10502 Op.getOperand(0), Op.getOperand(1));
10503 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10504 DAG.getValueType(VT));
10505 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10508 if (VT == MVT::f32) {
10509 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10510 // the result back to FR32 register. It's only worth matching if the
10511 // result has a single use which is a store or a bitcast to i32. And in
10512 // the case of a store, it's not worth it if the index is a constant 0,
10513 // because a MOVSSmr can be used instead, which is smaller and faster.
10514 if (!Op.hasOneUse())
10516 SDNode *User = *Op.getNode()->use_begin();
10517 if ((User->getOpcode() != ISD::STORE ||
10518 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10519 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10520 (User->getOpcode() != ISD::BITCAST ||
10521 User->getValueType(0) != MVT::i32))
10523 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10524 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10527 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10530 if (VT == MVT::i32 || VT == MVT::i64) {
10531 // ExtractPS/pextrq works with constant index.
10532 if (isa<ConstantSDNode>(Op.getOperand(1)))
10538 /// Extract one bit from mask vector, like v16i1 or v8i1.
10539 /// AVX-512 feature.
10541 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10542 SDValue Vec = Op.getOperand(0);
10544 MVT VecVT = Vec.getSimpleValueType();
10545 SDValue Idx = Op.getOperand(1);
10546 MVT EltVT = Op.getSimpleValueType();
10548 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10549 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10550 "Unexpected vector type in ExtractBitFromMaskVector");
10552 // variable index can't be handled in mask registers,
10553 // extend vector to VR512
10554 if (!isa<ConstantSDNode>(Idx)) {
10555 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10556 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10557 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10558 ExtVT.getVectorElementType(), Ext, Idx);
10559 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10562 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10563 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10564 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10565 rc = getRegClassFor(MVT::v16i1);
10566 unsigned MaxSift = rc->getSize()*8 - 1;
10567 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10568 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10569 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10570 DAG.getConstant(MaxSift, dl, MVT::i8));
10571 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10572 DAG.getIntPtrConstant(0, dl));
10576 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10577 SelectionDAG &DAG) const {
10579 SDValue Vec = Op.getOperand(0);
10580 MVT VecVT = Vec.getSimpleValueType();
10581 SDValue Idx = Op.getOperand(1);
10583 if (Op.getSimpleValueType() == MVT::i1)
10584 return ExtractBitFromMaskVector(Op, DAG);
10586 if (!isa<ConstantSDNode>(Idx)) {
10587 if (VecVT.is512BitVector() ||
10588 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10589 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10592 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10593 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10594 MaskEltVT.getSizeInBits());
10596 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10597 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10598 getZeroVector(MaskVT, Subtarget, DAG, dl),
10599 Idx, DAG.getConstant(0, dl, getPointerTy()));
10600 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10601 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10602 Perm, DAG.getConstant(0, dl, getPointerTy()));
10607 // If this is a 256-bit vector result, first extract the 128-bit vector and
10608 // then extract the element from the 128-bit vector.
10609 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10611 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10612 // Get the 128-bit vector.
10613 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10614 MVT EltVT = VecVT.getVectorElementType();
10616 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10618 //if (IdxVal >= NumElems/2)
10619 // IdxVal -= NumElems/2;
10620 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10621 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10622 DAG.getConstant(IdxVal, dl, MVT::i32));
10625 assert(VecVT.is128BitVector() && "Unexpected vector length");
10627 if (Subtarget->hasSSE41()) {
10628 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10633 MVT VT = Op.getSimpleValueType();
10634 // TODO: handle v16i8.
10635 if (VT.getSizeInBits() == 16) {
10636 SDValue Vec = Op.getOperand(0);
10637 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10639 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10640 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10641 DAG.getNode(ISD::BITCAST, dl,
10643 Op.getOperand(1)));
10644 // Transform it so it match pextrw which produces a 32-bit result.
10645 MVT EltVT = MVT::i32;
10646 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10647 Op.getOperand(0), Op.getOperand(1));
10648 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10649 DAG.getValueType(VT));
10650 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10653 if (VT.getSizeInBits() == 32) {
10654 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10658 // SHUFPS the element to the lowest double word, then movss.
10659 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10660 MVT VVT = Op.getOperand(0).getSimpleValueType();
10661 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10662 DAG.getUNDEF(VVT), Mask);
10663 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10664 DAG.getIntPtrConstant(0, dl));
10667 if (VT.getSizeInBits() == 64) {
10668 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10669 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10670 // to match extract_elt for f64.
10671 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10675 // UNPCKHPD the element to the lowest double word, then movsd.
10676 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10677 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10678 int Mask[2] = { 1, -1 };
10679 MVT VVT = Op.getOperand(0).getSimpleValueType();
10680 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10681 DAG.getUNDEF(VVT), Mask);
10682 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10683 DAG.getIntPtrConstant(0, dl));
10689 /// Insert one bit to mask vector, like v16i1 or v8i1.
10690 /// AVX-512 feature.
10692 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10694 SDValue Vec = Op.getOperand(0);
10695 SDValue Elt = Op.getOperand(1);
10696 SDValue Idx = Op.getOperand(2);
10697 MVT VecVT = Vec.getSimpleValueType();
10699 if (!isa<ConstantSDNode>(Idx)) {
10700 // Non constant index. Extend source and destination,
10701 // insert element and then truncate the result.
10702 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10703 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10704 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10705 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10706 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10707 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10710 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10711 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10713 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10714 DAG.getConstant(IdxVal, dl, MVT::i8));
10715 if (Vec.getOpcode() == ISD::UNDEF)
10717 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10720 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10721 SelectionDAG &DAG) const {
10722 MVT VT = Op.getSimpleValueType();
10723 MVT EltVT = VT.getVectorElementType();
10725 if (EltVT == MVT::i1)
10726 return InsertBitToMaskVector(Op, DAG);
10729 SDValue N0 = Op.getOperand(0);
10730 SDValue N1 = Op.getOperand(1);
10731 SDValue N2 = Op.getOperand(2);
10732 if (!isa<ConstantSDNode>(N2))
10734 auto *N2C = cast<ConstantSDNode>(N2);
10735 unsigned IdxVal = N2C->getZExtValue();
10737 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10738 // into that, and then insert the subvector back into the result.
10739 if (VT.is256BitVector() || VT.is512BitVector()) {
10740 // With a 256-bit vector, we can insert into the zero element efficiently
10741 // using a blend if we have AVX or AVX2 and the right data type.
10742 if (VT.is256BitVector() && IdxVal == 0) {
10743 // TODO: It is worthwhile to cast integer to floating point and back
10744 // and incur a domain crossing penalty if that's what we'll end up
10745 // doing anyway after extracting to a 128-bit vector.
10746 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10747 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10748 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10749 N2 = DAG.getIntPtrConstant(1, dl);
10750 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10754 // Get the desired 128-bit vector chunk.
10755 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10757 // Insert the element into the desired chunk.
10758 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10759 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10761 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10762 DAG.getConstant(IdxIn128, dl, MVT::i32));
10764 // Insert the changed part back into the bigger vector
10765 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10767 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10769 if (Subtarget->hasSSE41()) {
10770 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10772 if (VT == MVT::v8i16) {
10773 Opc = X86ISD::PINSRW;
10775 assert(VT == MVT::v16i8);
10776 Opc = X86ISD::PINSRB;
10779 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10781 if (N1.getValueType() != MVT::i32)
10782 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10783 if (N2.getValueType() != MVT::i32)
10784 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10785 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10788 if (EltVT == MVT::f32) {
10789 // Bits [7:6] of the constant are the source select. This will always be
10790 // zero here. The DAG Combiner may combine an extract_elt index into
10791 // these bits. For example (insert (extract, 3), 2) could be matched by
10792 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10793 // Bits [5:4] of the constant are the destination select. This is the
10794 // value of the incoming immediate.
10795 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10796 // combine either bitwise AND or insert of float 0.0 to set these bits.
10798 const Function *F = DAG.getMachineFunction().getFunction();
10799 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10800 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10801 // If this is an insertion of 32-bits into the low 32-bits of
10802 // a vector, we prefer to generate a blend with immediate rather
10803 // than an insertps. Blends are simpler operations in hardware and so
10804 // will always have equal or better performance than insertps.
10805 // But if optimizing for size and there's a load folding opportunity,
10806 // generate insertps because blendps does not have a 32-bit memory
10808 N2 = DAG.getIntPtrConstant(1, dl);
10809 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10810 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10812 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10813 // Create this as a scalar to vector..
10814 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10815 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10818 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10819 // PINSR* works with constant index.
10824 if (EltVT == MVT::i8)
10827 if (EltVT.getSizeInBits() == 16) {
10828 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10829 // as its second argument.
10830 if (N1.getValueType() != MVT::i32)
10831 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10832 if (N2.getValueType() != MVT::i32)
10833 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10834 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10839 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10841 MVT OpVT = Op.getSimpleValueType();
10843 // If this is a 256-bit vector result, first insert into a 128-bit
10844 // vector and then insert into the 256-bit vector.
10845 if (!OpVT.is128BitVector()) {
10846 // Insert into a 128-bit vector.
10847 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10848 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10849 OpVT.getVectorNumElements() / SizeFactor);
10851 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10853 // Insert the 128-bit vector.
10854 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10857 if (OpVT == MVT::v1i64 &&
10858 Op.getOperand(0).getValueType() == MVT::i64)
10859 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10861 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10862 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10863 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10864 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10867 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10868 // a simple subregister reference or explicit instructions to grab
10869 // upper bits of a vector.
10870 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10871 SelectionDAG &DAG) {
10873 SDValue In = Op.getOperand(0);
10874 SDValue Idx = Op.getOperand(1);
10875 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10876 MVT ResVT = Op.getSimpleValueType();
10877 MVT InVT = In.getSimpleValueType();
10879 if (Subtarget->hasFp256()) {
10880 if (ResVT.is128BitVector() &&
10881 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10882 isa<ConstantSDNode>(Idx)) {
10883 return Extract128BitVector(In, IdxVal, DAG, dl);
10885 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10886 isa<ConstantSDNode>(Idx)) {
10887 return Extract256BitVector(In, IdxVal, DAG, dl);
10893 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10894 // simple superregister reference or explicit instructions to insert
10895 // the upper bits of a vector.
10896 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10897 SelectionDAG &DAG) {
10898 if (!Subtarget->hasAVX())
10902 SDValue Vec = Op.getOperand(0);
10903 SDValue SubVec = Op.getOperand(1);
10904 SDValue Idx = Op.getOperand(2);
10906 if (!isa<ConstantSDNode>(Idx))
10909 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10910 MVT OpVT = Op.getSimpleValueType();
10911 MVT SubVecVT = SubVec.getSimpleValueType();
10913 // Fold two 16-byte subvector loads into one 32-byte load:
10914 // (insert_subvector (insert_subvector undef, (load addr), 0),
10915 // (load addr + 16), Elts/2)
10917 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10918 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10919 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10920 !Subtarget->isUnalignedMem32Slow()) {
10921 SDValue SubVec2 = Vec.getOperand(1);
10922 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10923 if (Idx2->getZExtValue() == 0) {
10924 SDValue Ops[] = { SubVec2, SubVec };
10925 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10932 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10933 SubVecVT.is128BitVector())
10934 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10936 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10937 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10939 if (OpVT.getVectorElementType() == MVT::i1) {
10940 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10942 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10943 SDValue Undef = DAG.getUNDEF(OpVT);
10944 unsigned NumElems = OpVT.getVectorNumElements();
10945 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10947 if (IdxVal == OpVT.getVectorNumElements() / 2) {
10948 // Zero upper bits of the Vec
10949 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10950 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10952 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10954 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10955 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10958 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10960 // Zero upper bits of the Vec2
10961 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10962 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10963 // Zero lower bits of the Vec
10964 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10965 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10966 // Merge them together
10967 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10973 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10974 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10975 // one of the above mentioned nodes. It has to be wrapped because otherwise
10976 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10977 // be used to form addressing mode. These wrapped nodes will be selected
10980 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10981 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10983 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10984 // global base reg.
10985 unsigned char OpFlag = 0;
10986 unsigned WrapperKind = X86ISD::Wrapper;
10987 CodeModel::Model M = DAG.getTarget().getCodeModel();
10989 if (Subtarget->isPICStyleRIPRel() &&
10990 (M == CodeModel::Small || M == CodeModel::Kernel))
10991 WrapperKind = X86ISD::WrapperRIP;
10992 else if (Subtarget->isPICStyleGOT())
10993 OpFlag = X86II::MO_GOTOFF;
10994 else if (Subtarget->isPICStyleStubPIC())
10995 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10997 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10998 CP->getAlignment(),
10999 CP->getOffset(), OpFlag);
11001 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11002 // With PIC, the address is actually $g + Offset.
11004 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11005 DAG.getNode(X86ISD::GlobalBaseReg,
11006 SDLoc(), getPointerTy()),
11013 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11014 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11016 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11017 // global base reg.
11018 unsigned char OpFlag = 0;
11019 unsigned WrapperKind = X86ISD::Wrapper;
11020 CodeModel::Model M = DAG.getTarget().getCodeModel();
11022 if (Subtarget->isPICStyleRIPRel() &&
11023 (M == CodeModel::Small || M == CodeModel::Kernel))
11024 WrapperKind = X86ISD::WrapperRIP;
11025 else if (Subtarget->isPICStyleGOT())
11026 OpFlag = X86II::MO_GOTOFF;
11027 else if (Subtarget->isPICStyleStubPIC())
11028 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11030 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11033 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11035 // With PIC, the address is actually $g + Offset.
11037 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11038 DAG.getNode(X86ISD::GlobalBaseReg,
11039 SDLoc(), getPointerTy()),
11046 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11047 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11049 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11050 // global base reg.
11051 unsigned char OpFlag = 0;
11052 unsigned WrapperKind = X86ISD::Wrapper;
11053 CodeModel::Model M = DAG.getTarget().getCodeModel();
11055 if (Subtarget->isPICStyleRIPRel() &&
11056 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11057 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11058 OpFlag = X86II::MO_GOTPCREL;
11059 WrapperKind = X86ISD::WrapperRIP;
11060 } else if (Subtarget->isPICStyleGOT()) {
11061 OpFlag = X86II::MO_GOT;
11062 } else if (Subtarget->isPICStyleStubPIC()) {
11063 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11064 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11065 OpFlag = X86II::MO_DARWIN_NONLAZY;
11068 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11071 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11073 // With PIC, the address is actually $g + Offset.
11074 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11075 !Subtarget->is64Bit()) {
11076 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11077 DAG.getNode(X86ISD::GlobalBaseReg,
11078 SDLoc(), getPointerTy()),
11082 // For symbols that require a load from a stub to get the address, emit the
11084 if (isGlobalStubReference(OpFlag))
11085 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11086 MachinePointerInfo::getGOT(), false, false, false, 0);
11092 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11093 // Create the TargetBlockAddressAddress node.
11094 unsigned char OpFlags =
11095 Subtarget->ClassifyBlockAddressReference();
11096 CodeModel::Model M = DAG.getTarget().getCodeModel();
11097 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11098 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11100 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11103 if (Subtarget->isPICStyleRIPRel() &&
11104 (M == CodeModel::Small || M == CodeModel::Kernel))
11105 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11107 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11109 // With PIC, the address is actually $g + Offset.
11110 if (isGlobalRelativeToPICBase(OpFlags)) {
11111 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11112 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11120 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11121 int64_t Offset, SelectionDAG &DAG) const {
11122 // Create the TargetGlobalAddress node, folding in the constant
11123 // offset if it is legal.
11124 unsigned char OpFlags =
11125 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11126 CodeModel::Model M = DAG.getTarget().getCodeModel();
11128 if (OpFlags == X86II::MO_NO_FLAG &&
11129 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11130 // A direct static reference to a global.
11131 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11134 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11137 if (Subtarget->isPICStyleRIPRel() &&
11138 (M == CodeModel::Small || M == CodeModel::Kernel))
11139 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11141 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11143 // With PIC, the address is actually $g + Offset.
11144 if (isGlobalRelativeToPICBase(OpFlags)) {
11145 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11146 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11150 // For globals that require a load from a stub to get the address, emit the
11152 if (isGlobalStubReference(OpFlags))
11153 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11154 MachinePointerInfo::getGOT(), false, false, false, 0);
11156 // If there was a non-zero offset that we didn't fold, create an explicit
11157 // addition for it.
11159 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11160 DAG.getConstant(Offset, dl, getPointerTy()));
11166 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11167 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11168 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11169 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11173 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11174 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11175 unsigned char OperandFlags, bool LocalDynamic = false) {
11176 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11177 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11179 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11180 GA->getValueType(0),
11184 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11188 SDValue Ops[] = { Chain, TGA, *InFlag };
11189 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11191 SDValue Ops[] = { Chain, TGA };
11192 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11195 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11196 MFI->setAdjustsStack(true);
11197 MFI->setHasCalls(true);
11199 SDValue Flag = Chain.getValue(1);
11200 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11203 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11205 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11208 SDLoc dl(GA); // ? function entry point might be better
11209 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11210 DAG.getNode(X86ISD::GlobalBaseReg,
11211 SDLoc(), PtrVT), InFlag);
11212 InFlag = Chain.getValue(1);
11214 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11217 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11219 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11221 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11222 X86::RAX, X86II::MO_TLSGD);
11225 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11231 // Get the start address of the TLS block for this module.
11232 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11233 .getInfo<X86MachineFunctionInfo>();
11234 MFI->incNumLocalDynamicTLSAccesses();
11238 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11239 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11242 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11243 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11244 InFlag = Chain.getValue(1);
11245 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11246 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11249 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11253 unsigned char OperandFlags = X86II::MO_DTPOFF;
11254 unsigned WrapperKind = X86ISD::Wrapper;
11255 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11256 GA->getValueType(0),
11257 GA->getOffset(), OperandFlags);
11258 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11260 // Add x@dtpoff with the base.
11261 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11264 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11265 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11266 const EVT PtrVT, TLSModel::Model model,
11267 bool is64Bit, bool isPIC) {
11270 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11271 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11272 is64Bit ? 257 : 256));
11274 SDValue ThreadPointer =
11275 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11276 MachinePointerInfo(Ptr), false, false, false, 0);
11278 unsigned char OperandFlags = 0;
11279 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11281 unsigned WrapperKind = X86ISD::Wrapper;
11282 if (model == TLSModel::LocalExec) {
11283 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11284 } else if (model == TLSModel::InitialExec) {
11286 OperandFlags = X86II::MO_GOTTPOFF;
11287 WrapperKind = X86ISD::WrapperRIP;
11289 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11292 llvm_unreachable("Unexpected model");
11295 // emit "addl x@ntpoff,%eax" (local exec)
11296 // or "addl x@indntpoff,%eax" (initial exec)
11297 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11299 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11300 GA->getOffset(), OperandFlags);
11301 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11303 if (model == TLSModel::InitialExec) {
11304 if (isPIC && !is64Bit) {
11305 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11306 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11310 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11311 MachinePointerInfo::getGOT(), false, false, false, 0);
11314 // The address of the thread local variable is the add of the thread
11315 // pointer with the offset of the variable.
11316 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11320 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11322 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11323 const GlobalValue *GV = GA->getGlobal();
11325 if (Subtarget->isTargetELF()) {
11326 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11328 case TLSModel::GeneralDynamic:
11329 if (Subtarget->is64Bit())
11330 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11331 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11332 case TLSModel::LocalDynamic:
11333 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11334 Subtarget->is64Bit());
11335 case TLSModel::InitialExec:
11336 case TLSModel::LocalExec:
11337 return LowerToTLSExecModel(
11338 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11339 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11341 llvm_unreachable("Unknown TLS model.");
11344 if (Subtarget->isTargetDarwin()) {
11345 // Darwin only has one model of TLS. Lower to that.
11346 unsigned char OpFlag = 0;
11347 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11348 X86ISD::WrapperRIP : X86ISD::Wrapper;
11350 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11351 // global base reg.
11352 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11353 !Subtarget->is64Bit();
11355 OpFlag = X86II::MO_TLVP_PIC_BASE;
11357 OpFlag = X86II::MO_TLVP;
11359 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11360 GA->getValueType(0),
11361 GA->getOffset(), OpFlag);
11362 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11364 // With PIC32, the address is actually $g + Offset.
11366 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11367 DAG.getNode(X86ISD::GlobalBaseReg,
11368 SDLoc(), getPointerTy()),
11371 // Lowering the machine isd will make sure everything is in the right
11373 SDValue Chain = DAG.getEntryNode();
11374 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11375 SDValue Args[] = { Chain, Offset };
11376 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11378 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11379 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11380 MFI->setAdjustsStack(true);
11382 // And our return value (tls address) is in the standard call return value
11384 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11385 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11386 Chain.getValue(1));
11389 if (Subtarget->isTargetKnownWindowsMSVC() ||
11390 Subtarget->isTargetWindowsGNU()) {
11391 // Just use the implicit TLS architecture
11392 // Need to generate someting similar to:
11393 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11395 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11396 // mov rcx, qword [rdx+rcx*8]
11397 // mov eax, .tls$:tlsvar
11398 // [rax+rcx] contains the address
11399 // Windows 64bit: gs:0x58
11400 // Windows 32bit: fs:__tls_array
11403 SDValue Chain = DAG.getEntryNode();
11405 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11406 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11407 // use its literal value of 0x2C.
11408 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11409 ? Type::getInt8PtrTy(*DAG.getContext(),
11411 : Type::getInt32PtrTy(*DAG.getContext(),
11415 Subtarget->is64Bit()
11416 ? DAG.getIntPtrConstant(0x58, dl)
11417 : (Subtarget->isTargetWindowsGNU()
11418 ? DAG.getIntPtrConstant(0x2C, dl)
11419 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11421 SDValue ThreadPointer =
11422 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11423 MachinePointerInfo(Ptr), false, false, false, 0);
11426 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11427 res = ThreadPointer;
11429 // Load the _tls_index variable
11430 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11431 if (Subtarget->is64Bit())
11432 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11433 MachinePointerInfo(), MVT::i32, false, false,
11436 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11437 false, false, false, 0);
11439 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11441 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11443 res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11446 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11447 false, false, false, 0);
11449 // Get the offset of start of .tls section
11450 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11451 GA->getValueType(0),
11452 GA->getOffset(), X86II::MO_SECREL);
11453 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11455 // The address of the thread local variable is the add of the thread
11456 // pointer with the offset of the variable.
11457 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11460 llvm_unreachable("TLS not implemented for this target.");
11463 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11464 /// and take a 2 x i32 value to shift plus a shift amount.
11465 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11466 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11467 MVT VT = Op.getSimpleValueType();
11468 unsigned VTBits = VT.getSizeInBits();
11470 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11471 SDValue ShOpLo = Op.getOperand(0);
11472 SDValue ShOpHi = Op.getOperand(1);
11473 SDValue ShAmt = Op.getOperand(2);
11474 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11475 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11477 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11478 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11479 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11480 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11481 : DAG.getConstant(0, dl, VT);
11483 SDValue Tmp2, Tmp3;
11484 if (Op.getOpcode() == ISD::SHL_PARTS) {
11485 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11486 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11488 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11489 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11492 // If the shift amount is larger or equal than the width of a part we can't
11493 // rely on the results of shld/shrd. Insert a test and select the appropriate
11494 // values for large shift amounts.
11495 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11496 DAG.getConstant(VTBits, dl, MVT::i8));
11497 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11498 AndNode, DAG.getConstant(0, dl, MVT::i8));
11501 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11502 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11503 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11505 if (Op.getOpcode() == ISD::SHL_PARTS) {
11506 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11507 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11509 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11510 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11513 SDValue Ops[2] = { Lo, Hi };
11514 return DAG.getMergeValues(Ops, dl);
11517 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11518 SelectionDAG &DAG) const {
11519 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11522 if (SrcVT.isVector()) {
11523 if (SrcVT.getVectorElementType() == MVT::i1) {
11524 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11525 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11526 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11527 Op.getOperand(0)));
11532 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11533 "Unknown SINT_TO_FP to lower!");
11535 // These are really Legal; return the operand so the caller accepts it as
11537 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11539 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11540 Subtarget->is64Bit()) {
11544 unsigned Size = SrcVT.getSizeInBits()/8;
11545 MachineFunction &MF = DAG.getMachineFunction();
11546 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11547 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11548 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11550 MachinePointerInfo::getFixedStack(SSFI),
11552 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11555 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11557 SelectionDAG &DAG) const {
11561 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11563 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11565 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11567 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11569 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11570 MachineMemOperand *MMO;
11572 int SSFI = FI->getIndex();
11574 DAG.getMachineFunction()
11575 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11576 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11578 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11579 StackSlot = StackSlot.getOperand(1);
11581 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11582 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11584 Tys, Ops, SrcVT, MMO);
11587 Chain = Result.getValue(1);
11588 SDValue InFlag = Result.getValue(2);
11590 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11591 // shouldn't be necessary except that RFP cannot be live across
11592 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11593 MachineFunction &MF = DAG.getMachineFunction();
11594 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11595 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11596 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11597 Tys = DAG.getVTList(MVT::Other);
11599 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11601 MachineMemOperand *MMO =
11602 DAG.getMachineFunction()
11603 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11604 MachineMemOperand::MOStore, SSFISize, SSFISize);
11606 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11607 Ops, Op.getValueType(), MMO);
11608 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11609 MachinePointerInfo::getFixedStack(SSFI),
11610 false, false, false, 0);
11616 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11617 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11618 SelectionDAG &DAG) const {
11619 // This algorithm is not obvious. Here it is what we're trying to output:
11622 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11623 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11625 haddpd %xmm0, %xmm0
11627 pshufd $0x4e, %xmm0, %xmm1
11633 LLVMContext *Context = DAG.getContext();
11635 // Build some magic constants.
11636 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11637 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11638 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11640 SmallVector<Constant*,2> CV1;
11642 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11643 APInt(64, 0x4330000000000000ULL))));
11645 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11646 APInt(64, 0x4530000000000000ULL))));
11647 Constant *C1 = ConstantVector::get(CV1);
11648 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11650 // Load the 64-bit value into an XMM register.
11651 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11653 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11654 MachinePointerInfo::getConstantPool(),
11655 false, false, false, 16);
11656 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11657 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11660 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11661 MachinePointerInfo::getConstantPool(),
11662 false, false, false, 16);
11663 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11664 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11667 if (Subtarget->hasSSE3()) {
11668 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11669 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11671 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11672 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11674 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11675 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11679 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11680 DAG.getIntPtrConstant(0, dl));
11683 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11684 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11685 SelectionDAG &DAG) const {
11687 // FP constant to bias correct the final result.
11688 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11691 // Load the 32-bit value into an XMM register.
11692 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11695 // Zero out the upper parts of the register.
11696 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11698 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11699 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11700 DAG.getIntPtrConstant(0, dl));
11702 // Or the load with the bias.
11703 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11704 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11705 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11706 MVT::v2f64, Load)),
11707 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11708 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11709 MVT::v2f64, Bias)));
11710 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11711 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11712 DAG.getIntPtrConstant(0, dl));
11714 // Subtract the bias.
11715 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11717 // Handle final rounding.
11718 EVT DestVT = Op.getValueType();
11720 if (DestVT.bitsLT(MVT::f64))
11721 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11722 DAG.getIntPtrConstant(0, dl));
11723 if (DestVT.bitsGT(MVT::f64))
11724 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11726 // Handle final rounding.
11730 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11731 const X86Subtarget &Subtarget) {
11732 // The algorithm is the following:
11733 // #ifdef __SSE4_1__
11734 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11735 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11736 // (uint4) 0x53000000, 0xaa);
11738 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11739 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11741 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11742 // return (float4) lo + fhi;
11745 SDValue V = Op->getOperand(0);
11746 EVT VecIntVT = V.getValueType();
11747 bool Is128 = VecIntVT == MVT::v4i32;
11748 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11749 // If we convert to something else than the supported type, e.g., to v4f64,
11751 if (VecFloatVT != Op->getValueType(0))
11754 unsigned NumElts = VecIntVT.getVectorNumElements();
11755 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11756 "Unsupported custom type");
11757 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11759 // In the #idef/#else code, we have in common:
11760 // - The vector of constants:
11766 // Create the splat vector for 0x4b000000.
11767 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11768 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11769 CstLow, CstLow, CstLow, CstLow};
11770 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11771 makeArrayRef(&CstLowArray[0], NumElts));
11772 // Create the splat vector for 0x53000000.
11773 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11774 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11775 CstHigh, CstHigh, CstHigh, CstHigh};
11776 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11777 makeArrayRef(&CstHighArray[0], NumElts));
11779 // Create the right shift.
11780 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11781 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11782 CstShift, CstShift, CstShift, CstShift};
11783 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11784 makeArrayRef(&CstShiftArray[0], NumElts));
11785 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11788 if (Subtarget.hasSSE41()) {
11789 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11790 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11791 SDValue VecCstLowBitcast =
11792 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11793 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11794 // Low will be bitcasted right away, so do not bother bitcasting back to its
11796 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11797 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11798 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11799 // (uint4) 0x53000000, 0xaa);
11800 SDValue VecCstHighBitcast =
11801 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11802 SDValue VecShiftBitcast =
11803 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11804 // High will be bitcasted right away, so do not bother bitcasting back to
11805 // its original type.
11806 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11807 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11809 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11810 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11811 CstMask, CstMask, CstMask);
11812 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11813 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11814 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11816 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11817 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11820 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11821 SDValue CstFAdd = DAG.getConstantFP(
11822 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11823 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11824 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11825 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11826 makeArrayRef(&CstFAddArray[0], NumElts));
11828 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11829 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11831 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11832 // return (float4) lo + fhi;
11833 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11834 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11837 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11838 SelectionDAG &DAG) const {
11839 SDValue N0 = Op.getOperand(0);
11840 MVT SVT = N0.getSimpleValueType();
11843 switch (SVT.SimpleTy) {
11845 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11850 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11851 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11852 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11856 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11859 if (Subtarget->hasAVX512())
11860 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11861 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11863 llvm_unreachable(nullptr);
11866 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11867 SelectionDAG &DAG) const {
11868 SDValue N0 = Op.getOperand(0);
11871 if (Op.getValueType().isVector())
11872 return lowerUINT_TO_FP_vec(Op, DAG);
11874 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11875 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11876 // the optimization here.
11877 if (DAG.SignBitIsZero(N0))
11878 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11880 MVT SrcVT = N0.getSimpleValueType();
11881 MVT DstVT = Op.getSimpleValueType();
11882 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11883 return LowerUINT_TO_FP_i64(Op, DAG);
11884 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11885 return LowerUINT_TO_FP_i32(Op, DAG);
11886 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11889 // Make a 64-bit buffer, and use it to build an FILD.
11890 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11891 if (SrcVT == MVT::i32) {
11892 SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11893 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11894 getPointerTy(), StackSlot, WordOff);
11895 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11896 StackSlot, MachinePointerInfo(),
11898 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11899 OffsetSlot, MachinePointerInfo(),
11901 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11905 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11906 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11907 StackSlot, MachinePointerInfo(),
11909 // For i64 source, we need to add the appropriate power of 2 if the input
11910 // was negative. This is the same as the optimization in
11911 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11912 // we must be careful to do the computation in x87 extended precision, not
11913 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11914 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11915 MachineMemOperand *MMO =
11916 DAG.getMachineFunction()
11917 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11918 MachineMemOperand::MOLoad, 8, 8);
11920 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11921 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11922 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11925 APInt FF(32, 0x5F800000ULL);
11927 // Check whether the sign bit is set.
11928 SDValue SignSet = DAG.getSetCC(dl,
11929 getSetCCResultType(*DAG.getContext(), MVT::i64),
11931 DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11933 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11934 SDValue FudgePtr = DAG.getConstantPool(
11935 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11938 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11939 SDValue Zero = DAG.getIntPtrConstant(0, dl);
11940 SDValue Four = DAG.getIntPtrConstant(4, dl);
11941 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11943 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11945 // Load the value out, extending it from f32 to f80.
11946 // FIXME: Avoid the extend by constructing the right constant pool?
11947 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11948 FudgePtr, MachinePointerInfo::getConstantPool(),
11949 MVT::f32, false, false, false, 4);
11950 // Extend everything to 80 bits to force it to be done on x87.
11951 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11952 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11953 DAG.getIntPtrConstant(0, dl));
11956 std::pair<SDValue,SDValue>
11957 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11958 bool IsSigned, bool IsReplace) const {
11961 EVT DstTy = Op.getValueType();
11963 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11964 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11968 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11969 DstTy.getSimpleVT() >= MVT::i16 &&
11970 "Unknown FP_TO_INT to lower!");
11972 // These are really Legal.
11973 if (DstTy == MVT::i32 &&
11974 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11975 return std::make_pair(SDValue(), SDValue());
11976 if (Subtarget->is64Bit() &&
11977 DstTy == MVT::i64 &&
11978 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11979 return std::make_pair(SDValue(), SDValue());
11981 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11982 // stack slot, or into the FTOL runtime function.
11983 MachineFunction &MF = DAG.getMachineFunction();
11984 unsigned MemSize = DstTy.getSizeInBits()/8;
11985 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11986 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11989 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11990 Opc = X86ISD::WIN_FTOL;
11992 switch (DstTy.getSimpleVT().SimpleTy) {
11993 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11994 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11995 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11996 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11999 SDValue Chain = DAG.getEntryNode();
12000 SDValue Value = Op.getOperand(0);
12001 EVT TheVT = Op.getOperand(0).getValueType();
12002 // FIXME This causes a redundant load/store if the SSE-class value is already
12003 // in memory, such as if it is on the callstack.
12004 if (isScalarFPTypeInSSEReg(TheVT)) {
12005 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12006 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12007 MachinePointerInfo::getFixedStack(SSFI),
12009 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12011 Chain, StackSlot, DAG.getValueType(TheVT)
12014 MachineMemOperand *MMO =
12015 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12016 MachineMemOperand::MOLoad, MemSize, MemSize);
12017 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12018 Chain = Value.getValue(1);
12019 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12020 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12023 MachineMemOperand *MMO =
12024 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12025 MachineMemOperand::MOStore, MemSize, MemSize);
12027 if (Opc != X86ISD::WIN_FTOL) {
12028 // Build the FP_TO_INT*_IN_MEM
12029 SDValue Ops[] = { Chain, Value, StackSlot };
12030 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12032 return std::make_pair(FIST, StackSlot);
12034 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12035 DAG.getVTList(MVT::Other, MVT::Glue),
12037 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12038 MVT::i32, ftol.getValue(1));
12039 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12040 MVT::i32, eax.getValue(2));
12041 SDValue Ops[] = { eax, edx };
12042 SDValue pair = IsReplace
12043 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12044 : DAG.getMergeValues(Ops, DL);
12045 return std::make_pair(pair, SDValue());
12049 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12050 const X86Subtarget *Subtarget) {
12051 MVT VT = Op->getSimpleValueType(0);
12052 SDValue In = Op->getOperand(0);
12053 MVT InVT = In.getSimpleValueType();
12056 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12057 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12059 // Optimize vectors in AVX mode:
12062 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12063 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12064 // Concat upper and lower parts.
12067 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12068 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12069 // Concat upper and lower parts.
12072 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12073 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12074 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12077 if (Subtarget->hasInt256())
12078 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12080 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12081 SDValue Undef = DAG.getUNDEF(InVT);
12082 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12083 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12084 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12086 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12087 VT.getVectorNumElements()/2);
12089 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12090 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12092 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12095 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12096 SelectionDAG &DAG) {
12097 MVT VT = Op->getSimpleValueType(0);
12098 SDValue In = Op->getOperand(0);
12099 MVT InVT = In.getSimpleValueType();
12101 unsigned int NumElts = VT.getVectorNumElements();
12102 if (NumElts != 8 && NumElts != 16)
12105 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12106 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12108 assert(InVT.getVectorElementType() == MVT::i1);
12109 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12111 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12113 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12115 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12116 if (VT.is512BitVector())
12118 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12121 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12122 SelectionDAG &DAG) {
12123 if (Subtarget->hasFp256()) {
12124 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12132 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12133 SelectionDAG &DAG) {
12135 MVT VT = Op.getSimpleValueType();
12136 SDValue In = Op.getOperand(0);
12137 MVT SVT = In.getSimpleValueType();
12139 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12140 return LowerZERO_EXTEND_AVX512(Op, DAG);
12142 if (Subtarget->hasFp256()) {
12143 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12148 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12149 VT.getVectorNumElements() != SVT.getVectorNumElements());
12153 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12155 MVT VT = Op.getSimpleValueType();
12156 SDValue In = Op.getOperand(0);
12157 MVT InVT = In.getSimpleValueType();
12159 if (VT == MVT::i1) {
12160 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12161 "Invalid scalar TRUNCATE operation");
12162 if (InVT.getSizeInBits() >= 32)
12164 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12165 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12167 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12168 "Invalid TRUNCATE operation");
12170 // move vector to mask - truncate solution for SKX
12171 if (VT.getVectorElementType() == MVT::i1) {
12172 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12173 Subtarget->hasBWI())
12174 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12175 if ((InVT.is256BitVector() || InVT.is128BitVector())
12176 && InVT.getScalarSizeInBits() <= 16 &&
12177 Subtarget->hasBWI() && Subtarget->hasVLX())
12178 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12179 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12180 Subtarget->hasDQI())
12181 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12182 if ((InVT.is256BitVector() || InVT.is128BitVector())
12183 && InVT.getScalarSizeInBits() >= 32 &&
12184 Subtarget->hasDQI() && Subtarget->hasVLX())
12185 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12187 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12188 if (VT.getVectorElementType().getSizeInBits() >=8)
12189 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12191 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12192 unsigned NumElts = InVT.getVectorNumElements();
12193 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12194 if (InVT.getSizeInBits() < 512) {
12195 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12196 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12201 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12202 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12203 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12206 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12207 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12208 if (Subtarget->hasInt256()) {
12209 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12210 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12211 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12213 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12214 DAG.getIntPtrConstant(0, DL));
12217 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12218 DAG.getIntPtrConstant(0, DL));
12219 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12220 DAG.getIntPtrConstant(2, DL));
12221 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12222 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12223 static const int ShufMask[] = {0, 2, 4, 6};
12224 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12227 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12228 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12229 if (Subtarget->hasInt256()) {
12230 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12232 SmallVector<SDValue,32> pshufbMask;
12233 for (unsigned i = 0; i < 2; ++i) {
12234 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12235 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12236 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12237 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12238 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12239 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12240 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12241 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12242 for (unsigned j = 0; j < 8; ++j)
12243 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12245 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12246 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12247 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12249 static const int ShufMask[] = {0, 2, -1, -1};
12250 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12252 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12253 DAG.getIntPtrConstant(0, DL));
12254 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12257 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12258 DAG.getIntPtrConstant(0, DL));
12260 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12261 DAG.getIntPtrConstant(4, DL));
12263 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12264 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12266 // The PSHUFB mask:
12267 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12268 -1, -1, -1, -1, -1, -1, -1, -1};
12270 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12271 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12272 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12274 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12275 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12277 // The MOVLHPS Mask:
12278 static const int ShufMask2[] = {0, 1, 4, 5};
12279 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12280 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12283 // Handle truncation of V256 to V128 using shuffles.
12284 if (!VT.is128BitVector() || !InVT.is256BitVector())
12287 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12289 unsigned NumElems = VT.getVectorNumElements();
12290 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12292 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12293 // Prepare truncation shuffle mask
12294 for (unsigned i = 0; i != NumElems; ++i)
12295 MaskVec[i] = i * 2;
12296 SDValue V = DAG.getVectorShuffle(NVT, DL,
12297 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12298 DAG.getUNDEF(NVT), &MaskVec[0]);
12299 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12300 DAG.getIntPtrConstant(0, DL));
12303 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12304 SelectionDAG &DAG) const {
12305 assert(!Op.getSimpleValueType().isVector());
12307 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12308 /*IsSigned=*/ true, /*IsReplace=*/ false);
12309 SDValue FIST = Vals.first, StackSlot = Vals.second;
12310 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12311 if (!FIST.getNode()) return Op;
12313 if (StackSlot.getNode())
12314 // Load the result.
12315 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12316 FIST, StackSlot, MachinePointerInfo(),
12317 false, false, false, 0);
12319 // The node is the result.
12323 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12324 SelectionDAG &DAG) const {
12325 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12326 /*IsSigned=*/ false, /*IsReplace=*/ false);
12327 SDValue FIST = Vals.first, StackSlot = Vals.second;
12328 assert(FIST.getNode() && "Unexpected failure");
12330 if (StackSlot.getNode())
12331 // Load the result.
12332 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12333 FIST, StackSlot, MachinePointerInfo(),
12334 false, false, false, 0);
12336 // The node is the result.
12340 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12342 MVT VT = Op.getSimpleValueType();
12343 SDValue In = Op.getOperand(0);
12344 MVT SVT = In.getSimpleValueType();
12346 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12348 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12349 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12350 In, DAG.getUNDEF(SVT)));
12353 /// The only differences between FABS and FNEG are the mask and the logic op.
12354 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12355 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12356 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12357 "Wrong opcode for lowering FABS or FNEG.");
12359 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12361 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12362 // into an FNABS. We'll lower the FABS after that if it is still in use.
12364 for (SDNode *User : Op->uses())
12365 if (User->getOpcode() == ISD::FNEG)
12368 SDValue Op0 = Op.getOperand(0);
12369 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12372 MVT VT = Op.getSimpleValueType();
12373 // Assume scalar op for initialization; update for vector if needed.
12374 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12375 // generate a 16-byte vector constant and logic op even for the scalar case.
12376 // Using a 16-byte mask allows folding the load of the mask with
12377 // the logic op, so it can save (~4 bytes) on code size.
12379 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12380 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12381 // decide if we should generate a 16-byte constant mask when we only need 4 or
12382 // 8 bytes for the scalar case.
12383 if (VT.isVector()) {
12384 EltVT = VT.getVectorElementType();
12385 NumElts = VT.getVectorNumElements();
12388 unsigned EltBits = EltVT.getSizeInBits();
12389 LLVMContext *Context = DAG.getContext();
12390 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12392 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12393 Constant *C = ConstantInt::get(*Context, MaskElt);
12394 C = ConstantVector::getSplat(NumElts, C);
12395 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12396 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12397 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12398 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12399 MachinePointerInfo::getConstantPool(),
12400 false, false, false, Alignment);
12402 if (VT.isVector()) {
12403 // For a vector, cast operands to a vector type, perform the logic op,
12404 // and cast the result back to the original value type.
12405 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12406 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12407 SDValue Operand = IsFNABS ?
12408 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12409 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12410 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12411 return DAG.getNode(ISD::BITCAST, dl, VT,
12412 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12415 // If not vector, then scalar.
12416 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12417 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12418 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12421 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12422 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12423 LLVMContext *Context = DAG.getContext();
12424 SDValue Op0 = Op.getOperand(0);
12425 SDValue Op1 = Op.getOperand(1);
12427 MVT VT = Op.getSimpleValueType();
12428 MVT SrcVT = Op1.getSimpleValueType();
12430 // If second operand is smaller, extend it first.
12431 if (SrcVT.bitsLT(VT)) {
12432 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12435 // And if it is bigger, shrink it first.
12436 if (SrcVT.bitsGT(VT)) {
12437 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12441 // At this point the operands and the result should have the same
12442 // type, and that won't be f80 since that is not custom lowered.
12444 const fltSemantics &Sem =
12445 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12446 const unsigned SizeInBits = VT.getSizeInBits();
12448 SmallVector<Constant *, 4> CV(
12449 VT == MVT::f64 ? 2 : 4,
12450 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12452 // First, clear all bits but the sign bit from the second operand (sign).
12453 CV[0] = ConstantFP::get(*Context,
12454 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12455 Constant *C = ConstantVector::get(CV);
12456 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12457 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12458 MachinePointerInfo::getConstantPool(),
12459 false, false, false, 16);
12460 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12462 // Next, clear the sign bit from the first operand (magnitude).
12463 // If it's a constant, we can clear it here.
12464 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12465 APFloat APF = Op0CN->getValueAPF();
12466 // If the magnitude is a positive zero, the sign bit alone is enough.
12467 if (APF.isPosZero())
12470 CV[0] = ConstantFP::get(*Context, APF);
12472 CV[0] = ConstantFP::get(
12474 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12476 C = ConstantVector::get(CV);
12477 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12478 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12479 MachinePointerInfo::getConstantPool(),
12480 false, false, false, 16);
12481 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12482 if (!isa<ConstantFPSDNode>(Op0))
12483 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12485 // OR the magnitude value with the sign bit.
12486 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12489 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12490 SDValue N0 = Op.getOperand(0);
12492 MVT VT = Op.getSimpleValueType();
12494 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12495 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12496 DAG.getConstant(1, dl, VT));
12497 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12500 // Check whether an OR'd tree is PTEST-able.
12501 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12502 SelectionDAG &DAG) {
12503 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12505 if (!Subtarget->hasSSE41())
12508 if (!Op->hasOneUse())
12511 SDNode *N = Op.getNode();
12514 SmallVector<SDValue, 8> Opnds;
12515 DenseMap<SDValue, unsigned> VecInMap;
12516 SmallVector<SDValue, 8> VecIns;
12517 EVT VT = MVT::Other;
12519 // Recognize a special case where a vector is casted into wide integer to
12521 Opnds.push_back(N->getOperand(0));
12522 Opnds.push_back(N->getOperand(1));
12524 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12525 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12526 // BFS traverse all OR'd operands.
12527 if (I->getOpcode() == ISD::OR) {
12528 Opnds.push_back(I->getOperand(0));
12529 Opnds.push_back(I->getOperand(1));
12530 // Re-evaluate the number of nodes to be traversed.
12531 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12535 // Quit if a non-EXTRACT_VECTOR_ELT
12536 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12539 // Quit if without a constant index.
12540 SDValue Idx = I->getOperand(1);
12541 if (!isa<ConstantSDNode>(Idx))
12544 SDValue ExtractedFromVec = I->getOperand(0);
12545 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12546 if (M == VecInMap.end()) {
12547 VT = ExtractedFromVec.getValueType();
12548 // Quit if not 128/256-bit vector.
12549 if (!VT.is128BitVector() && !VT.is256BitVector())
12551 // Quit if not the same type.
12552 if (VecInMap.begin() != VecInMap.end() &&
12553 VT != VecInMap.begin()->first.getValueType())
12555 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12556 VecIns.push_back(ExtractedFromVec);
12558 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12561 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12562 "Not extracted from 128-/256-bit vector.");
12564 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12566 for (DenseMap<SDValue, unsigned>::const_iterator
12567 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12568 // Quit if not all elements are used.
12569 if (I->second != FullMask)
12573 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12575 // Cast all vectors into TestVT for PTEST.
12576 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12577 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12579 // If more than one full vectors are evaluated, OR them first before PTEST.
12580 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12581 // Each iteration will OR 2 nodes and append the result until there is only
12582 // 1 node left, i.e. the final OR'd value of all vectors.
12583 SDValue LHS = VecIns[Slot];
12584 SDValue RHS = VecIns[Slot + 1];
12585 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12588 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12589 VecIns.back(), VecIns.back());
12592 /// \brief return true if \c Op has a use that doesn't just read flags.
12593 static bool hasNonFlagsUse(SDValue Op) {
12594 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12596 SDNode *User = *UI;
12597 unsigned UOpNo = UI.getOperandNo();
12598 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12599 // Look pass truncate.
12600 UOpNo = User->use_begin().getOperandNo();
12601 User = *User->use_begin();
12604 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12605 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12611 /// Emit nodes that will be selected as "test Op0,Op0", or something
12613 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12614 SelectionDAG &DAG) const {
12615 if (Op.getValueType() == MVT::i1) {
12616 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12617 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12618 DAG.getConstant(0, dl, MVT::i8));
12620 // CF and OF aren't always set the way we want. Determine which
12621 // of these we need.
12622 bool NeedCF = false;
12623 bool NeedOF = false;
12626 case X86::COND_A: case X86::COND_AE:
12627 case X86::COND_B: case X86::COND_BE:
12630 case X86::COND_G: case X86::COND_GE:
12631 case X86::COND_L: case X86::COND_LE:
12632 case X86::COND_O: case X86::COND_NO: {
12633 // Check if we really need to set the
12634 // Overflow flag. If NoSignedWrap is present
12635 // that is not actually needed.
12636 switch (Op->getOpcode()) {
12641 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12642 if (BinNode->Flags.hasNoSignedWrap())
12652 // See if we can use the EFLAGS value from the operand instead of
12653 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12654 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12655 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12656 // Emit a CMP with 0, which is the TEST pattern.
12657 //if (Op.getValueType() == MVT::i1)
12658 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12659 // DAG.getConstant(0, MVT::i1));
12660 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12661 DAG.getConstant(0, dl, Op.getValueType()));
12663 unsigned Opcode = 0;
12664 unsigned NumOperands = 0;
12666 // Truncate operations may prevent the merge of the SETCC instruction
12667 // and the arithmetic instruction before it. Attempt to truncate the operands
12668 // of the arithmetic instruction and use a reduced bit-width instruction.
12669 bool NeedTruncation = false;
12670 SDValue ArithOp = Op;
12671 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12672 SDValue Arith = Op->getOperand(0);
12673 // Both the trunc and the arithmetic op need to have one user each.
12674 if (Arith->hasOneUse())
12675 switch (Arith.getOpcode()) {
12682 NeedTruncation = true;
12688 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12689 // which may be the result of a CAST. We use the variable 'Op', which is the
12690 // non-casted variable when we check for possible users.
12691 switch (ArithOp.getOpcode()) {
12693 // Due to an isel shortcoming, be conservative if this add is likely to be
12694 // selected as part of a load-modify-store instruction. When the root node
12695 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12696 // uses of other nodes in the match, such as the ADD in this case. This
12697 // leads to the ADD being left around and reselected, with the result being
12698 // two adds in the output. Alas, even if none our users are stores, that
12699 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12700 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12701 // climbing the DAG back to the root, and it doesn't seem to be worth the
12703 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12704 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12705 if (UI->getOpcode() != ISD::CopyToReg &&
12706 UI->getOpcode() != ISD::SETCC &&
12707 UI->getOpcode() != ISD::STORE)
12710 if (ConstantSDNode *C =
12711 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12712 // An add of one will be selected as an INC.
12713 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12714 Opcode = X86ISD::INC;
12719 // An add of negative one (subtract of one) will be selected as a DEC.
12720 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12721 Opcode = X86ISD::DEC;
12727 // Otherwise use a regular EFLAGS-setting add.
12728 Opcode = X86ISD::ADD;
12733 // If we have a constant logical shift that's only used in a comparison
12734 // against zero turn it into an equivalent AND. This allows turning it into
12735 // a TEST instruction later.
12736 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12737 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12738 EVT VT = Op.getValueType();
12739 unsigned BitWidth = VT.getSizeInBits();
12740 unsigned ShAmt = Op->getConstantOperandVal(1);
12741 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12743 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12744 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12745 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12746 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12748 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12749 DAG.getConstant(Mask, dl, VT));
12750 DAG.ReplaceAllUsesWith(Op, New);
12756 // If the primary and result isn't used, don't bother using X86ISD::AND,
12757 // because a TEST instruction will be better.
12758 if (!hasNonFlagsUse(Op))
12764 // Due to the ISEL shortcoming noted above, be conservative if this op is
12765 // likely to be selected as part of a load-modify-store instruction.
12766 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12767 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12768 if (UI->getOpcode() == ISD::STORE)
12771 // Otherwise use a regular EFLAGS-setting instruction.
12772 switch (ArithOp.getOpcode()) {
12773 default: llvm_unreachable("unexpected operator!");
12774 case ISD::SUB: Opcode = X86ISD::SUB; break;
12775 case ISD::XOR: Opcode = X86ISD::XOR; break;
12776 case ISD::AND: Opcode = X86ISD::AND; break;
12778 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12779 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12780 if (EFLAGS.getNode())
12783 Opcode = X86ISD::OR;
12797 return SDValue(Op.getNode(), 1);
12803 // If we found that truncation is beneficial, perform the truncation and
12805 if (NeedTruncation) {
12806 EVT VT = Op.getValueType();
12807 SDValue WideVal = Op->getOperand(0);
12808 EVT WideVT = WideVal.getValueType();
12809 unsigned ConvertedOp = 0;
12810 // Use a target machine opcode to prevent further DAGCombine
12811 // optimizations that may separate the arithmetic operations
12812 // from the setcc node.
12813 switch (WideVal.getOpcode()) {
12815 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12816 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12817 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12818 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12819 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12823 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12824 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12825 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12826 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12827 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12833 // Emit a CMP with 0, which is the TEST pattern.
12834 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12835 DAG.getConstant(0, dl, Op.getValueType()));
12837 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12838 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12840 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12841 DAG.ReplaceAllUsesWith(Op, New);
12842 return SDValue(New.getNode(), 1);
12845 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12847 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12848 SDLoc dl, SelectionDAG &DAG) const {
12849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12850 if (C->getAPIntValue() == 0)
12851 return EmitTest(Op0, X86CC, dl, DAG);
12853 if (Op0.getValueType() == MVT::i1)
12854 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12857 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12858 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12859 // Do the comparison at i32 if it's smaller, besides the Atom case.
12860 // This avoids subregister aliasing issues. Keep the smaller reference
12861 // if we're optimizing for size, however, as that'll allow better folding
12862 // of memory operations.
12863 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12864 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12865 Attribute::MinSize) &&
12866 !Subtarget->isAtom()) {
12867 unsigned ExtendOp =
12868 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12869 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12870 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12872 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12873 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12874 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12876 return SDValue(Sub.getNode(), 1);
12878 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12881 /// Convert a comparison if required by the subtarget.
12882 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12883 SelectionDAG &DAG) const {
12884 // If the subtarget does not support the FUCOMI instruction, floating-point
12885 // comparisons have to be converted.
12886 if (Subtarget->hasCMov() ||
12887 Cmp.getOpcode() != X86ISD::CMP ||
12888 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12889 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12892 // The instruction selector will select an FUCOM instruction instead of
12893 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12894 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12895 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12897 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12898 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12899 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12900 DAG.getConstant(8, dl, MVT::i8));
12901 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12902 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12905 /// The minimum architected relative accuracy is 2^-12. We need one
12906 /// Newton-Raphson step to have a good float result (24 bits of precision).
12907 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12908 DAGCombinerInfo &DCI,
12909 unsigned &RefinementSteps,
12910 bool &UseOneConstNR) const {
12911 // FIXME: We should use instruction latency models to calculate the cost of
12912 // each potential sequence, but this is very hard to do reliably because
12913 // at least Intel's Core* chips have variable timing based on the number of
12914 // significant digits in the divisor and/or sqrt operand.
12915 if (!Subtarget->useSqrtEst())
12918 EVT VT = Op.getValueType();
12920 // SSE1 has rsqrtss and rsqrtps.
12921 // TODO: Add support for AVX512 (v16f32).
12922 // It is likely not profitable to do this for f64 because a double-precision
12923 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12924 // instructions: convert to single, rsqrtss, convert back to double, refine
12925 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12926 // along with FMA, this could be a throughput win.
12927 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12928 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12929 RefinementSteps = 1;
12930 UseOneConstNR = false;
12931 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12936 /// The minimum architected relative accuracy is 2^-12. We need one
12937 /// Newton-Raphson step to have a good float result (24 bits of precision).
12938 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12939 DAGCombinerInfo &DCI,
12940 unsigned &RefinementSteps) const {
12941 // FIXME: We should use instruction latency models to calculate the cost of
12942 // each potential sequence, but this is very hard to do reliably because
12943 // at least Intel's Core* chips have variable timing based on the number of
12944 // significant digits in the divisor.
12945 if (!Subtarget->useReciprocalEst())
12948 EVT VT = Op.getValueType();
12950 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12951 // TODO: Add support for AVX512 (v16f32).
12952 // It is likely not profitable to do this for f64 because a double-precision
12953 // reciprocal estimate with refinement on x86 prior to FMA requires
12954 // 15 instructions: convert to single, rcpss, convert back to double, refine
12955 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12956 // along with FMA, this could be a throughput win.
12957 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12958 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12959 RefinementSteps = ReciprocalEstimateRefinementSteps;
12960 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12965 /// If we have at least two divisions that use the same divisor, convert to
12966 /// multplication by a reciprocal. This may need to be adjusted for a given
12967 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12968 /// This is because we still need one division to calculate the reciprocal and
12969 /// then we need two multiplies by that reciprocal as replacements for the
12970 /// original divisions.
12971 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12972 return NumUsers > 1;
12975 static bool isAllOnes(SDValue V) {
12976 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12977 return C && C->isAllOnesValue();
12980 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12981 /// if it's possible.
12982 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12983 SDLoc dl, SelectionDAG &DAG) const {
12984 SDValue Op0 = And.getOperand(0);
12985 SDValue Op1 = And.getOperand(1);
12986 if (Op0.getOpcode() == ISD::TRUNCATE)
12987 Op0 = Op0.getOperand(0);
12988 if (Op1.getOpcode() == ISD::TRUNCATE)
12989 Op1 = Op1.getOperand(0);
12992 if (Op1.getOpcode() == ISD::SHL)
12993 std::swap(Op0, Op1);
12994 if (Op0.getOpcode() == ISD::SHL) {
12995 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12996 if (And00C->getZExtValue() == 1) {
12997 // If we looked past a truncate, check that it's only truncating away
12999 unsigned BitWidth = Op0.getValueSizeInBits();
13000 unsigned AndBitWidth = And.getValueSizeInBits();
13001 if (BitWidth > AndBitWidth) {
13003 DAG.computeKnownBits(Op0, Zeros, Ones);
13004 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13008 RHS = Op0.getOperand(1);
13010 } else if (Op1.getOpcode() == ISD::Constant) {
13011 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13012 uint64_t AndRHSVal = AndRHS->getZExtValue();
13013 SDValue AndLHS = Op0;
13015 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13016 LHS = AndLHS.getOperand(0);
13017 RHS = AndLHS.getOperand(1);
13020 // Use BT if the immediate can't be encoded in a TEST instruction.
13021 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13023 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13027 if (LHS.getNode()) {
13028 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13029 // instruction. Since the shift amount is in-range-or-undefined, we know
13030 // that doing a bittest on the i32 value is ok. We extend to i32 because
13031 // the encoding for the i16 version is larger than the i32 version.
13032 // Also promote i16 to i32 for performance / code size reason.
13033 if (LHS.getValueType() == MVT::i8 ||
13034 LHS.getValueType() == MVT::i16)
13035 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13037 // If the operand types disagree, extend the shift amount to match. Since
13038 // BT ignores high bits (like shifts) we can use anyextend.
13039 if (LHS.getValueType() != RHS.getValueType())
13040 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13042 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13043 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13044 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13045 DAG.getConstant(Cond, dl, MVT::i8), BT);
13051 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13053 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13058 // SSE Condition code mapping:
13067 switch (SetCCOpcode) {
13068 default: llvm_unreachable("Unexpected SETCC condition");
13070 case ISD::SETEQ: SSECC = 0; break;
13072 case ISD::SETGT: Swap = true; // Fallthrough
13074 case ISD::SETOLT: SSECC = 1; break;
13076 case ISD::SETGE: Swap = true; // Fallthrough
13078 case ISD::SETOLE: SSECC = 2; break;
13079 case ISD::SETUO: SSECC = 3; break;
13081 case ISD::SETNE: SSECC = 4; break;
13082 case ISD::SETULE: Swap = true; // Fallthrough
13083 case ISD::SETUGE: SSECC = 5; break;
13084 case ISD::SETULT: Swap = true; // Fallthrough
13085 case ISD::SETUGT: SSECC = 6; break;
13086 case ISD::SETO: SSECC = 7; break;
13088 case ISD::SETONE: SSECC = 8; break;
13091 std::swap(Op0, Op1);
13096 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13097 // ones, and then concatenate the result back.
13098 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13099 MVT VT = Op.getSimpleValueType();
13101 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13102 "Unsupported value type for operation");
13104 unsigned NumElems = VT.getVectorNumElements();
13106 SDValue CC = Op.getOperand(2);
13108 // Extract the LHS vectors
13109 SDValue LHS = Op.getOperand(0);
13110 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13111 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13113 // Extract the RHS vectors
13114 SDValue RHS = Op.getOperand(1);
13115 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13116 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13118 // Issue the operation on the smaller types and concatenate the result back
13119 MVT EltVT = VT.getVectorElementType();
13120 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13121 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13122 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13123 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13126 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13127 SDValue Op0 = Op.getOperand(0);
13128 SDValue Op1 = Op.getOperand(1);
13129 SDValue CC = Op.getOperand(2);
13130 MVT VT = Op.getSimpleValueType();
13133 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13134 "Unexpected type for boolean compare operation");
13135 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13136 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13137 DAG.getConstant(-1, dl, VT));
13138 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13139 DAG.getConstant(-1, dl, VT));
13140 switch (SetCCOpcode) {
13141 default: llvm_unreachable("Unexpected SETCC condition");
13143 // (x != y) -> ~(x ^ y)
13144 return DAG.getNode(ISD::XOR, dl, VT,
13145 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13146 DAG.getConstant(-1, dl, VT));
13148 // (x == y) -> (x ^ y)
13149 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13152 // (x > y) -> (x & ~y)
13153 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13156 // (x < y) -> (~x & y)
13157 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13160 // (x <= y) -> (~x | y)
13161 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13164 // (x >=y) -> (x | ~y)
13165 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13169 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13170 const X86Subtarget *Subtarget) {
13171 SDValue Op0 = Op.getOperand(0);
13172 SDValue Op1 = Op.getOperand(1);
13173 SDValue CC = Op.getOperand(2);
13174 MVT VT = Op.getSimpleValueType();
13177 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13178 Op.getValueType().getScalarType() == MVT::i1 &&
13179 "Cannot set masked compare for this operation");
13181 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13183 bool Unsigned = false;
13186 switch (SetCCOpcode) {
13187 default: llvm_unreachable("Unexpected SETCC condition");
13188 case ISD::SETNE: SSECC = 4; break;
13189 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13190 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13191 case ISD::SETLT: Swap = true; //fall-through
13192 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13193 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13194 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13195 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13196 case ISD::SETULE: Unsigned = true; //fall-through
13197 case ISD::SETLE: SSECC = 2; break;
13201 std::swap(Op0, Op1);
13203 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13204 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13205 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13206 DAG.getConstant(SSECC, dl, MVT::i8));
13209 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13210 /// operand \p Op1. If non-trivial (for example because it's not constant)
13211 /// return an empty value.
13212 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13214 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13218 MVT VT = Op1.getSimpleValueType();
13219 MVT EVT = VT.getVectorElementType();
13220 unsigned n = VT.getVectorNumElements();
13221 SmallVector<SDValue, 8> ULTOp1;
13223 for (unsigned i = 0; i < n; ++i) {
13224 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13225 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13228 // Avoid underflow.
13229 APInt Val = Elt->getAPIntValue();
13233 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13236 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13239 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13240 SelectionDAG &DAG) {
13241 SDValue Op0 = Op.getOperand(0);
13242 SDValue Op1 = Op.getOperand(1);
13243 SDValue CC = Op.getOperand(2);
13244 MVT VT = Op.getSimpleValueType();
13245 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13246 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13251 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13252 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13255 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13256 unsigned Opc = X86ISD::CMPP;
13257 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13258 assert(VT.getVectorNumElements() <= 16);
13259 Opc = X86ISD::CMPM;
13261 // In the two special cases we can't handle, emit two comparisons.
13264 unsigned CombineOpc;
13265 if (SetCCOpcode == ISD::SETUEQ) {
13266 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13268 assert(SetCCOpcode == ISD::SETONE);
13269 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13272 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13273 DAG.getConstant(CC0, dl, MVT::i8));
13274 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13275 DAG.getConstant(CC1, dl, MVT::i8));
13276 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13278 // Handle all other FP comparisons here.
13279 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13280 DAG.getConstant(SSECC, dl, MVT::i8));
13283 // Break 256-bit integer vector compare into smaller ones.
13284 if (VT.is256BitVector() && !Subtarget->hasInt256())
13285 return Lower256IntVSETCC(Op, DAG);
13287 EVT OpVT = Op1.getValueType();
13288 if (OpVT.getVectorElementType() == MVT::i1)
13289 return LowerBoolVSETCC_AVX512(Op, DAG);
13291 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13292 if (Subtarget->hasAVX512()) {
13293 if (Op1.getValueType().is512BitVector() ||
13294 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13295 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13296 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13298 // In AVX-512 architecture setcc returns mask with i1 elements,
13299 // But there is no compare instruction for i8 and i16 elements in KNL.
13300 // We are not talking about 512-bit operands in this case, these
13301 // types are illegal.
13303 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13304 OpVT.getVectorElementType().getSizeInBits() >= 8))
13305 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13306 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13309 // We are handling one of the integer comparisons here. Since SSE only has
13310 // GT and EQ comparisons for integer, swapping operands and multiple
13311 // operations may be required for some comparisons.
13313 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13314 bool Subus = false;
13316 switch (SetCCOpcode) {
13317 default: llvm_unreachable("Unexpected SETCC condition");
13318 case ISD::SETNE: Invert = true;
13319 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13320 case ISD::SETLT: Swap = true;
13321 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13322 case ISD::SETGE: Swap = true;
13323 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13324 Invert = true; break;
13325 case ISD::SETULT: Swap = true;
13326 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13327 FlipSigns = true; break;
13328 case ISD::SETUGE: Swap = true;
13329 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13330 FlipSigns = true; Invert = true; break;
13333 // Special case: Use min/max operations for SETULE/SETUGE
13334 MVT VET = VT.getVectorElementType();
13336 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13337 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13340 switch (SetCCOpcode) {
13342 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13343 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13346 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13349 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13350 if (!MinMax && hasSubus) {
13351 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13353 // t = psubus Op0, Op1
13354 // pcmpeq t, <0..0>
13355 switch (SetCCOpcode) {
13357 case ISD::SETULT: {
13358 // If the comparison is against a constant we can turn this into a
13359 // setule. With psubus, setule does not require a swap. This is
13360 // beneficial because the constant in the register is no longer
13361 // destructed as the destination so it can be hoisted out of a loop.
13362 // Only do this pre-AVX since vpcmp* is no longer destructive.
13363 if (Subtarget->hasAVX())
13365 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13366 if (ULEOp1.getNode()) {
13368 Subus = true; Invert = false; Swap = false;
13372 // Psubus is better than flip-sign because it requires no inversion.
13373 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13374 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13378 Opc = X86ISD::SUBUS;
13384 std::swap(Op0, Op1);
13386 // Check that the operation in question is available (most are plain SSE2,
13387 // but PCMPGTQ and PCMPEQQ have different requirements).
13388 if (VT == MVT::v2i64) {
13389 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13390 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13392 // First cast everything to the right type.
13393 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13394 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13396 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13397 // bits of the inputs before performing those operations. The lower
13398 // compare is always unsigned.
13401 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13403 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13404 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13405 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13406 Sign, Zero, Sign, Zero);
13408 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13409 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13411 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13412 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13413 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13415 // Create masks for only the low parts/high parts of the 64 bit integers.
13416 static const int MaskHi[] = { 1, 1, 3, 3 };
13417 static const int MaskLo[] = { 0, 0, 2, 2 };
13418 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13419 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13420 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13422 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13423 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13426 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13428 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13431 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13432 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13433 // pcmpeqd + pshufd + pand.
13434 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13436 // First cast everything to the right type.
13437 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13438 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13441 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13443 // Make sure the lower and upper halves are both all-ones.
13444 static const int Mask[] = { 1, 0, 3, 2 };
13445 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13446 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13449 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13451 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13455 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13456 // bits of the inputs before performing those operations.
13458 EVT EltVT = VT.getVectorElementType();
13459 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13461 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13462 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13465 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13467 // If the logical-not of the result is required, perform that now.
13469 Result = DAG.getNOT(dl, Result, VT);
13472 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13475 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13476 getZeroVector(VT, Subtarget, DAG, dl));
13481 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13483 MVT VT = Op.getSimpleValueType();
13485 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13487 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13488 && "SetCC type must be 8-bit or 1-bit integer");
13489 SDValue Op0 = Op.getOperand(0);
13490 SDValue Op1 = Op.getOperand(1);
13492 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13494 // Optimize to BT if possible.
13495 // Lower (X & (1 << N)) == 0 to BT(X, N).
13496 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13497 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13498 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13499 Op1.getOpcode() == ISD::Constant &&
13500 cast<ConstantSDNode>(Op1)->isNullValue() &&
13501 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13502 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13503 if (NewSetCC.getNode()) {
13505 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13510 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13512 if (Op1.getOpcode() == ISD::Constant &&
13513 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13514 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13515 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13517 // If the input is a setcc, then reuse the input setcc or use a new one with
13518 // the inverted condition.
13519 if (Op0.getOpcode() == X86ISD::SETCC) {
13520 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13521 bool Invert = (CC == ISD::SETNE) ^
13522 cast<ConstantSDNode>(Op1)->isNullValue();
13526 CCode = X86::GetOppositeBranchCondition(CCode);
13527 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13528 DAG.getConstant(CCode, dl, MVT::i8),
13529 Op0.getOperand(1));
13531 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13535 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13536 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13537 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13539 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13540 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13543 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13544 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13545 if (X86CC == X86::COND_INVALID)
13548 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13549 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13550 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13551 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13553 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13557 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13558 static bool isX86LogicalCmp(SDValue Op) {
13559 unsigned Opc = Op.getNode()->getOpcode();
13560 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13561 Opc == X86ISD::SAHF)
13563 if (Op.getResNo() == 1 &&
13564 (Opc == X86ISD::ADD ||
13565 Opc == X86ISD::SUB ||
13566 Opc == X86ISD::ADC ||
13567 Opc == X86ISD::SBB ||
13568 Opc == X86ISD::SMUL ||
13569 Opc == X86ISD::UMUL ||
13570 Opc == X86ISD::INC ||
13571 Opc == X86ISD::DEC ||
13572 Opc == X86ISD::OR ||
13573 Opc == X86ISD::XOR ||
13574 Opc == X86ISD::AND))
13577 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13583 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13584 if (V.getOpcode() != ISD::TRUNCATE)
13587 SDValue VOp0 = V.getOperand(0);
13588 unsigned InBits = VOp0.getValueSizeInBits();
13589 unsigned Bits = V.getValueSizeInBits();
13590 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13593 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13594 bool addTest = true;
13595 SDValue Cond = Op.getOperand(0);
13596 SDValue Op1 = Op.getOperand(1);
13597 SDValue Op2 = Op.getOperand(2);
13599 EVT VT = Op1.getValueType();
13602 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13603 // are available or VBLENDV if AVX is available.
13604 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13605 if (Cond.getOpcode() == ISD::SETCC &&
13606 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13607 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13608 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13609 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13610 int SSECC = translateX86FSETCC(
13611 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13614 if (Subtarget->hasAVX512()) {
13615 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13616 DAG.getConstant(SSECC, DL, MVT::i8));
13617 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13620 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13621 DAG.getConstant(SSECC, DL, MVT::i8));
13623 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13624 // of 3 logic instructions for size savings and potentially speed.
13625 // Unfortunately, there is no scalar form of VBLENDV.
13627 // If either operand is a constant, don't try this. We can expect to
13628 // optimize away at least one of the logic instructions later in that
13629 // case, so that sequence would be faster than a variable blend.
13631 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13632 // uses XMM0 as the selection register. That may need just as many
13633 // instructions as the AND/ANDN/OR sequence due to register moves, so
13636 if (Subtarget->hasAVX() &&
13637 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13639 // Convert to vectors, do a VSELECT, and convert back to scalar.
13640 // All of the conversions should be optimized away.
13642 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13643 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13644 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13645 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13647 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13648 VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13650 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13652 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13653 VSel, DAG.getIntPtrConstant(0, DL));
13655 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13656 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13657 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13661 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13663 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13664 Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13665 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13666 Op1Scalar = Op1.getOperand(0);
13668 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13669 Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13670 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13671 Op2Scalar = Op2.getOperand(0);
13672 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13673 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13674 Op1Scalar.getValueType(),
13675 Cond, Op1Scalar, Op2Scalar);
13676 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13677 return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13678 SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13679 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13680 DAG.getIntPtrConstant(0, DL));
13684 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13685 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13686 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13687 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13688 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13689 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13690 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13692 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13695 if (Cond.getOpcode() == ISD::SETCC) {
13696 SDValue NewCond = LowerSETCC(Cond, DAG);
13697 if (NewCond.getNode())
13701 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13702 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13703 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13704 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13705 if (Cond.getOpcode() == X86ISD::SETCC &&
13706 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13707 isZero(Cond.getOperand(1).getOperand(1))) {
13708 SDValue Cmp = Cond.getOperand(1);
13710 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13712 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13713 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13714 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13716 SDValue CmpOp0 = Cmp.getOperand(0);
13717 // Apply further optimizations for special cases
13718 // (select (x != 0), -1, 0) -> neg & sbb
13719 // (select (x == 0), 0, -1) -> neg & sbb
13720 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13721 if (YC->isNullValue() &&
13722 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13723 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13724 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13725 DAG.getConstant(0, DL,
13726 CmpOp0.getValueType()),
13728 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13729 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13730 SDValue(Neg.getNode(), 1));
13734 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13735 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13736 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13738 SDValue Res = // Res = 0 or -1.
13739 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13740 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13742 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13743 Res = DAG.getNOT(DL, Res, Res.getValueType());
13745 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13746 if (!N2C || !N2C->isNullValue())
13747 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13752 // Look past (and (setcc_carry (cmp ...)), 1).
13753 if (Cond.getOpcode() == ISD::AND &&
13754 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13755 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13756 if (C && C->getAPIntValue() == 1)
13757 Cond = Cond.getOperand(0);
13760 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13761 // setting operand in place of the X86ISD::SETCC.
13762 unsigned CondOpcode = Cond.getOpcode();
13763 if (CondOpcode == X86ISD::SETCC ||
13764 CondOpcode == X86ISD::SETCC_CARRY) {
13765 CC = Cond.getOperand(0);
13767 SDValue Cmp = Cond.getOperand(1);
13768 unsigned Opc = Cmp.getOpcode();
13769 MVT VT = Op.getSimpleValueType();
13771 bool IllegalFPCMov = false;
13772 if (VT.isFloatingPoint() && !VT.isVector() &&
13773 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13774 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13776 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13777 Opc == X86ISD::BT) { // FIXME
13781 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13782 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13783 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13784 Cond.getOperand(0).getValueType() != MVT::i8)) {
13785 SDValue LHS = Cond.getOperand(0);
13786 SDValue RHS = Cond.getOperand(1);
13787 unsigned X86Opcode;
13790 switch (CondOpcode) {
13791 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13792 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13793 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13794 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13795 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13796 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13797 default: llvm_unreachable("unexpected overflowing operator");
13799 if (CondOpcode == ISD::UMULO)
13800 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13803 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13805 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13807 if (CondOpcode == ISD::UMULO)
13808 Cond = X86Op.getValue(2);
13810 Cond = X86Op.getValue(1);
13812 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13817 // Look pass the truncate if the high bits are known zero.
13818 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13819 Cond = Cond.getOperand(0);
13821 // We know the result of AND is compared against zero. Try to match
13823 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13824 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13825 if (NewSetCC.getNode()) {
13826 CC = NewSetCC.getOperand(0);
13827 Cond = NewSetCC.getOperand(1);
13834 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13835 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13838 // a < b ? -1 : 0 -> RES = ~setcc_carry
13839 // a < b ? 0 : -1 -> RES = setcc_carry
13840 // a >= b ? -1 : 0 -> RES = setcc_carry
13841 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13842 if (Cond.getOpcode() == X86ISD::SUB) {
13843 Cond = ConvertCmpIfNecessary(Cond, DAG);
13844 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13846 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13847 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13848 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13849 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13851 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13852 return DAG.getNOT(DL, Res, Res.getValueType());
13857 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13858 // widen the cmov and push the truncate through. This avoids introducing a new
13859 // branch during isel and doesn't add any extensions.
13860 if (Op.getValueType() == MVT::i8 &&
13861 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13862 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13863 if (T1.getValueType() == T2.getValueType() &&
13864 // Blacklist CopyFromReg to avoid partial register stalls.
13865 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13866 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13867 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13868 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13872 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13873 // condition is true.
13874 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13875 SDValue Ops[] = { Op2, Op1, CC, Cond };
13876 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13879 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13880 SelectionDAG &DAG) {
13881 MVT VT = Op->getSimpleValueType(0);
13882 SDValue In = Op->getOperand(0);
13883 MVT InVT = In.getSimpleValueType();
13884 MVT VTElt = VT.getVectorElementType();
13885 MVT InVTElt = InVT.getVectorElementType();
13889 if ((InVTElt == MVT::i1) &&
13890 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13891 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13893 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13894 VTElt.getSizeInBits() <= 16)) ||
13896 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13897 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13899 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13900 VTElt.getSizeInBits() >= 32))))
13901 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13903 unsigned int NumElts = VT.getVectorNumElements();
13905 if (NumElts != 8 && NumElts != 16)
13908 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13909 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13910 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13911 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13914 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13915 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13917 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13920 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13922 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13923 if (VT.is512BitVector())
13925 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13928 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
13929 const X86Subtarget *Subtarget,
13930 SelectionDAG &DAG) {
13931 SDValue In = Op->getOperand(0);
13932 MVT VT = Op->getSimpleValueType(0);
13933 MVT InVT = In.getSimpleValueType();
13934 assert(VT.getSizeInBits() == InVT.getSizeInBits());
13936 MVT InSVT = InVT.getScalarType();
13937 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
13939 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13941 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
13946 // SSE41 targets can use the pmovsx* instructions directly.
13947 if (Subtarget->hasSSE41())
13948 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13950 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
13954 // As SRAI is only available on i16/i32 types, we expand only up to i32
13955 // and handle i64 separately.
13956 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
13957 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
13958 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
13959 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
13960 Curr = DAG.getNode(ISD::BITCAST, dl, CurrVT, Curr);
13963 SDValue SignExt = Curr;
13964 if (CurrVT != InVT) {
13965 unsigned SignExtShift =
13966 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
13967 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13968 DAG.getConstant(SignExtShift, dl, MVT::i8));
13974 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
13975 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13976 DAG.getConstant(31, dl, MVT::i8));
13977 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
13978 return DAG.getNode(ISD::BITCAST, dl, VT, Ext);
13984 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13985 SelectionDAG &DAG) {
13986 MVT VT = Op->getSimpleValueType(0);
13987 SDValue In = Op->getOperand(0);
13988 MVT InVT = In.getSimpleValueType();
13991 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13992 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13994 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13995 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13996 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13999 if (Subtarget->hasInt256())
14000 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14002 // Optimize vectors in AVX mode
14003 // Sign extend v8i16 to v8i32 and
14006 // Divide input vector into two parts
14007 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14008 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14009 // concat the vectors to original VT
14011 unsigned NumElems = InVT.getVectorNumElements();
14012 SDValue Undef = DAG.getUNDEF(InVT);
14014 SmallVector<int,8> ShufMask1(NumElems, -1);
14015 for (unsigned i = 0; i != NumElems/2; ++i)
14018 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14020 SmallVector<int,8> ShufMask2(NumElems, -1);
14021 for (unsigned i = 0; i != NumElems/2; ++i)
14022 ShufMask2[i] = i + NumElems/2;
14024 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14026 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14027 VT.getVectorNumElements()/2);
14029 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14030 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14032 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14035 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14036 // may emit an illegal shuffle but the expansion is still better than scalar
14037 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14038 // we'll emit a shuffle and a arithmetic shift.
14039 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14040 // TODO: It is possible to support ZExt by zeroing the undef values during
14041 // the shuffle phase or after the shuffle.
14042 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14043 SelectionDAG &DAG) {
14044 MVT RegVT = Op.getSimpleValueType();
14045 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14046 assert(RegVT.isInteger() &&
14047 "We only custom lower integer vector sext loads.");
14049 // Nothing useful we can do without SSE2 shuffles.
14050 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14052 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14054 EVT MemVT = Ld->getMemoryVT();
14055 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14056 unsigned RegSz = RegVT.getSizeInBits();
14058 ISD::LoadExtType Ext = Ld->getExtensionType();
14060 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14061 && "Only anyext and sext are currently implemented.");
14062 assert(MemVT != RegVT && "Cannot extend to the same type");
14063 assert(MemVT.isVector() && "Must load a vector from memory");
14065 unsigned NumElems = RegVT.getVectorNumElements();
14066 unsigned MemSz = MemVT.getSizeInBits();
14067 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14069 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14070 // The only way in which we have a legal 256-bit vector result but not the
14071 // integer 256-bit operations needed to directly lower a sextload is if we
14072 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14073 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14074 // correctly legalized. We do this late to allow the canonical form of
14075 // sextload to persist throughout the rest of the DAG combiner -- it wants
14076 // to fold together any extensions it can, and so will fuse a sign_extend
14077 // of an sextload into a sextload targeting a wider value.
14079 if (MemSz == 128) {
14080 // Just switch this to a normal load.
14081 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14082 "it must be a legal 128-bit vector "
14084 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14085 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14086 Ld->isInvariant(), Ld->getAlignment());
14088 assert(MemSz < 128 &&
14089 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14090 // Do an sext load to a 128-bit vector type. We want to use the same
14091 // number of elements, but elements half as wide. This will end up being
14092 // recursively lowered by this routine, but will succeed as we definitely
14093 // have all the necessary features if we're using AVX1.
14095 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14096 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14098 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14099 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14100 Ld->isNonTemporal(), Ld->isInvariant(),
14101 Ld->getAlignment());
14104 // Replace chain users with the new chain.
14105 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14106 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14108 // Finally, do a normal sign-extend to the desired register.
14109 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14112 // All sizes must be a power of two.
14113 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14114 "Non-power-of-two elements are not custom lowered!");
14116 // Attempt to load the original value using scalar loads.
14117 // Find the largest scalar type that divides the total loaded size.
14118 MVT SclrLoadTy = MVT::i8;
14119 for (MVT Tp : MVT::integer_valuetypes()) {
14120 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14125 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14126 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14128 SclrLoadTy = MVT::f64;
14130 // Calculate the number of scalar loads that we need to perform
14131 // in order to load our vector from memory.
14132 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14134 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14135 "Can only lower sext loads with a single scalar load!");
14137 unsigned loadRegZize = RegSz;
14138 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14141 // Represent our vector as a sequence of elements which are the
14142 // largest scalar that we can load.
14143 EVT LoadUnitVecVT = EVT::getVectorVT(
14144 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14146 // Represent the data using the same element type that is stored in
14147 // memory. In practice, we ''widen'' MemVT.
14149 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14150 loadRegZize / MemVT.getScalarType().getSizeInBits());
14152 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14153 "Invalid vector type");
14155 // We can't shuffle using an illegal type.
14156 assert(TLI.isTypeLegal(WideVecVT) &&
14157 "We only lower types that form legal widened vector types");
14159 SmallVector<SDValue, 8> Chains;
14160 SDValue Ptr = Ld->getBasePtr();
14161 SDValue Increment =
14162 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14163 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14165 for (unsigned i = 0; i < NumLoads; ++i) {
14166 // Perform a single load.
14167 SDValue ScalarLoad =
14168 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14169 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14170 Ld->getAlignment());
14171 Chains.push_back(ScalarLoad.getValue(1));
14172 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14173 // another round of DAGCombining.
14175 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14177 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14178 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14180 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14183 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14185 // Bitcast the loaded value to a vector of the original element type, in
14186 // the size of the target vector type.
14187 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14188 unsigned SizeRatio = RegSz / MemSz;
14190 if (Ext == ISD::SEXTLOAD) {
14191 // If we have SSE4.1, we can directly emit a VSEXT node.
14192 if (Subtarget->hasSSE41()) {
14193 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14194 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14198 // Otherwise we'll shuffle the small elements in the high bits of the
14199 // larger type and perform an arithmetic shift. If the shift is not legal
14200 // it's better to scalarize.
14201 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14202 "We can't implement a sext load without an arithmetic right shift!");
14204 // Redistribute the loaded elements into the different locations.
14205 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14206 for (unsigned i = 0; i != NumElems; ++i)
14207 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14209 SDValue Shuff = DAG.getVectorShuffle(
14210 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14212 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14214 // Build the arithmetic shift.
14215 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14216 MemVT.getVectorElementType().getSizeInBits();
14218 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14219 DAG.getConstant(Amt, dl, RegVT));
14221 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14225 // Redistribute the loaded elements into the different locations.
14226 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14227 for (unsigned i = 0; i != NumElems; ++i)
14228 ShuffleVec[i * SizeRatio] = i;
14230 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14231 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14233 // Bitcast to the requested type.
14234 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14235 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14239 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14240 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14241 // from the AND / OR.
14242 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14243 Opc = Op.getOpcode();
14244 if (Opc != ISD::OR && Opc != ISD::AND)
14246 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14247 Op.getOperand(0).hasOneUse() &&
14248 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14249 Op.getOperand(1).hasOneUse());
14252 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14253 // 1 and that the SETCC node has a single use.
14254 static bool isXor1OfSetCC(SDValue Op) {
14255 if (Op.getOpcode() != ISD::XOR)
14257 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14258 if (N1C && N1C->getAPIntValue() == 1) {
14259 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14260 Op.getOperand(0).hasOneUse();
14265 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14266 bool addTest = true;
14267 SDValue Chain = Op.getOperand(0);
14268 SDValue Cond = Op.getOperand(1);
14269 SDValue Dest = Op.getOperand(2);
14272 bool Inverted = false;
14274 if (Cond.getOpcode() == ISD::SETCC) {
14275 // Check for setcc([su]{add,sub,mul}o == 0).
14276 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14277 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14278 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14279 Cond.getOperand(0).getResNo() == 1 &&
14280 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14281 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14282 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14283 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14284 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14285 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14287 Cond = Cond.getOperand(0);
14289 SDValue NewCond = LowerSETCC(Cond, DAG);
14290 if (NewCond.getNode())
14295 // FIXME: LowerXALUO doesn't handle these!!
14296 else if (Cond.getOpcode() == X86ISD::ADD ||
14297 Cond.getOpcode() == X86ISD::SUB ||
14298 Cond.getOpcode() == X86ISD::SMUL ||
14299 Cond.getOpcode() == X86ISD::UMUL)
14300 Cond = LowerXALUO(Cond, DAG);
14303 // Look pass (and (setcc_carry (cmp ...)), 1).
14304 if (Cond.getOpcode() == ISD::AND &&
14305 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14306 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14307 if (C && C->getAPIntValue() == 1)
14308 Cond = Cond.getOperand(0);
14311 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14312 // setting operand in place of the X86ISD::SETCC.
14313 unsigned CondOpcode = Cond.getOpcode();
14314 if (CondOpcode == X86ISD::SETCC ||
14315 CondOpcode == X86ISD::SETCC_CARRY) {
14316 CC = Cond.getOperand(0);
14318 SDValue Cmp = Cond.getOperand(1);
14319 unsigned Opc = Cmp.getOpcode();
14320 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14321 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14325 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14329 // These can only come from an arithmetic instruction with overflow,
14330 // e.g. SADDO, UADDO.
14331 Cond = Cond.getNode()->getOperand(1);
14337 CondOpcode = Cond.getOpcode();
14338 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14339 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14340 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14341 Cond.getOperand(0).getValueType() != MVT::i8)) {
14342 SDValue LHS = Cond.getOperand(0);
14343 SDValue RHS = Cond.getOperand(1);
14344 unsigned X86Opcode;
14347 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14348 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14350 switch (CondOpcode) {
14351 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14353 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14355 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14358 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14359 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14363 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14366 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14367 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14368 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14369 default: llvm_unreachable("unexpected overflowing operator");
14372 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14373 if (CondOpcode == ISD::UMULO)
14374 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14377 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14379 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14381 if (CondOpcode == ISD::UMULO)
14382 Cond = X86Op.getValue(2);
14384 Cond = X86Op.getValue(1);
14386 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14390 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14391 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14392 if (CondOpc == ISD::OR) {
14393 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14394 // two branches instead of an explicit OR instruction with a
14396 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14397 isX86LogicalCmp(Cmp)) {
14398 CC = Cond.getOperand(0).getOperand(0);
14399 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14400 Chain, Dest, CC, Cmp);
14401 CC = Cond.getOperand(1).getOperand(0);
14405 } else { // ISD::AND
14406 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14407 // two branches instead of an explicit AND instruction with a
14408 // separate test. However, we only do this if this block doesn't
14409 // have a fall-through edge, because this requires an explicit
14410 // jmp when the condition is false.
14411 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14412 isX86LogicalCmp(Cmp) &&
14413 Op.getNode()->hasOneUse()) {
14414 X86::CondCode CCode =
14415 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14416 CCode = X86::GetOppositeBranchCondition(CCode);
14417 CC = DAG.getConstant(CCode, dl, MVT::i8);
14418 SDNode *User = *Op.getNode()->use_begin();
14419 // Look for an unconditional branch following this conditional branch.
14420 // We need this because we need to reverse the successors in order
14421 // to implement FCMP_OEQ.
14422 if (User->getOpcode() == ISD::BR) {
14423 SDValue FalseBB = User->getOperand(1);
14425 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14426 assert(NewBR == User);
14430 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14431 Chain, Dest, CC, Cmp);
14432 X86::CondCode CCode =
14433 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14434 CCode = X86::GetOppositeBranchCondition(CCode);
14435 CC = DAG.getConstant(CCode, dl, MVT::i8);
14441 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14442 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14443 // It should be transformed during dag combiner except when the condition
14444 // is set by a arithmetics with overflow node.
14445 X86::CondCode CCode =
14446 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14447 CCode = X86::GetOppositeBranchCondition(CCode);
14448 CC = DAG.getConstant(CCode, dl, MVT::i8);
14449 Cond = Cond.getOperand(0).getOperand(1);
14451 } else if (Cond.getOpcode() == ISD::SETCC &&
14452 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14453 // For FCMP_OEQ, we can emit
14454 // two branches instead of an explicit AND instruction with a
14455 // separate test. However, we only do this if this block doesn't
14456 // have a fall-through edge, because this requires an explicit
14457 // jmp when the condition is false.
14458 if (Op.getNode()->hasOneUse()) {
14459 SDNode *User = *Op.getNode()->use_begin();
14460 // Look for an unconditional branch following this conditional branch.
14461 // We need this because we need to reverse the successors in order
14462 // to implement FCMP_OEQ.
14463 if (User->getOpcode() == ISD::BR) {
14464 SDValue FalseBB = User->getOperand(1);
14466 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14467 assert(NewBR == User);
14471 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14472 Cond.getOperand(0), Cond.getOperand(1));
14473 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14474 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14475 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14476 Chain, Dest, CC, Cmp);
14477 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14482 } else if (Cond.getOpcode() == ISD::SETCC &&
14483 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14484 // For FCMP_UNE, we can emit
14485 // two branches instead of an explicit AND instruction with a
14486 // separate test. However, we only do this if this block doesn't
14487 // have a fall-through edge, because this requires an explicit
14488 // jmp when the condition is false.
14489 if (Op.getNode()->hasOneUse()) {
14490 SDNode *User = *Op.getNode()->use_begin();
14491 // Look for an unconditional branch following this conditional branch.
14492 // We need this because we need to reverse the successors in order
14493 // to implement FCMP_UNE.
14494 if (User->getOpcode() == ISD::BR) {
14495 SDValue FalseBB = User->getOperand(1);
14497 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14498 assert(NewBR == User);
14501 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14502 Cond.getOperand(0), Cond.getOperand(1));
14503 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14504 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14505 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14506 Chain, Dest, CC, Cmp);
14507 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14517 // Look pass the truncate if the high bits are known zero.
14518 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14519 Cond = Cond.getOperand(0);
14521 // We know the result of AND is compared against zero. Try to match
14523 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14524 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14525 if (NewSetCC.getNode()) {
14526 CC = NewSetCC.getOperand(0);
14527 Cond = NewSetCC.getOperand(1);
14534 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14535 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14536 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14538 Cond = ConvertCmpIfNecessary(Cond, DAG);
14539 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14540 Chain, Dest, CC, Cond);
14543 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14544 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14545 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14546 // that the guard pages used by the OS virtual memory manager are allocated in
14547 // correct sequence.
14549 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14550 SelectionDAG &DAG) const {
14551 MachineFunction &MF = DAG.getMachineFunction();
14552 bool SplitStack = MF.shouldSplitStack();
14553 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14558 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14559 SDNode* Node = Op.getNode();
14561 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14562 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14563 " not tell us which reg is the stack pointer!");
14564 EVT VT = Node->getValueType(0);
14565 SDValue Tmp1 = SDValue(Node, 0);
14566 SDValue Tmp2 = SDValue(Node, 1);
14567 SDValue Tmp3 = Node->getOperand(2);
14568 SDValue Chain = Tmp1.getOperand(0);
14570 // Chain the dynamic stack allocation so that it doesn't modify the stack
14571 // pointer when other instructions are using the stack.
14572 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14575 SDValue Size = Tmp2.getOperand(1);
14576 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14577 Chain = SP.getValue(1);
14578 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14579 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14580 unsigned StackAlign = TFI.getStackAlignment();
14581 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14582 if (Align > StackAlign)
14583 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14584 DAG.getConstant(-(uint64_t)Align, dl, VT));
14585 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14587 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14588 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14591 SDValue Ops[2] = { Tmp1, Tmp2 };
14592 return DAG.getMergeValues(Ops, dl);
14596 SDValue Chain = Op.getOperand(0);
14597 SDValue Size = Op.getOperand(1);
14598 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14599 EVT VT = Op.getNode()->getValueType(0);
14601 bool Is64Bit = Subtarget->is64Bit();
14602 EVT SPTy = getPointerTy();
14605 MachineRegisterInfo &MRI = MF.getRegInfo();
14608 // The 64 bit implementation of segmented stacks needs to clobber both r10
14609 // r11. This makes it impossible to use it along with nested parameters.
14610 const Function *F = MF.getFunction();
14612 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14614 if (I->hasNestAttr())
14615 report_fatal_error("Cannot use segmented stacks with functions that "
14616 "have nested arguments.");
14619 const TargetRegisterClass *AddrRegClass =
14620 getRegClassFor(getPointerTy());
14621 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14622 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14623 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14624 DAG.getRegister(Vreg, SPTy));
14625 SDValue Ops1[2] = { Value, Chain };
14626 return DAG.getMergeValues(Ops1, dl);
14629 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14631 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14632 Flag = Chain.getValue(1);
14633 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14635 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14637 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14638 unsigned SPReg = RegInfo->getStackRegister();
14639 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14640 Chain = SP.getValue(1);
14643 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14644 DAG.getConstant(-(uint64_t)Align, dl, VT));
14645 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14648 SDValue Ops1[2] = { SP, Chain };
14649 return DAG.getMergeValues(Ops1, dl);
14653 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14654 MachineFunction &MF = DAG.getMachineFunction();
14655 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14657 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14660 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14661 // vastart just stores the address of the VarArgsFrameIndex slot into the
14662 // memory location argument.
14663 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14665 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14666 MachinePointerInfo(SV), false, false, 0);
14670 // gp_offset (0 - 6 * 8)
14671 // fp_offset (48 - 48 + 8 * 16)
14672 // overflow_arg_area (point to parameters coming in memory).
14674 SmallVector<SDValue, 8> MemOps;
14675 SDValue FIN = Op.getOperand(1);
14677 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14678 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14680 FIN, MachinePointerInfo(SV), false, false, 0);
14681 MemOps.push_back(Store);
14684 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14685 FIN, DAG.getIntPtrConstant(4, DL));
14686 Store = DAG.getStore(Op.getOperand(0), DL,
14687 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14689 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14690 MemOps.push_back(Store);
14692 // Store ptr to overflow_arg_area
14693 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14694 FIN, DAG.getIntPtrConstant(4, DL));
14695 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14697 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14698 MachinePointerInfo(SV, 8),
14700 MemOps.push_back(Store);
14702 // Store ptr to reg_save_area.
14703 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14704 FIN, DAG.getIntPtrConstant(8, DL));
14705 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14707 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14708 MachinePointerInfo(SV, 16), false, false, 0);
14709 MemOps.push_back(Store);
14710 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14713 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14714 assert(Subtarget->is64Bit() &&
14715 "LowerVAARG only handles 64-bit va_arg!");
14716 assert((Subtarget->isTargetLinux() ||
14717 Subtarget->isTargetDarwin()) &&
14718 "Unhandled target in LowerVAARG");
14719 assert(Op.getNode()->getNumOperands() == 4);
14720 SDValue Chain = Op.getOperand(0);
14721 SDValue SrcPtr = Op.getOperand(1);
14722 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14723 unsigned Align = Op.getConstantOperandVal(3);
14726 EVT ArgVT = Op.getNode()->getValueType(0);
14727 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14728 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14731 // Decide which area this value should be read from.
14732 // TODO: Implement the AMD64 ABI in its entirety. This simple
14733 // selection mechanism works only for the basic types.
14734 if (ArgVT == MVT::f80) {
14735 llvm_unreachable("va_arg for f80 not yet implemented");
14736 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14737 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14738 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14739 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14741 llvm_unreachable("Unhandled argument type in LowerVAARG");
14744 if (ArgMode == 2) {
14745 // Sanity Check: Make sure using fp_offset makes sense.
14746 assert(!Subtarget->useSoftFloat() &&
14747 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14748 Attribute::NoImplicitFloat)) &&
14749 Subtarget->hasSSE1());
14752 // Insert VAARG_64 node into the DAG
14753 // VAARG_64 returns two values: Variable Argument Address, Chain
14754 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14755 DAG.getConstant(ArgMode, dl, MVT::i8),
14756 DAG.getConstant(Align, dl, MVT::i32)};
14757 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14758 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14759 VTs, InstOps, MVT::i64,
14760 MachinePointerInfo(SV),
14762 /*Volatile=*/false,
14764 /*WriteMem=*/true);
14765 Chain = VAARG.getValue(1);
14767 // Load the next argument and return it
14768 return DAG.getLoad(ArgVT, dl,
14771 MachinePointerInfo(),
14772 false, false, false, 0);
14775 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14776 SelectionDAG &DAG) {
14777 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14778 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14779 SDValue Chain = Op.getOperand(0);
14780 SDValue DstPtr = Op.getOperand(1);
14781 SDValue SrcPtr = Op.getOperand(2);
14782 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14783 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14786 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14787 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14789 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14792 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14793 // amount is a constant. Takes immediate version of shift as input.
14794 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14795 SDValue SrcOp, uint64_t ShiftAmt,
14796 SelectionDAG &DAG) {
14797 MVT ElementType = VT.getVectorElementType();
14799 // Fold this packed shift into its first operand if ShiftAmt is 0.
14803 // Check for ShiftAmt >= element width
14804 if (ShiftAmt >= ElementType.getSizeInBits()) {
14805 if (Opc == X86ISD::VSRAI)
14806 ShiftAmt = ElementType.getSizeInBits() - 1;
14808 return DAG.getConstant(0, dl, VT);
14811 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14812 && "Unknown target vector shift-by-constant node");
14814 // Fold this packed vector shift into a build vector if SrcOp is a
14815 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14816 if (VT == SrcOp.getSimpleValueType() &&
14817 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14818 SmallVector<SDValue, 8> Elts;
14819 unsigned NumElts = SrcOp->getNumOperands();
14820 ConstantSDNode *ND;
14823 default: llvm_unreachable(nullptr);
14824 case X86ISD::VSHLI:
14825 for (unsigned i=0; i!=NumElts; ++i) {
14826 SDValue CurrentOp = SrcOp->getOperand(i);
14827 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14828 Elts.push_back(CurrentOp);
14831 ND = cast<ConstantSDNode>(CurrentOp);
14832 const APInt &C = ND->getAPIntValue();
14833 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14836 case X86ISD::VSRLI:
14837 for (unsigned i=0; i!=NumElts; ++i) {
14838 SDValue CurrentOp = SrcOp->getOperand(i);
14839 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14840 Elts.push_back(CurrentOp);
14843 ND = cast<ConstantSDNode>(CurrentOp);
14844 const APInt &C = ND->getAPIntValue();
14845 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14848 case X86ISD::VSRAI:
14849 for (unsigned i=0; i!=NumElts; ++i) {
14850 SDValue CurrentOp = SrcOp->getOperand(i);
14851 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14852 Elts.push_back(CurrentOp);
14855 ND = cast<ConstantSDNode>(CurrentOp);
14856 const APInt &C = ND->getAPIntValue();
14857 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14862 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14865 return DAG.getNode(Opc, dl, VT, SrcOp,
14866 DAG.getConstant(ShiftAmt, dl, MVT::i8));
14869 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14870 // may or may not be a constant. Takes immediate version of shift as input.
14871 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14872 SDValue SrcOp, SDValue ShAmt,
14873 SelectionDAG &DAG) {
14874 MVT SVT = ShAmt.getSimpleValueType();
14875 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14877 // Catch shift-by-constant.
14878 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14879 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14880 CShAmt->getZExtValue(), DAG);
14882 // Change opcode to non-immediate version
14884 default: llvm_unreachable("Unknown target vector shift node");
14885 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14886 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14887 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14890 const X86Subtarget &Subtarget =
14891 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14892 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14893 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14894 // Let the shuffle legalizer expand this shift amount node.
14895 SDValue Op0 = ShAmt.getOperand(0);
14896 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14897 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14899 // Need to build a vector containing shift amount.
14900 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14901 SmallVector<SDValue, 4> ShOps;
14902 ShOps.push_back(ShAmt);
14903 if (SVT == MVT::i32) {
14904 ShOps.push_back(DAG.getConstant(0, dl, SVT));
14905 ShOps.push_back(DAG.getUNDEF(SVT));
14907 ShOps.push_back(DAG.getUNDEF(SVT));
14909 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14910 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14913 // The return type has to be a 128-bit type with the same element
14914 // type as the input type.
14915 MVT EltVT = VT.getVectorElementType();
14916 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14918 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14919 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14922 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14923 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14924 /// necessary casting for \p Mask when lowering masking intrinsics.
14925 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14926 SDValue PreservedSrc,
14927 const X86Subtarget *Subtarget,
14928 SelectionDAG &DAG) {
14929 EVT VT = Op.getValueType();
14930 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14931 MVT::i1, VT.getVectorNumElements());
14932 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14933 Mask.getValueType().getSizeInBits());
14936 assert(MaskVT.isSimple() && "invalid mask type");
14938 if (isAllOnes(Mask))
14941 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14942 // are extracted by EXTRACT_SUBVECTOR.
14943 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14944 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14945 DAG.getIntPtrConstant(0, dl));
14947 switch (Op.getOpcode()) {
14949 case X86ISD::PCMPEQM:
14950 case X86ISD::PCMPGTM:
14952 case X86ISD::CMPMU:
14953 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14955 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14956 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14957 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14960 /// \brief Creates an SDNode for a predicated scalar operation.
14961 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14962 /// The mask is comming as MVT::i8 and it should be truncated
14963 /// to MVT::i1 while lowering masking intrinsics.
14964 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14965 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14966 /// a scalar instruction.
14967 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14968 SDValue PreservedSrc,
14969 const X86Subtarget *Subtarget,
14970 SelectionDAG &DAG) {
14971 if (isAllOnes(Mask))
14974 EVT VT = Op.getValueType();
14976 // The mask should be of type MVT::i1
14977 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14979 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14980 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14981 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14984 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14985 SelectionDAG &DAG) {
14987 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14988 EVT VT = Op.getValueType();
14989 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14991 switch(IntrData->Type) {
14992 case INTR_TYPE_1OP:
14993 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14994 case INTR_TYPE_2OP:
14995 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14997 case INTR_TYPE_3OP:
14998 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14999 Op.getOperand(2), Op.getOperand(3));
15000 case INTR_TYPE_1OP_MASK_RM: {
15001 SDValue Src = Op.getOperand(1);
15002 SDValue Src0 = Op.getOperand(2);
15003 SDValue Mask = Op.getOperand(3);
15004 SDValue RoundingMode = Op.getOperand(4);
15005 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15007 Mask, Src0, Subtarget, DAG);
15009 case INTR_TYPE_SCALAR_MASK_RM: {
15010 SDValue Src1 = Op.getOperand(1);
15011 SDValue Src2 = Op.getOperand(2);
15012 SDValue Src0 = Op.getOperand(3);
15013 SDValue Mask = Op.getOperand(4);
15014 // There are 2 kinds of intrinsics in this group:
15015 // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15016 // (2) With rounding mode and sae - 7 operands.
15017 if (Op.getNumOperands() == 6) {
15018 SDValue Sae = Op.getOperand(5);
15019 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15020 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15022 Mask, Src0, Subtarget, DAG);
15024 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15025 SDValue RoundingMode = Op.getOperand(5);
15026 SDValue Sae = Op.getOperand(6);
15027 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15028 RoundingMode, Sae),
15029 Mask, Src0, Subtarget, DAG);
15031 case INTR_TYPE_2OP_MASK: {
15032 SDValue Src1 = Op.getOperand(1);
15033 SDValue Src2 = Op.getOperand(2);
15034 SDValue PassThru = Op.getOperand(3);
15035 SDValue Mask = Op.getOperand(4);
15036 // We specify 2 possible opcodes for intrinsics with rounding modes.
15037 // First, we check if the intrinsic may have non-default rounding mode,
15038 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15039 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15040 if (IntrWithRoundingModeOpcode != 0) {
15041 SDValue Rnd = Op.getOperand(5);
15042 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15043 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15044 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15045 dl, Op.getValueType(),
15047 Mask, PassThru, Subtarget, DAG);
15050 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15052 Mask, PassThru, Subtarget, DAG);
15054 case FMA_OP_MASK: {
15055 SDValue Src1 = Op.getOperand(1);
15056 SDValue Src2 = Op.getOperand(2);
15057 SDValue Src3 = Op.getOperand(3);
15058 SDValue Mask = Op.getOperand(4);
15059 // We specify 2 possible opcodes for intrinsics with rounding modes.
15060 // First, we check if the intrinsic may have non-default rounding mode,
15061 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15062 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15063 if (IntrWithRoundingModeOpcode != 0) {
15064 SDValue Rnd = Op.getOperand(5);
15065 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15066 X86::STATIC_ROUNDING::CUR_DIRECTION)
15067 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15068 dl, Op.getValueType(),
15069 Src1, Src2, Src3, Rnd),
15070 Mask, Src1, Subtarget, DAG);
15072 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15073 dl, Op.getValueType(),
15075 Mask, Src1, Subtarget, DAG);
15078 case CMP_MASK_CC: {
15079 // Comparison intrinsics with masks.
15080 // Example of transformation:
15081 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15082 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15084 // (v8i1 (insert_subvector undef,
15085 // (v2i1 (and (PCMPEQM %a, %b),
15086 // (extract_subvector
15087 // (v8i1 (bitcast %mask)), 0))), 0))))
15088 EVT VT = Op.getOperand(1).getValueType();
15089 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15090 VT.getVectorNumElements());
15091 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15092 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15093 Mask.getValueType().getSizeInBits());
15095 if (IntrData->Type == CMP_MASK_CC) {
15096 SDValue CC = Op.getOperand(3);
15097 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15098 // We specify 2 possible opcodes for intrinsics with rounding modes.
15099 // First, we check if the intrinsic may have non-default rounding mode,
15100 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15101 if (IntrData->Opc1 != 0) {
15102 SDValue Rnd = Op.getOperand(5);
15103 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15104 X86::STATIC_ROUNDING::CUR_DIRECTION)
15105 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15106 Op.getOperand(2), CC, Rnd);
15108 //default rounding mode
15110 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15111 Op.getOperand(2), CC);
15114 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15115 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15118 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15119 DAG.getTargetConstant(0, dl,
15122 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15123 DAG.getUNDEF(BitcastVT), CmpMask,
15124 DAG.getIntPtrConstant(0, dl));
15125 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15127 case COMI: { // Comparison intrinsics
15128 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15129 SDValue LHS = Op.getOperand(1);
15130 SDValue RHS = Op.getOperand(2);
15131 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15132 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15133 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15134 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15135 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15136 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15139 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15140 Op.getOperand(1), Op.getOperand(2), DAG);
15142 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15143 Op.getSimpleValueType(),
15145 Op.getOperand(2), DAG),
15146 Op.getOperand(4), Op.getOperand(3), Subtarget,
15148 case COMPRESS_EXPAND_IN_REG: {
15149 SDValue Mask = Op.getOperand(3);
15150 SDValue DataToCompress = Op.getOperand(1);
15151 SDValue PassThru = Op.getOperand(2);
15152 if (isAllOnes(Mask)) // return data as is
15153 return Op.getOperand(1);
15154 EVT VT = Op.getValueType();
15155 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15156 VT.getVectorNumElements());
15157 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15158 Mask.getValueType().getSizeInBits());
15160 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15161 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15162 DAG.getIntPtrConstant(0, dl));
15164 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15168 SDValue Mask = Op.getOperand(3);
15169 EVT VT = Op.getValueType();
15170 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15171 VT.getVectorNumElements());
15172 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15173 Mask.getValueType().getSizeInBits());
15175 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15176 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15177 DAG.getIntPtrConstant(0, dl));
15178 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15187 default: return SDValue(); // Don't custom lower most intrinsics.
15189 case Intrinsic::x86_avx2_permd:
15190 case Intrinsic::x86_avx2_permps:
15191 // Operands intentionally swapped. Mask is last operand to intrinsic,
15192 // but second operand for node/instruction.
15193 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15194 Op.getOperand(2), Op.getOperand(1));
15196 case Intrinsic::x86_avx512_mask_valign_q_512:
15197 case Intrinsic::x86_avx512_mask_valign_d_512:
15198 // Vector source operands are swapped.
15199 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15200 Op.getValueType(), Op.getOperand(2),
15203 Op.getOperand(5), Op.getOperand(4),
15206 // ptest and testp intrinsics. The intrinsic these come from are designed to
15207 // return an integer value, not just an instruction so lower it to the ptest
15208 // or testp pattern and a setcc for the result.
15209 case Intrinsic::x86_sse41_ptestz:
15210 case Intrinsic::x86_sse41_ptestc:
15211 case Intrinsic::x86_sse41_ptestnzc:
15212 case Intrinsic::x86_avx_ptestz_256:
15213 case Intrinsic::x86_avx_ptestc_256:
15214 case Intrinsic::x86_avx_ptestnzc_256:
15215 case Intrinsic::x86_avx_vtestz_ps:
15216 case Intrinsic::x86_avx_vtestc_ps:
15217 case Intrinsic::x86_avx_vtestnzc_ps:
15218 case Intrinsic::x86_avx_vtestz_pd:
15219 case Intrinsic::x86_avx_vtestc_pd:
15220 case Intrinsic::x86_avx_vtestnzc_pd:
15221 case Intrinsic::x86_avx_vtestz_ps_256:
15222 case Intrinsic::x86_avx_vtestc_ps_256:
15223 case Intrinsic::x86_avx_vtestnzc_ps_256:
15224 case Intrinsic::x86_avx_vtestz_pd_256:
15225 case Intrinsic::x86_avx_vtestc_pd_256:
15226 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15227 bool IsTestPacked = false;
15230 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15231 case Intrinsic::x86_avx_vtestz_ps:
15232 case Intrinsic::x86_avx_vtestz_pd:
15233 case Intrinsic::x86_avx_vtestz_ps_256:
15234 case Intrinsic::x86_avx_vtestz_pd_256:
15235 IsTestPacked = true; // Fallthrough
15236 case Intrinsic::x86_sse41_ptestz:
15237 case Intrinsic::x86_avx_ptestz_256:
15239 X86CC = X86::COND_E;
15241 case Intrinsic::x86_avx_vtestc_ps:
15242 case Intrinsic::x86_avx_vtestc_pd:
15243 case Intrinsic::x86_avx_vtestc_ps_256:
15244 case Intrinsic::x86_avx_vtestc_pd_256:
15245 IsTestPacked = true; // Fallthrough
15246 case Intrinsic::x86_sse41_ptestc:
15247 case Intrinsic::x86_avx_ptestc_256:
15249 X86CC = X86::COND_B;
15251 case Intrinsic::x86_avx_vtestnzc_ps:
15252 case Intrinsic::x86_avx_vtestnzc_pd:
15253 case Intrinsic::x86_avx_vtestnzc_ps_256:
15254 case Intrinsic::x86_avx_vtestnzc_pd_256:
15255 IsTestPacked = true; // Fallthrough
15256 case Intrinsic::x86_sse41_ptestnzc:
15257 case Intrinsic::x86_avx_ptestnzc_256:
15259 X86CC = X86::COND_A;
15263 SDValue LHS = Op.getOperand(1);
15264 SDValue RHS = Op.getOperand(2);
15265 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15266 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15267 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15268 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15269 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15271 case Intrinsic::x86_avx512_kortestz_w:
15272 case Intrinsic::x86_avx512_kortestc_w: {
15273 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15274 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15275 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15276 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15277 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15278 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15279 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15282 case Intrinsic::x86_sse42_pcmpistria128:
15283 case Intrinsic::x86_sse42_pcmpestria128:
15284 case Intrinsic::x86_sse42_pcmpistric128:
15285 case Intrinsic::x86_sse42_pcmpestric128:
15286 case Intrinsic::x86_sse42_pcmpistrio128:
15287 case Intrinsic::x86_sse42_pcmpestrio128:
15288 case Intrinsic::x86_sse42_pcmpistris128:
15289 case Intrinsic::x86_sse42_pcmpestris128:
15290 case Intrinsic::x86_sse42_pcmpistriz128:
15291 case Intrinsic::x86_sse42_pcmpestriz128: {
15295 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15296 case Intrinsic::x86_sse42_pcmpistria128:
15297 Opcode = X86ISD::PCMPISTRI;
15298 X86CC = X86::COND_A;
15300 case Intrinsic::x86_sse42_pcmpestria128:
15301 Opcode = X86ISD::PCMPESTRI;
15302 X86CC = X86::COND_A;
15304 case Intrinsic::x86_sse42_pcmpistric128:
15305 Opcode = X86ISD::PCMPISTRI;
15306 X86CC = X86::COND_B;
15308 case Intrinsic::x86_sse42_pcmpestric128:
15309 Opcode = X86ISD::PCMPESTRI;
15310 X86CC = X86::COND_B;
15312 case Intrinsic::x86_sse42_pcmpistrio128:
15313 Opcode = X86ISD::PCMPISTRI;
15314 X86CC = X86::COND_O;
15316 case Intrinsic::x86_sse42_pcmpestrio128:
15317 Opcode = X86ISD::PCMPESTRI;
15318 X86CC = X86::COND_O;
15320 case Intrinsic::x86_sse42_pcmpistris128:
15321 Opcode = X86ISD::PCMPISTRI;
15322 X86CC = X86::COND_S;
15324 case Intrinsic::x86_sse42_pcmpestris128:
15325 Opcode = X86ISD::PCMPESTRI;
15326 X86CC = X86::COND_S;
15328 case Intrinsic::x86_sse42_pcmpistriz128:
15329 Opcode = X86ISD::PCMPISTRI;
15330 X86CC = X86::COND_E;
15332 case Intrinsic::x86_sse42_pcmpestriz128:
15333 Opcode = X86ISD::PCMPESTRI;
15334 X86CC = X86::COND_E;
15337 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15338 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15339 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15340 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15341 DAG.getConstant(X86CC, dl, MVT::i8),
15342 SDValue(PCMP.getNode(), 1));
15343 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15346 case Intrinsic::x86_sse42_pcmpistri128:
15347 case Intrinsic::x86_sse42_pcmpestri128: {
15349 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15350 Opcode = X86ISD::PCMPISTRI;
15352 Opcode = X86ISD::PCMPESTRI;
15354 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15355 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15356 return DAG.getNode(Opcode, dl, VTs, NewOps);
15359 case Intrinsic::x86_seh_lsda: {
15360 // Compute the symbol for the LSDA. We know it'll get emitted later.
15361 MachineFunction &MF = DAG.getMachineFunction();
15362 SDValue Op1 = Op.getOperand(1);
15364 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15365 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15366 GlobalValue::getRealLinkageName(Fn->getName()));
15367 StringRef Name = LSDASym->getName();
15368 assert(Name.data()[Name.size()] == '\0' && "not null terminated");
15370 // Generate a simple absolute symbol reference. This intrinsic is only
15371 // supported on 32-bit Windows, which isn't PIC.
15373 DAG.getTargetExternalSymbol(Name.data(), VT, X86II::MO_NOPREFIX);
15374 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15379 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15380 SDValue Src, SDValue Mask, SDValue Base,
15381 SDValue Index, SDValue ScaleOp, SDValue Chain,
15382 const X86Subtarget * Subtarget) {
15384 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15385 assert(C && "Invalid scale type");
15386 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15387 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15388 Index.getSimpleValueType().getVectorNumElements());
15390 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15392 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15394 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15395 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15396 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15397 SDValue Segment = DAG.getRegister(0, MVT::i32);
15398 if (Src.getOpcode() == ISD::UNDEF)
15399 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15400 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15401 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15402 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15403 return DAG.getMergeValues(RetOps, dl);
15406 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15407 SDValue Src, SDValue Mask, SDValue Base,
15408 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15410 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15411 assert(C && "Invalid scale type");
15412 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15413 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15414 SDValue Segment = DAG.getRegister(0, MVT::i32);
15415 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15416 Index.getSimpleValueType().getVectorNumElements());
15418 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15420 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15422 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15423 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15424 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15425 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15426 return SDValue(Res, 1);
15429 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15430 SDValue Mask, SDValue Base, SDValue Index,
15431 SDValue ScaleOp, SDValue Chain) {
15433 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15434 assert(C && "Invalid scale type");
15435 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15436 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15437 SDValue Segment = DAG.getRegister(0, MVT::i32);
15439 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15441 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15443 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15445 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15446 //SDVTList VTs = DAG.getVTList(MVT::Other);
15447 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15448 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15449 return SDValue(Res, 0);
15452 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15453 // read performance monitor counters (x86_rdpmc).
15454 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15455 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15456 SmallVectorImpl<SDValue> &Results) {
15457 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15458 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15461 // The ECX register is used to select the index of the performance counter
15463 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15465 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15467 // Reads the content of a 64-bit performance counter and returns it in the
15468 // registers EDX:EAX.
15469 if (Subtarget->is64Bit()) {
15470 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15471 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15474 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15475 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15478 Chain = HI.getValue(1);
15480 if (Subtarget->is64Bit()) {
15481 // The EAX register is loaded with the low-order 32 bits. The EDX register
15482 // is loaded with the supported high-order bits of the counter.
15483 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15484 DAG.getConstant(32, DL, MVT::i8));
15485 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15486 Results.push_back(Chain);
15490 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15491 SDValue Ops[] = { LO, HI };
15492 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15493 Results.push_back(Pair);
15494 Results.push_back(Chain);
15497 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15498 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15499 // also used to custom lower READCYCLECOUNTER nodes.
15500 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15501 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15502 SmallVectorImpl<SDValue> &Results) {
15503 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15504 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15507 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15508 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15509 // and the EAX register is loaded with the low-order 32 bits.
15510 if (Subtarget->is64Bit()) {
15511 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15512 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15515 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15516 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15519 SDValue Chain = HI.getValue(1);
15521 if (Opcode == X86ISD::RDTSCP_DAG) {
15522 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15524 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15525 // the ECX register. Add 'ecx' explicitly to the chain.
15526 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15528 // Explicitly store the content of ECX at the location passed in input
15529 // to the 'rdtscp' intrinsic.
15530 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15531 MachinePointerInfo(), false, false, 0);
15534 if (Subtarget->is64Bit()) {
15535 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15536 // the EAX register is loaded with the low-order 32 bits.
15537 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15538 DAG.getConstant(32, DL, MVT::i8));
15539 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15540 Results.push_back(Chain);
15544 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15545 SDValue Ops[] = { LO, HI };
15546 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15547 Results.push_back(Pair);
15548 Results.push_back(Chain);
15551 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15552 SelectionDAG &DAG) {
15553 SmallVector<SDValue, 2> Results;
15555 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15557 return DAG.getMergeValues(Results, DL);
15561 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15562 SelectionDAG &DAG) {
15563 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15565 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15570 switch(IntrData->Type) {
15572 llvm_unreachable("Unknown Intrinsic Type");
15576 // Emit the node with the right value type.
15577 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15578 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15580 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15581 // Otherwise return the value from Rand, which is always 0, casted to i32.
15582 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15583 DAG.getConstant(1, dl, Op->getValueType(1)),
15584 DAG.getConstant(X86::COND_B, dl, MVT::i32),
15585 SDValue(Result.getNode(), 1) };
15586 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15587 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15590 // Return { result, isValid, chain }.
15591 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15592 SDValue(Result.getNode(), 2));
15595 //gather(v1, mask, index, base, scale);
15596 SDValue Chain = Op.getOperand(0);
15597 SDValue Src = Op.getOperand(2);
15598 SDValue Base = Op.getOperand(3);
15599 SDValue Index = Op.getOperand(4);
15600 SDValue Mask = Op.getOperand(5);
15601 SDValue Scale = Op.getOperand(6);
15602 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15606 //scatter(base, mask, index, v1, scale);
15607 SDValue Chain = Op.getOperand(0);
15608 SDValue Base = Op.getOperand(2);
15609 SDValue Mask = Op.getOperand(3);
15610 SDValue Index = Op.getOperand(4);
15611 SDValue Src = Op.getOperand(5);
15612 SDValue Scale = Op.getOperand(6);
15613 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15617 SDValue Hint = Op.getOperand(6);
15618 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15619 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15620 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15621 SDValue Chain = Op.getOperand(0);
15622 SDValue Mask = Op.getOperand(2);
15623 SDValue Index = Op.getOperand(3);
15624 SDValue Base = Op.getOperand(4);
15625 SDValue Scale = Op.getOperand(5);
15626 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15628 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15630 SmallVector<SDValue, 2> Results;
15631 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15633 return DAG.getMergeValues(Results, dl);
15635 // Read Performance Monitoring Counters.
15637 SmallVector<SDValue, 2> Results;
15638 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15639 return DAG.getMergeValues(Results, dl);
15641 // XTEST intrinsics.
15643 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15644 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15645 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15646 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15648 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15649 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15650 Ret, SDValue(InTrans.getNode(), 1));
15654 SmallVector<SDValue, 2> Results;
15655 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15656 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15657 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15658 DAG.getConstant(-1, dl, MVT::i8));
15659 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15660 Op.getOperand(4), GenCF.getValue(1));
15661 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15662 Op.getOperand(5), MachinePointerInfo(),
15664 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15665 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15667 Results.push_back(SetCC);
15668 Results.push_back(Store);
15669 return DAG.getMergeValues(Results, dl);
15671 case COMPRESS_TO_MEM: {
15673 SDValue Mask = Op.getOperand(4);
15674 SDValue DataToCompress = Op.getOperand(3);
15675 SDValue Addr = Op.getOperand(2);
15676 SDValue Chain = Op.getOperand(0);
15678 if (isAllOnes(Mask)) // return just a store
15679 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15680 MachinePointerInfo(), false, false, 0);
15682 EVT VT = DataToCompress.getValueType();
15683 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15684 VT.getVectorNumElements());
15685 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15686 Mask.getValueType().getSizeInBits());
15687 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15688 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15689 DAG.getIntPtrConstant(0, dl));
15691 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15692 DataToCompress, DAG.getUNDEF(VT));
15693 return DAG.getStore(Chain, dl, Compressed, Addr,
15694 MachinePointerInfo(), false, false, 0);
15696 case EXPAND_FROM_MEM: {
15698 SDValue Mask = Op.getOperand(4);
15699 SDValue PathThru = Op.getOperand(3);
15700 SDValue Addr = Op.getOperand(2);
15701 SDValue Chain = Op.getOperand(0);
15702 EVT VT = Op.getValueType();
15704 if (isAllOnes(Mask)) // return just a load
15705 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15707 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15708 VT.getVectorNumElements());
15709 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15710 Mask.getValueType().getSizeInBits());
15711 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15712 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15713 DAG.getIntPtrConstant(0, dl));
15715 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15716 false, false, false, 0);
15718 SDValue Results[] = {
15719 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15721 return DAG.getMergeValues(Results, dl);
15726 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15727 SelectionDAG &DAG) const {
15728 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15729 MFI->setReturnAddressIsTaken(true);
15731 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15734 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15736 EVT PtrVT = getPointerTy();
15739 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15740 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15741 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15742 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15743 DAG.getNode(ISD::ADD, dl, PtrVT,
15744 FrameAddr, Offset),
15745 MachinePointerInfo(), false, false, false, 0);
15748 // Just load the return address.
15749 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15750 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15751 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15754 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15755 MachineFunction &MF = DAG.getMachineFunction();
15756 MachineFrameInfo *MFI = MF.getFrameInfo();
15757 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15758 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15759 EVT VT = Op.getValueType();
15761 MFI->setFrameAddressIsTaken(true);
15763 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15764 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15765 // is not possible to crawl up the stack without looking at the unwind codes
15767 int FrameAddrIndex = FuncInfo->getFAIndex();
15768 if (!FrameAddrIndex) {
15769 // Set up a frame object for the return address.
15770 unsigned SlotSize = RegInfo->getSlotSize();
15771 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15772 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15773 FuncInfo->setFAIndex(FrameAddrIndex);
15775 return DAG.getFrameIndex(FrameAddrIndex, VT);
15778 unsigned FrameReg =
15779 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15780 SDLoc dl(Op); // FIXME probably not meaningful
15781 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15782 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15783 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15784 "Invalid Frame Register!");
15785 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15787 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15788 MachinePointerInfo(),
15789 false, false, false, 0);
15793 // FIXME? Maybe this could be a TableGen attribute on some registers and
15794 // this table could be generated automatically from RegInfo.
15795 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15797 unsigned Reg = StringSwitch<unsigned>(RegName)
15798 .Case("esp", X86::ESP)
15799 .Case("rsp", X86::RSP)
15803 report_fatal_error("Invalid register name global variable");
15806 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15807 SelectionDAG &DAG) const {
15808 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15809 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15812 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15813 SDValue Chain = Op.getOperand(0);
15814 SDValue Offset = Op.getOperand(1);
15815 SDValue Handler = Op.getOperand(2);
15818 EVT PtrVT = getPointerTy();
15819 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15820 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15821 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15822 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15823 "Invalid Frame Register!");
15824 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15825 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15827 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15828 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15830 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15831 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15833 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15835 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15836 DAG.getRegister(StoreAddrReg, PtrVT));
15839 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15840 SelectionDAG &DAG) const {
15842 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15843 DAG.getVTList(MVT::i32, MVT::Other),
15844 Op.getOperand(0), Op.getOperand(1));
15847 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15848 SelectionDAG &DAG) const {
15850 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15851 Op.getOperand(0), Op.getOperand(1));
15854 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15855 return Op.getOperand(0);
15858 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15859 SelectionDAG &DAG) const {
15860 SDValue Root = Op.getOperand(0);
15861 SDValue Trmp = Op.getOperand(1); // trampoline
15862 SDValue FPtr = Op.getOperand(2); // nested function
15863 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15866 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15867 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15869 if (Subtarget->is64Bit()) {
15870 SDValue OutChains[6];
15872 // Large code-model.
15873 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15874 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15876 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15877 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15879 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15881 // Load the pointer to the nested function into R11.
15882 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15883 SDValue Addr = Trmp;
15884 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15885 Addr, MachinePointerInfo(TrmpAddr),
15888 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15889 DAG.getConstant(2, dl, MVT::i64));
15890 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15891 MachinePointerInfo(TrmpAddr, 2),
15894 // Load the 'nest' parameter value into R10.
15895 // R10 is specified in X86CallingConv.td
15896 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15897 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15898 DAG.getConstant(10, dl, MVT::i64));
15899 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15900 Addr, MachinePointerInfo(TrmpAddr, 10),
15903 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15904 DAG.getConstant(12, dl, MVT::i64));
15905 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15906 MachinePointerInfo(TrmpAddr, 12),
15909 // Jump to the nested function.
15910 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15911 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15912 DAG.getConstant(20, dl, MVT::i64));
15913 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15914 Addr, MachinePointerInfo(TrmpAddr, 20),
15917 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15918 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15919 DAG.getConstant(22, dl, MVT::i64));
15920 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15921 Addr, MachinePointerInfo(TrmpAddr, 22),
15924 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15926 const Function *Func =
15927 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15928 CallingConv::ID CC = Func->getCallingConv();
15933 llvm_unreachable("Unsupported calling convention");
15934 case CallingConv::C:
15935 case CallingConv::X86_StdCall: {
15936 // Pass 'nest' parameter in ECX.
15937 // Must be kept in sync with X86CallingConv.td
15938 NestReg = X86::ECX;
15940 // Check that ECX wasn't needed by an 'inreg' parameter.
15941 FunctionType *FTy = Func->getFunctionType();
15942 const AttributeSet &Attrs = Func->getAttributes();
15944 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15945 unsigned InRegCount = 0;
15948 for (FunctionType::param_iterator I = FTy->param_begin(),
15949 E = FTy->param_end(); I != E; ++I, ++Idx)
15950 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15951 // FIXME: should only count parameters that are lowered to integers.
15952 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15954 if (InRegCount > 2) {
15955 report_fatal_error("Nest register in use - reduce number of inreg"
15961 case CallingConv::X86_FastCall:
15962 case CallingConv::X86_ThisCall:
15963 case CallingConv::Fast:
15964 // Pass 'nest' parameter in EAX.
15965 // Must be kept in sync with X86CallingConv.td
15966 NestReg = X86::EAX;
15970 SDValue OutChains[4];
15971 SDValue Addr, Disp;
15973 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15974 DAG.getConstant(10, dl, MVT::i32));
15975 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15977 // This is storing the opcode for MOV32ri.
15978 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15979 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15980 OutChains[0] = DAG.getStore(Root, dl,
15981 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15982 Trmp, MachinePointerInfo(TrmpAddr),
15985 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15986 DAG.getConstant(1, dl, MVT::i32));
15987 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15988 MachinePointerInfo(TrmpAddr, 1),
15991 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15992 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15993 DAG.getConstant(5, dl, MVT::i32));
15994 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15995 Addr, MachinePointerInfo(TrmpAddr, 5),
15998 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15999 DAG.getConstant(6, dl, MVT::i32));
16000 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16001 MachinePointerInfo(TrmpAddr, 6),
16004 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16008 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16009 SelectionDAG &DAG) const {
16011 The rounding mode is in bits 11:10 of FPSR, and has the following
16013 00 Round to nearest
16018 FLT_ROUNDS, on the other hand, expects the following:
16025 To perform the conversion, we do:
16026 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16029 MachineFunction &MF = DAG.getMachineFunction();
16030 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16031 unsigned StackAlignment = TFI.getStackAlignment();
16032 MVT VT = Op.getSimpleValueType();
16035 // Save FP Control Word to stack slot
16036 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16037 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16039 MachineMemOperand *MMO =
16040 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16041 MachineMemOperand::MOStore, 2, 2);
16043 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16044 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16045 DAG.getVTList(MVT::Other),
16046 Ops, MVT::i16, MMO);
16048 // Load FP Control Word from stack slot
16049 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16050 MachinePointerInfo(), false, false, false, 0);
16052 // Transform as necessary
16054 DAG.getNode(ISD::SRL, DL, MVT::i16,
16055 DAG.getNode(ISD::AND, DL, MVT::i16,
16056 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16057 DAG.getConstant(11, DL, MVT::i8));
16059 DAG.getNode(ISD::SRL, DL, MVT::i16,
16060 DAG.getNode(ISD::AND, DL, MVT::i16,
16061 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16062 DAG.getConstant(9, DL, MVT::i8));
16065 DAG.getNode(ISD::AND, DL, MVT::i16,
16066 DAG.getNode(ISD::ADD, DL, MVT::i16,
16067 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16068 DAG.getConstant(1, DL, MVT::i16)),
16069 DAG.getConstant(3, DL, MVT::i16));
16071 return DAG.getNode((VT.getSizeInBits() < 16 ?
16072 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16075 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16076 MVT VT = Op.getSimpleValueType();
16078 unsigned NumBits = VT.getSizeInBits();
16081 Op = Op.getOperand(0);
16082 if (VT == MVT::i8) {
16083 // Zero extend to i32 since there is not an i8 bsr.
16085 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16088 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16089 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16090 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16092 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16095 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16096 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16099 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16101 // Finally xor with NumBits-1.
16102 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16103 DAG.getConstant(NumBits - 1, dl, OpVT));
16106 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16110 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16111 MVT VT = Op.getSimpleValueType();
16113 unsigned NumBits = VT.getSizeInBits();
16116 Op = Op.getOperand(0);
16117 if (VT == MVT::i8) {
16118 // Zero extend to i32 since there is not an i8 bsr.
16120 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16123 // Issue a bsr (scan bits in reverse).
16124 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16125 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16127 // And xor with NumBits-1.
16128 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16129 DAG.getConstant(NumBits - 1, dl, OpVT));
16132 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16136 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16137 MVT VT = Op.getSimpleValueType();
16138 unsigned NumBits = VT.getSizeInBits();
16140 Op = Op.getOperand(0);
16142 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16143 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16144 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16146 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16149 DAG.getConstant(NumBits, dl, VT),
16150 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16153 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16156 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16157 // ones, and then concatenate the result back.
16158 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16159 MVT VT = Op.getSimpleValueType();
16161 assert(VT.is256BitVector() && VT.isInteger() &&
16162 "Unsupported value type for operation");
16164 unsigned NumElems = VT.getVectorNumElements();
16167 // Extract the LHS vectors
16168 SDValue LHS = Op.getOperand(0);
16169 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16170 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16172 // Extract the RHS vectors
16173 SDValue RHS = Op.getOperand(1);
16174 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16175 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16177 MVT EltVT = VT.getVectorElementType();
16178 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16180 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16181 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16182 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16185 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16186 if (Op.getValueType() == MVT::i1)
16187 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16188 Op.getOperand(0), Op.getOperand(1));
16189 assert(Op.getSimpleValueType().is256BitVector() &&
16190 Op.getSimpleValueType().isInteger() &&
16191 "Only handle AVX 256-bit vector integer operation");
16192 return Lower256IntArith(Op, DAG);
16195 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16196 if (Op.getValueType() == MVT::i1)
16197 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16198 Op.getOperand(0), Op.getOperand(1));
16199 assert(Op.getSimpleValueType().is256BitVector() &&
16200 Op.getSimpleValueType().isInteger() &&
16201 "Only handle AVX 256-bit vector integer operation");
16202 return Lower256IntArith(Op, DAG);
16205 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16206 SelectionDAG &DAG) {
16208 MVT VT = Op.getSimpleValueType();
16211 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16213 // Decompose 256-bit ops into smaller 128-bit ops.
16214 if (VT.is256BitVector() && !Subtarget->hasInt256())
16215 return Lower256IntArith(Op, DAG);
16217 SDValue A = Op.getOperand(0);
16218 SDValue B = Op.getOperand(1);
16220 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16221 // pairs, multiply and truncate.
16222 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16223 if (Subtarget->hasInt256()) {
16224 if (VT == MVT::v32i8) {
16225 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16226 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16227 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16228 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16229 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16230 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16231 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16232 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16233 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16234 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16237 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16238 return DAG.getNode(
16239 ISD::TRUNCATE, dl, VT,
16240 DAG.getNode(ISD::MUL, dl, ExVT,
16241 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16242 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16245 assert(VT == MVT::v16i8 &&
16246 "Pre-AVX2 support only supports v16i8 multiplication");
16247 MVT ExVT = MVT::v8i16;
16249 // Extract the lo parts and sign extend to i16
16251 if (Subtarget->hasSSE41()) {
16252 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16253 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16255 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16256 -1, 4, -1, 5, -1, 6, -1, 7};
16257 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16258 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16259 ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16260 BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16261 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16262 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16265 // Extract the hi parts and sign extend to i16
16267 if (Subtarget->hasSSE41()) {
16268 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16269 -1, -1, -1, -1, -1, -1, -1, -1};
16270 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16271 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16272 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16273 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16275 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16276 -1, 12, -1, 13, -1, 14, -1, 15};
16277 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16278 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16279 AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16280 BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16281 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16282 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16285 // Multiply, mask the lower 8bits of the lo/hi results and pack
16286 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16287 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16288 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16289 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16290 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16293 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16294 if (VT == MVT::v4i32) {
16295 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16296 "Should not custom lower when pmuldq is available!");
16298 // Extract the odd parts.
16299 static const int UnpackMask[] = { 1, -1, 3, -1 };
16300 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16301 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16303 // Multiply the even parts.
16304 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16305 // Now multiply odd parts.
16306 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16308 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16309 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16311 // Merge the two vectors back together with a shuffle. This expands into 2
16313 static const int ShufMask[] = { 0, 4, 2, 6 };
16314 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16317 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16318 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16320 // Ahi = psrlqi(a, 32);
16321 // Bhi = psrlqi(b, 32);
16323 // AloBlo = pmuludq(a, b);
16324 // AloBhi = pmuludq(a, Bhi);
16325 // AhiBlo = pmuludq(Ahi, b);
16327 // AloBhi = psllqi(AloBhi, 32);
16328 // AhiBlo = psllqi(AhiBlo, 32);
16329 // return AloBlo + AloBhi + AhiBlo;
16331 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16332 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16334 // Bit cast to 32-bit vectors for MULUDQ
16335 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16336 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16337 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16338 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16339 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16340 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16342 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16343 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16344 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16346 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16347 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16349 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16350 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16353 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16354 assert(Subtarget->isTargetWin64() && "Unexpected target");
16355 EVT VT = Op.getValueType();
16356 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16357 "Unexpected return type for lowering");
16361 switch (Op->getOpcode()) {
16362 default: llvm_unreachable("Unexpected request for libcall!");
16363 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
16364 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
16365 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
16366 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
16367 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
16368 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16372 SDValue InChain = DAG.getEntryNode();
16374 TargetLowering::ArgListTy Args;
16375 TargetLowering::ArgListEntry Entry;
16376 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16377 EVT ArgVT = Op->getOperand(i).getValueType();
16378 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16379 "Unexpected argument type for lowering");
16380 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16381 Entry.Node = StackPtr;
16382 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16384 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16385 Entry.Ty = PointerType::get(ArgTy,0);
16386 Entry.isSExt = false;
16387 Entry.isZExt = false;
16388 Args.push_back(Entry);
16391 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16394 TargetLowering::CallLoweringInfo CLI(DAG);
16395 CLI.setDebugLoc(dl).setChain(InChain)
16396 .setCallee(getLibcallCallingConv(LC),
16397 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16398 Callee, std::move(Args), 0)
16399 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16401 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16402 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16405 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16406 SelectionDAG &DAG) {
16407 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16408 EVT VT = Op0.getValueType();
16411 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16412 (VT == MVT::v8i32 && Subtarget->hasInt256()));
16414 // PMULxD operations multiply each even value (starting at 0) of LHS with
16415 // the related value of RHS and produce a widen result.
16416 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16417 // => <2 x i64> <ae|cg>
16419 // In other word, to have all the results, we need to perform two PMULxD:
16420 // 1. one with the even values.
16421 // 2. one with the odd values.
16422 // To achieve #2, with need to place the odd values at an even position.
16424 // Place the odd value at an even position (basically, shift all values 1
16425 // step to the left):
16426 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16427 // <a|b|c|d> => <b|undef|d|undef>
16428 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16429 // <e|f|g|h> => <f|undef|h|undef>
16430 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16432 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16434 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16435 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16437 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16438 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16439 // => <2 x i64> <ae|cg>
16440 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16441 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16442 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16443 // => <2 x i64> <bf|dh>
16444 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16445 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16447 // Shuffle it back into the right order.
16448 SDValue Highs, Lows;
16449 if (VT == MVT::v8i32) {
16450 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16451 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16452 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16453 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16455 const int HighMask[] = {1, 5, 3, 7};
16456 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16457 const int LowMask[] = {0, 4, 2, 6};
16458 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16461 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16462 // unsigned multiply.
16463 if (IsSigned && !Subtarget->hasSSE41()) {
16465 DAG.getConstant(31, dl,
16466 DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16467 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16468 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16469 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16470 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16472 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16473 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16476 // The first result of MUL_LOHI is actually the low value, followed by the
16478 SDValue Ops[] = {Lows, Highs};
16479 return DAG.getMergeValues(Ops, dl);
16482 // Return true if the requred (according to Opcode) shift-imm form is natively
16483 // supported by the Subtarget
16484 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16486 if (VT.getScalarSizeInBits() < 16)
16489 if (VT.is512BitVector() &&
16490 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16493 bool LShift = VT.is128BitVector() ||
16494 (VT.is256BitVector() && Subtarget->hasInt256());
16496 bool AShift = LShift && (Subtarget->hasVLX() ||
16497 (VT != MVT::v2i64 && VT != MVT::v4i64));
16498 return (Opcode == ISD::SRA) ? AShift : LShift;
16501 // The shift amount is a variable, but it is the same for all vector lanes.
16502 // These instrcutions are defined together with shift-immediate.
16504 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
16506 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16509 // Return true if the requred (according to Opcode) variable-shift form is
16510 // natively supported by the Subtarget
16511 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
16514 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16517 // vXi16 supported only on AVX-512, BWI
16518 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16521 if (VT.is512BitVector() || Subtarget->hasVLX())
16524 bool LShift = VT.is128BitVector() || VT.is256BitVector();
16525 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
16526 return (Opcode == ISD::SRA) ? AShift : LShift;
16529 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16530 const X86Subtarget *Subtarget) {
16531 MVT VT = Op.getSimpleValueType();
16533 SDValue R = Op.getOperand(0);
16534 SDValue Amt = Op.getOperand(1);
16536 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16537 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16539 // Optimize shl/srl/sra with constant shift amount.
16540 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16541 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16542 uint64_t ShiftAmt = ShiftConst->getZExtValue();
16544 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16545 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16547 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16548 unsigned NumElts = VT.getVectorNumElements();
16549 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16551 if (Op.getOpcode() == ISD::SHL) {
16552 // Simple i8 add case
16554 return DAG.getNode(ISD::ADD, dl, VT, R, R);
16556 // Make a large shift.
16557 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16559 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16560 // Zero out the rightmost bits.
16561 SmallVector<SDValue, 32> V(
16562 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16563 return DAG.getNode(ISD::AND, dl, VT, SHL,
16564 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16566 if (Op.getOpcode() == ISD::SRL) {
16567 // Make a large shift.
16568 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16570 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16571 // Zero out the leftmost bits.
16572 SmallVector<SDValue, 32> V(
16573 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16574 return DAG.getNode(ISD::AND, dl, VT, SRL,
16575 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16577 if (Op.getOpcode() == ISD::SRA) {
16578 if (ShiftAmt == 7) {
16579 // R s>> 7 === R s< 0
16580 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16581 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16584 // R s>> a === ((R u>> a) ^ m) - m
16585 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16586 SmallVector<SDValue, 32> V(NumElts,
16587 DAG.getConstant(128 >> ShiftAmt, dl,
16589 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16590 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16591 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16594 llvm_unreachable("Unknown shift opcode.");
16599 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16600 if (!Subtarget->is64Bit() &&
16601 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16602 Amt.getOpcode() == ISD::BITCAST &&
16603 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16604 Amt = Amt.getOperand(0);
16605 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16606 VT.getVectorNumElements();
16607 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16608 uint64_t ShiftAmt = 0;
16609 for (unsigned i = 0; i != Ratio; ++i) {
16610 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16614 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16616 // Check remaining shift amounts.
16617 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16618 uint64_t ShAmt = 0;
16619 for (unsigned j = 0; j != Ratio; ++j) {
16620 ConstantSDNode *C =
16621 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16625 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16627 if (ShAmt != ShiftAmt)
16630 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16636 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16637 const X86Subtarget* Subtarget) {
16638 MVT VT = Op.getSimpleValueType();
16640 SDValue R = Op.getOperand(0);
16641 SDValue Amt = Op.getOperand(1);
16643 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16644 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16646 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16647 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16649 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16651 EVT EltVT = VT.getVectorElementType();
16653 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16654 // Check if this build_vector node is doing a splat.
16655 // If so, then set BaseShAmt equal to the splat value.
16656 BaseShAmt = BV->getSplatValue();
16657 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16658 BaseShAmt = SDValue();
16660 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16661 Amt = Amt.getOperand(0);
16663 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16664 if (SVN && SVN->isSplat()) {
16665 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16666 SDValue InVec = Amt.getOperand(0);
16667 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16668 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16669 "Unexpected shuffle index found!");
16670 BaseShAmt = InVec.getOperand(SplatIdx);
16671 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16672 if (ConstantSDNode *C =
16673 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16674 if (C->getZExtValue() == SplatIdx)
16675 BaseShAmt = InVec.getOperand(1);
16680 // Avoid introducing an extract element from a shuffle.
16681 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16682 DAG.getIntPtrConstant(SplatIdx, dl));
16686 if (BaseShAmt.getNode()) {
16687 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16688 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16689 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16690 else if (EltVT.bitsLT(MVT::i32))
16691 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16693 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16697 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16698 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
16699 Amt.getOpcode() == ISD::BITCAST &&
16700 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16701 Amt = Amt.getOperand(0);
16702 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16703 VT.getVectorNumElements();
16704 std::vector<SDValue> Vals(Ratio);
16705 for (unsigned i = 0; i != Ratio; ++i)
16706 Vals[i] = Amt.getOperand(i);
16707 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16708 for (unsigned j = 0; j != Ratio; ++j)
16709 if (Vals[j] != Amt.getOperand(i + j))
16712 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16717 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16718 SelectionDAG &DAG) {
16719 MVT VT = Op.getSimpleValueType();
16721 SDValue R = Op.getOperand(0);
16722 SDValue Amt = Op.getOperand(1);
16724 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16725 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16727 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16730 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16733 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16736 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16737 // shifts per-lane and then shuffle the partial results back together.
16738 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16739 // Splat the shift amounts so the scalar shifts above will catch it.
16740 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16741 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16742 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16743 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16744 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16747 // If possible, lower this packed shift into a vector multiply instead of
16748 // expanding it into a sequence of scalar shifts.
16749 // Do this only if the vector shift count is a constant build_vector.
16750 if (Op.getOpcode() == ISD::SHL &&
16751 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16752 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16753 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16754 SmallVector<SDValue, 8> Elts;
16755 EVT SVT = VT.getScalarType();
16756 unsigned SVTBits = SVT.getSizeInBits();
16757 const APInt &One = APInt(SVTBits, 1);
16758 unsigned NumElems = VT.getVectorNumElements();
16760 for (unsigned i=0; i !=NumElems; ++i) {
16761 SDValue Op = Amt->getOperand(i);
16762 if (Op->getOpcode() == ISD::UNDEF) {
16763 Elts.push_back(Op);
16767 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16768 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16769 uint64_t ShAmt = C.getZExtValue();
16770 if (ShAmt >= SVTBits) {
16771 Elts.push_back(DAG.getUNDEF(SVT));
16774 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16776 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16777 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16780 // Lower SHL with variable shift amount.
16781 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16782 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16784 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16785 DAG.getConstant(0x3f800000U, dl, VT));
16786 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16787 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16788 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16791 // If possible, lower this shift as a sequence of two shifts by
16792 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16794 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16796 // Could be rewritten as:
16797 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16799 // The advantage is that the two shifts from the example would be
16800 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16801 // the vector shift into four scalar shifts plus four pairs of vector
16803 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16804 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16805 unsigned TargetOpcode = X86ISD::MOVSS;
16806 bool CanBeSimplified;
16807 // The splat value for the first packed shift (the 'X' from the example).
16808 SDValue Amt1 = Amt->getOperand(0);
16809 // The splat value for the second packed shift (the 'Y' from the example).
16810 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16811 Amt->getOperand(2);
16813 // See if it is possible to replace this node with a sequence of
16814 // two shifts followed by a MOVSS/MOVSD
16815 if (VT == MVT::v4i32) {
16816 // Check if it is legal to use a MOVSS.
16817 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16818 Amt2 == Amt->getOperand(3);
16819 if (!CanBeSimplified) {
16820 // Otherwise, check if we can still simplify this node using a MOVSD.
16821 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16822 Amt->getOperand(2) == Amt->getOperand(3);
16823 TargetOpcode = X86ISD::MOVSD;
16824 Amt2 = Amt->getOperand(2);
16827 // Do similar checks for the case where the machine value type
16829 CanBeSimplified = Amt1 == Amt->getOperand(1);
16830 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16831 CanBeSimplified = Amt2 == Amt->getOperand(i);
16833 if (!CanBeSimplified) {
16834 TargetOpcode = X86ISD::MOVSD;
16835 CanBeSimplified = true;
16836 Amt2 = Amt->getOperand(4);
16837 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16838 CanBeSimplified = Amt1 == Amt->getOperand(i);
16839 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16840 CanBeSimplified = Amt2 == Amt->getOperand(j);
16844 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16845 isa<ConstantSDNode>(Amt2)) {
16846 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16847 EVT CastVT = MVT::v4i32;
16849 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16850 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16852 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16853 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16854 if (TargetOpcode == X86ISD::MOVSD)
16855 CastVT = MVT::v2i64;
16856 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16857 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16858 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16860 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16864 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16865 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16866 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16868 SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16869 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16870 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16872 // r = VSELECT(r, shl(r, 4), a);
16873 SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16874 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16877 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16878 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16879 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16881 // r = VSELECT(r, shl(r, 2), a);
16882 M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16883 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16886 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16887 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16888 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16890 // return VSELECT(r, r+r, a);
16891 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16892 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16896 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16897 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16898 // solution better.
16899 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16900 MVT ExtVT = MVT::v8i32;
16902 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16903 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
16904 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
16905 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16906 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
16909 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
16910 MVT ExtVT = MVT::v8i32;
16911 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
16912 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
16913 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
16914 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
16915 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
16916 ALo = DAG.getNode(ISD::BITCAST, dl, ExtVT, ALo);
16917 AHi = DAG.getNode(ISD::BITCAST, dl, ExtVT, AHi);
16918 RLo = DAG.getNode(ISD::BITCAST, dl, ExtVT, RLo);
16919 RHi = DAG.getNode(ISD::BITCAST, dl, ExtVT, RHi);
16920 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
16921 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
16922 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
16923 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
16924 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
16927 // Decompose 256-bit shifts into smaller 128-bit shifts.
16928 if (VT.is256BitVector()) {
16929 unsigned NumElems = VT.getVectorNumElements();
16930 MVT EltVT = VT.getVectorElementType();
16931 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16933 // Extract the two vectors
16934 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16935 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16937 // Recreate the shift amount vectors
16938 SDValue Amt1, Amt2;
16939 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16940 // Constant shift amount
16941 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16942 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16943 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16945 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16946 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16948 // Variable shift amount
16949 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16950 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16953 // Issue new vector shifts for the smaller types
16954 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16955 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16957 // Concatenate the result back
16958 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16964 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16965 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16966 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16967 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16968 // has only one use.
16969 SDNode *N = Op.getNode();
16970 SDValue LHS = N->getOperand(0);
16971 SDValue RHS = N->getOperand(1);
16972 unsigned BaseOp = 0;
16975 switch (Op.getOpcode()) {
16976 default: llvm_unreachable("Unknown ovf instruction!");
16978 // A subtract of one will be selected as a INC. Note that INC doesn't
16979 // set CF, so we can't do this for UADDO.
16980 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16982 BaseOp = X86ISD::INC;
16983 Cond = X86::COND_O;
16986 BaseOp = X86ISD::ADD;
16987 Cond = X86::COND_O;
16990 BaseOp = X86ISD::ADD;
16991 Cond = X86::COND_B;
16994 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16995 // set CF, so we can't do this for USUBO.
16996 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16998 BaseOp = X86ISD::DEC;
16999 Cond = X86::COND_O;
17002 BaseOp = X86ISD::SUB;
17003 Cond = X86::COND_O;
17006 BaseOp = X86ISD::SUB;
17007 Cond = X86::COND_B;
17010 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17011 Cond = X86::COND_O;
17013 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17014 if (N->getValueType(0) == MVT::i8) {
17015 BaseOp = X86ISD::UMUL8;
17016 Cond = X86::COND_O;
17019 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17021 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17024 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17025 DAG.getConstant(X86::COND_O, DL, MVT::i32),
17026 SDValue(Sum.getNode(), 2));
17028 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17032 // Also sets EFLAGS.
17033 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17034 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17037 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17038 DAG.getConstant(Cond, DL, MVT::i32),
17039 SDValue(Sum.getNode(), 1));
17041 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17044 /// Returns true if the operand type is exactly twice the native width, and
17045 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17046 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17047 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17048 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17049 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17052 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17053 else if (OpWidth == 128)
17054 return Subtarget->hasCmpxchg16b();
17059 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17060 return needsCmpXchgNb(SI->getValueOperand()->getType());
17063 // Note: this turns large loads into lock cmpxchg8b/16b.
17064 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17065 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17066 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17067 return needsCmpXchgNb(PTy->getElementType());
17070 TargetLoweringBase::AtomicRMWExpansionKind
17071 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17072 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17073 const Type *MemType = AI->getType();
17075 // If the operand is too big, we must see if cmpxchg8/16b is available
17076 // and default to library calls otherwise.
17077 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17078 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17079 : AtomicRMWExpansionKind::None;
17082 AtomicRMWInst::BinOp Op = AI->getOperation();
17085 llvm_unreachable("Unknown atomic operation");
17086 case AtomicRMWInst::Xchg:
17087 case AtomicRMWInst::Add:
17088 case AtomicRMWInst::Sub:
17089 // It's better to use xadd, xsub or xchg for these in all cases.
17090 return AtomicRMWExpansionKind::None;
17091 case AtomicRMWInst::Or:
17092 case AtomicRMWInst::And:
17093 case AtomicRMWInst::Xor:
17094 // If the atomicrmw's result isn't actually used, we can just add a "lock"
17095 // prefix to a normal instruction for these operations.
17096 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17097 : AtomicRMWExpansionKind::None;
17098 case AtomicRMWInst::Nand:
17099 case AtomicRMWInst::Max:
17100 case AtomicRMWInst::Min:
17101 case AtomicRMWInst::UMax:
17102 case AtomicRMWInst::UMin:
17103 // These always require a non-trivial set of data operations on x86. We must
17104 // use a cmpxchg loop.
17105 return AtomicRMWExpansionKind::CmpXChg;
17109 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17110 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17111 // no-sse2). There isn't any reason to disable it if the target processor
17113 return Subtarget.hasSSE2() || Subtarget.is64Bit();
17117 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17118 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17119 const Type *MemType = AI->getType();
17120 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17121 // there is no benefit in turning such RMWs into loads, and it is actually
17122 // harmful as it introduces a mfence.
17123 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17126 auto Builder = IRBuilder<>(AI);
17127 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17128 auto SynchScope = AI->getSynchScope();
17129 // We must restrict the ordering to avoid generating loads with Release or
17130 // ReleaseAcquire orderings.
17131 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17132 auto Ptr = AI->getPointerOperand();
17134 // Before the load we need a fence. Here is an example lifted from
17135 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17138 // x.store(1, relaxed);
17139 // r1 = y.fetch_add(0, release);
17141 // y.fetch_add(42, acquire);
17142 // r2 = x.load(relaxed);
17143 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17144 // lowered to just a load without a fence. A mfence flushes the store buffer,
17145 // making the optimization clearly correct.
17146 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17147 // otherwise, we might be able to be more agressive on relaxed idempotent
17148 // rmw. In practice, they do not look useful, so we don't try to be
17149 // especially clever.
17150 if (SynchScope == SingleThread)
17151 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17152 // the IR level, so we must wrap it in an intrinsic.
17155 if (!hasMFENCE(*Subtarget))
17156 // FIXME: it might make sense to use a locked operation here but on a
17157 // different cache-line to prevent cache-line bouncing. In practice it
17158 // is probably a small win, and x86 processors without mfence are rare
17159 // enough that we do not bother.
17163 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17164 Builder.CreateCall(MFence, {});
17166 // Finally we can emit the atomic load.
17167 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17168 AI->getType()->getPrimitiveSizeInBits());
17169 Loaded->setAtomic(Order, SynchScope);
17170 AI->replaceAllUsesWith(Loaded);
17171 AI->eraseFromParent();
17175 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17176 SelectionDAG &DAG) {
17178 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17179 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17180 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17181 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17183 // The only fence that needs an instruction is a sequentially-consistent
17184 // cross-thread fence.
17185 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17186 if (hasMFENCE(*Subtarget))
17187 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17189 SDValue Chain = Op.getOperand(0);
17190 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17192 DAG.getRegister(X86::ESP, MVT::i32), // Base
17193 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
17194 DAG.getRegister(0, MVT::i32), // Index
17195 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
17196 DAG.getRegister(0, MVT::i32), // Segment.
17200 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17201 return SDValue(Res, 0);
17204 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17205 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17208 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17209 SelectionDAG &DAG) {
17210 MVT T = Op.getSimpleValueType();
17214 switch(T.SimpleTy) {
17215 default: llvm_unreachable("Invalid value type!");
17216 case MVT::i8: Reg = X86::AL; size = 1; break;
17217 case MVT::i16: Reg = X86::AX; size = 2; break;
17218 case MVT::i32: Reg = X86::EAX; size = 4; break;
17220 assert(Subtarget->is64Bit() && "Node not type legal!");
17221 Reg = X86::RAX; size = 8;
17224 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17225 Op.getOperand(2), SDValue());
17226 SDValue Ops[] = { cpIn.getValue(0),
17229 DAG.getTargetConstant(size, DL, MVT::i8),
17230 cpIn.getValue(1) };
17231 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17232 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17233 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17237 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17238 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17239 MVT::i32, cpOut.getValue(2));
17240 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17241 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17244 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17245 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17246 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17250 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17251 SelectionDAG &DAG) {
17252 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17253 MVT DstVT = Op.getSimpleValueType();
17255 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17256 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17257 if (DstVT != MVT::f64)
17258 // This conversion needs to be expanded.
17261 SDValue InVec = Op->getOperand(0);
17263 unsigned NumElts = SrcVT.getVectorNumElements();
17264 EVT SVT = SrcVT.getVectorElementType();
17266 // Widen the vector in input in the case of MVT::v2i32.
17267 // Example: from MVT::v2i32 to MVT::v4i32.
17268 SmallVector<SDValue, 16> Elts;
17269 for (unsigned i = 0, e = NumElts; i != e; ++i)
17270 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17271 DAG.getIntPtrConstant(i, dl)));
17273 // Explicitly mark the extra elements as Undef.
17274 Elts.append(NumElts, DAG.getUNDEF(SVT));
17276 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17277 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17278 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17279 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17280 DAG.getIntPtrConstant(0, dl));
17283 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17284 Subtarget->hasMMX() && "Unexpected custom BITCAST");
17285 assert((DstVT == MVT::i64 ||
17286 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17287 "Unexpected custom BITCAST");
17288 // i64 <=> MMX conversions are Legal.
17289 if (SrcVT==MVT::i64 && DstVT.isVector())
17291 if (DstVT==MVT::i64 && SrcVT.isVector())
17293 // MMX <=> MMX conversions are Legal.
17294 if (SrcVT.isVector() && DstVT.isVector())
17296 // All other conversions need to be expanded.
17300 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17301 SelectionDAG &DAG) {
17302 SDNode *Node = Op.getNode();
17305 Op = Op.getOperand(0);
17306 EVT VT = Op.getValueType();
17307 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17308 "CTPOP lowering only implemented for 128/256-bit wide vector types");
17310 unsigned NumElts = VT.getVectorNumElements();
17311 EVT EltVT = VT.getVectorElementType();
17312 unsigned Len = EltVT.getSizeInBits();
17314 // This is the vectorized version of the "best" algorithm from
17315 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17316 // with a minor tweak to use a series of adds + shifts instead of vector
17317 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17319 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17320 // v8i32 => Always profitable
17322 // FIXME: There a couple of possible improvements:
17324 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17325 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17327 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17328 "CTPOP not implemented for this vector element type.");
17330 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17331 // extra legalization.
17332 bool NeedsBitcast = EltVT == MVT::i32;
17333 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17335 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17337 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17339 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17342 // v = v - ((v >> 1) & 0x55555555...)
17343 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17344 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17345 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17347 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17349 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17350 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17352 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17354 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17355 if (VT != And.getValueType())
17356 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17357 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17359 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17360 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17361 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17362 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17363 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17365 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17366 if (NeedsBitcast) {
17367 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17368 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17369 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17372 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17373 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17374 if (VT != AndRHS.getValueType()) {
17375 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17376 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17378 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17380 // v = (v + (v >> 4)) & 0x0F0F0F0F...
17381 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17382 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17383 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17384 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17386 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17387 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17388 if (NeedsBitcast) {
17389 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17390 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17392 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17393 if (VT != And.getValueType())
17394 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17396 // The algorithm mentioned above uses:
17397 // v = (v * 0x01010101...) >> (Len - 8)
17399 // Change it to use vector adds + vector shifts which yield faster results on
17400 // Haswell than using vector integer multiplication.
17402 // For i32 elements:
17403 // v = v + (v >> 8)
17404 // v = v + (v >> 16)
17406 // For i64 elements:
17407 // v = v + (v >> 8)
17408 // v = v + (v >> 16)
17409 // v = v + (v >> 32)
17412 SmallVector<SDValue, 8> Csts;
17413 for (unsigned i = 8; i <= Len/2; i *= 2) {
17414 Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17415 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17416 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17417 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17421 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17422 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17424 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17425 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17426 if (NeedsBitcast) {
17427 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17428 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17430 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17431 if (VT != And.getValueType())
17432 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17437 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17438 SDNode *Node = Op.getNode();
17440 EVT T = Node->getValueType(0);
17441 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17442 DAG.getConstant(0, dl, T), Node->getOperand(2));
17443 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17444 cast<AtomicSDNode>(Node)->getMemoryVT(),
17445 Node->getOperand(0),
17446 Node->getOperand(1), negOp,
17447 cast<AtomicSDNode>(Node)->getMemOperand(),
17448 cast<AtomicSDNode>(Node)->getOrdering(),
17449 cast<AtomicSDNode>(Node)->getSynchScope());
17452 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17453 SDNode *Node = Op.getNode();
17455 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17457 // Convert seq_cst store -> xchg
17458 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17459 // FIXME: On 32-bit, store -> fist or movq would be more efficient
17460 // (The only way to get a 16-byte store is cmpxchg16b)
17461 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17462 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17463 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17464 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17465 cast<AtomicSDNode>(Node)->getMemoryVT(),
17466 Node->getOperand(0),
17467 Node->getOperand(1), Node->getOperand(2),
17468 cast<AtomicSDNode>(Node)->getMemOperand(),
17469 cast<AtomicSDNode>(Node)->getOrdering(),
17470 cast<AtomicSDNode>(Node)->getSynchScope());
17471 return Swap.getValue(1);
17473 // Other atomic stores have a simple pattern.
17477 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17478 EVT VT = Op.getNode()->getSimpleValueType(0);
17480 // Let legalize expand this if it isn't a legal type yet.
17481 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17484 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17487 bool ExtraOp = false;
17488 switch (Op.getOpcode()) {
17489 default: llvm_unreachable("Invalid code");
17490 case ISD::ADDC: Opc = X86ISD::ADD; break;
17491 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17492 case ISD::SUBC: Opc = X86ISD::SUB; break;
17493 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17497 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17499 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17500 Op.getOperand(1), Op.getOperand(2));
17503 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17504 SelectionDAG &DAG) {
17505 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17507 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17508 // which returns the values as { float, float } (in XMM0) or
17509 // { double, double } (which is returned in XMM0, XMM1).
17511 SDValue Arg = Op.getOperand(0);
17512 EVT ArgVT = Arg.getValueType();
17513 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17515 TargetLowering::ArgListTy Args;
17516 TargetLowering::ArgListEntry Entry;
17520 Entry.isSExt = false;
17521 Entry.isZExt = false;
17522 Args.push_back(Entry);
17524 bool isF64 = ArgVT == MVT::f64;
17525 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17526 // the small struct {f32, f32} is returned in (eax, edx). For f64,
17527 // the results are returned via SRet in memory.
17528 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
17529 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17530 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17532 Type *RetTy = isF64
17533 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17534 : (Type*)VectorType::get(ArgTy, 4);
17536 TargetLowering::CallLoweringInfo CLI(DAG);
17537 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17538 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17540 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17543 // Returned in xmm0 and xmm1.
17544 return CallResult.first;
17546 // Returned in bits 0:31 and 32:64 xmm0.
17547 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17548 CallResult.first, DAG.getIntPtrConstant(0, dl));
17549 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17550 CallResult.first, DAG.getIntPtrConstant(1, dl));
17551 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17552 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17555 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17556 SelectionDAG &DAG) {
17557 assert(Subtarget->hasAVX512() &&
17558 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17560 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17561 EVT VT = N->getValue().getValueType();
17562 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17565 // X86 scatter kills mask register, so its type should be added to
17566 // the list of return values
17567 if (N->getNumValues() == 1) {
17568 SDValue Index = N->getIndex();
17569 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17570 !Index.getValueType().is512BitVector())
17571 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17573 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17574 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17575 N->getOperand(3), Index };
17577 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17578 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17579 return SDValue(NewScatter.getNode(), 0);
17584 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17585 SelectionDAG &DAG) {
17586 assert(Subtarget->hasAVX512() &&
17587 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17589 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17590 EVT VT = Op.getValueType();
17591 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17594 SDValue Index = N->getIndex();
17595 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17596 !Index.getValueType().is512BitVector()) {
17597 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17598 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17599 N->getOperand(3), Index };
17600 DAG.UpdateNodeOperands(N, Ops);
17605 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17606 SelectionDAG &DAG) const {
17607 // TODO: Eventually, the lowering of these nodes should be informed by or
17608 // deferred to the GC strategy for the function in which they appear. For
17609 // now, however, they must be lowered to something. Since they are logically
17610 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17611 // require special handling for these nodes), lower them as literal NOOPs for
17613 SmallVector<SDValue, 2> Ops;
17615 Ops.push_back(Op.getOperand(0));
17616 if (Op->getGluedNode())
17617 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17620 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17621 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17626 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17627 SelectionDAG &DAG) const {
17628 // TODO: Eventually, the lowering of these nodes should be informed by or
17629 // deferred to the GC strategy for the function in which they appear. For
17630 // now, however, they must be lowered to something. Since they are logically
17631 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17632 // require special handling for these nodes), lower them as literal NOOPs for
17634 SmallVector<SDValue, 2> Ops;
17636 Ops.push_back(Op.getOperand(0));
17637 if (Op->getGluedNode())
17638 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17641 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17642 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17647 /// LowerOperation - Provide custom lowering hooks for some operations.
17649 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17650 switch (Op.getOpcode()) {
17651 default: llvm_unreachable("Should not custom lower this!");
17652 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17653 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17654 return LowerCMP_SWAP(Op, Subtarget, DAG);
17655 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
17656 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
17657 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
17658 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
17659 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17660 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
17661 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17662 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17663 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17664 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17665 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17666 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17667 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17668 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17669 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17670 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17671 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17672 case ISD::SHL_PARTS:
17673 case ISD::SRA_PARTS:
17674 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17675 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17676 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17677 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17678 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17679 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17680 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17681 case ISD::SIGN_EXTEND_VECTOR_INREG:
17682 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
17683 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17684 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17685 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17686 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17688 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17689 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17690 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17691 case ISD::SETCC: return LowerSETCC(Op, DAG);
17692 case ISD::SELECT: return LowerSELECT(Op, DAG);
17693 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17694 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17695 case ISD::VASTART: return LowerVASTART(Op, DAG);
17696 case ISD::VAARG: return LowerVAARG(Op, DAG);
17697 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17698 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17699 case ISD::INTRINSIC_VOID:
17700 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17701 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17702 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17703 case ISD::FRAME_TO_ARGS_OFFSET:
17704 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17705 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17706 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17707 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17708 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17709 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17710 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17711 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17712 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17713 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17714 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17715 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17716 case ISD::UMUL_LOHI:
17717 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17720 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17726 case ISD::UMULO: return LowerXALUO(Op, DAG);
17727 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17728 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17732 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17733 case ISD::ADD: return LowerADD(Op, DAG);
17734 case ISD::SUB: return LowerSUB(Op, DAG);
17735 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17736 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
17737 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
17738 case ISD::GC_TRANSITION_START:
17739 return LowerGC_TRANSITION_START(Op, DAG);
17740 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
17744 /// ReplaceNodeResults - Replace a node with an illegal result type
17745 /// with a new node built out of custom code.
17746 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17747 SmallVectorImpl<SDValue>&Results,
17748 SelectionDAG &DAG) const {
17750 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17751 switch (N->getOpcode()) {
17753 llvm_unreachable("Do not know how to custom type legalize this operation!");
17754 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17755 case X86ISD::FMINC:
17757 case X86ISD::FMAXC:
17758 case X86ISD::FMAX: {
17759 EVT VT = N->getValueType(0);
17760 if (VT != MVT::v2f32)
17761 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17762 SDValue UNDEF = DAG.getUNDEF(VT);
17763 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17764 N->getOperand(0), UNDEF);
17765 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17766 N->getOperand(1), UNDEF);
17767 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17770 case ISD::SIGN_EXTEND_INREG:
17775 // We don't want to expand or promote these.
17782 case ISD::UDIVREM: {
17783 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17784 Results.push_back(V);
17787 case ISD::FP_TO_SINT:
17788 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
17789 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17790 if (N->getOperand(0).getValueType() == MVT::f16)
17793 case ISD::FP_TO_UINT: {
17794 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17796 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17799 std::pair<SDValue,SDValue> Vals =
17800 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17801 SDValue FIST = Vals.first, StackSlot = Vals.second;
17802 if (FIST.getNode()) {
17803 EVT VT = N->getValueType(0);
17804 // Return a load from the stack slot.
17805 if (StackSlot.getNode())
17806 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17807 MachinePointerInfo(),
17808 false, false, false, 0));
17810 Results.push_back(FIST);
17814 case ISD::UINT_TO_FP: {
17815 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17816 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17817 N->getValueType(0) != MVT::v2f32)
17819 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17821 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17823 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17824 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17825 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17826 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17827 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17828 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17831 case ISD::FP_ROUND: {
17832 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17834 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17835 Results.push_back(V);
17838 case ISD::FP_EXTEND: {
17839 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17840 // No other ValueType for FP_EXTEND should reach this point.
17841 assert(N->getValueType(0) == MVT::v2f32 &&
17842 "Do not know how to legalize this Node");
17845 case ISD::INTRINSIC_W_CHAIN: {
17846 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17848 default : llvm_unreachable("Do not know how to custom type "
17849 "legalize this intrinsic operation!");
17850 case Intrinsic::x86_rdtsc:
17851 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17853 case Intrinsic::x86_rdtscp:
17854 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17856 case Intrinsic::x86_rdpmc:
17857 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17860 case ISD::READCYCLECOUNTER: {
17861 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17864 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17865 EVT T = N->getValueType(0);
17866 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17867 bool Regs64bit = T == MVT::i128;
17868 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17869 SDValue cpInL, cpInH;
17870 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17871 DAG.getConstant(0, dl, HalfT));
17872 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17873 DAG.getConstant(1, dl, HalfT));
17874 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17875 Regs64bit ? X86::RAX : X86::EAX,
17877 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17878 Regs64bit ? X86::RDX : X86::EDX,
17879 cpInH, cpInL.getValue(1));
17880 SDValue swapInL, swapInH;
17881 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17882 DAG.getConstant(0, dl, HalfT));
17883 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17884 DAG.getConstant(1, dl, HalfT));
17885 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17886 Regs64bit ? X86::RBX : X86::EBX,
17887 swapInL, cpInH.getValue(1));
17888 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17889 Regs64bit ? X86::RCX : X86::ECX,
17890 swapInH, swapInL.getValue(1));
17891 SDValue Ops[] = { swapInH.getValue(0),
17893 swapInH.getValue(1) };
17894 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17895 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17896 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17897 X86ISD::LCMPXCHG8_DAG;
17898 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17899 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17900 Regs64bit ? X86::RAX : X86::EAX,
17901 HalfT, Result.getValue(1));
17902 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17903 Regs64bit ? X86::RDX : X86::EDX,
17904 HalfT, cpOutL.getValue(2));
17905 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17907 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17908 MVT::i32, cpOutH.getValue(2));
17910 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17911 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17912 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17914 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17915 Results.push_back(Success);
17916 Results.push_back(EFLAGS.getValue(1));
17919 case ISD::ATOMIC_SWAP:
17920 case ISD::ATOMIC_LOAD_ADD:
17921 case ISD::ATOMIC_LOAD_SUB:
17922 case ISD::ATOMIC_LOAD_AND:
17923 case ISD::ATOMIC_LOAD_OR:
17924 case ISD::ATOMIC_LOAD_XOR:
17925 case ISD::ATOMIC_LOAD_NAND:
17926 case ISD::ATOMIC_LOAD_MIN:
17927 case ISD::ATOMIC_LOAD_MAX:
17928 case ISD::ATOMIC_LOAD_UMIN:
17929 case ISD::ATOMIC_LOAD_UMAX:
17930 case ISD::ATOMIC_LOAD: {
17931 // Delegate to generic TypeLegalization. Situations we can really handle
17932 // should have already been dealt with by AtomicExpandPass.cpp.
17935 case ISD::BITCAST: {
17936 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17937 EVT DstVT = N->getValueType(0);
17938 EVT SrcVT = N->getOperand(0)->getValueType(0);
17940 if (SrcVT != MVT::f64 ||
17941 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17944 unsigned NumElts = DstVT.getVectorNumElements();
17945 EVT SVT = DstVT.getVectorElementType();
17946 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17947 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17948 MVT::v2f64, N->getOperand(0));
17949 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17951 if (ExperimentalVectorWideningLegalization) {
17952 // If we are legalizing vectors by widening, we already have the desired
17953 // legal vector type, just return it.
17954 Results.push_back(ToVecInt);
17958 SmallVector<SDValue, 8> Elts;
17959 for (unsigned i = 0, e = NumElts; i != e; ++i)
17960 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17961 ToVecInt, DAG.getIntPtrConstant(i, dl)));
17963 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17968 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17969 switch ((X86ISD::NodeType)Opcode) {
17970 case X86ISD::FIRST_NUMBER: break;
17971 case X86ISD::BSF: return "X86ISD::BSF";
17972 case X86ISD::BSR: return "X86ISD::BSR";
17973 case X86ISD::SHLD: return "X86ISD::SHLD";
17974 case X86ISD::SHRD: return "X86ISD::SHRD";
17975 case X86ISD::FAND: return "X86ISD::FAND";
17976 case X86ISD::FANDN: return "X86ISD::FANDN";
17977 case X86ISD::FOR: return "X86ISD::FOR";
17978 case X86ISD::FXOR: return "X86ISD::FXOR";
17979 case X86ISD::FSRL: return "X86ISD::FSRL";
17980 case X86ISD::FILD: return "X86ISD::FILD";
17981 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17982 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17983 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17984 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17985 case X86ISD::FLD: return "X86ISD::FLD";
17986 case X86ISD::FST: return "X86ISD::FST";
17987 case X86ISD::CALL: return "X86ISD::CALL";
17988 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17989 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17990 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17991 case X86ISD::BT: return "X86ISD::BT";
17992 case X86ISD::CMP: return "X86ISD::CMP";
17993 case X86ISD::COMI: return "X86ISD::COMI";
17994 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17995 case X86ISD::CMPM: return "X86ISD::CMPM";
17996 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17997 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
17998 case X86ISD::SETCC: return "X86ISD::SETCC";
17999 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
18000 case X86ISD::FSETCC: return "X86ISD::FSETCC";
18001 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
18002 case X86ISD::CMOV: return "X86ISD::CMOV";
18003 case X86ISD::BRCOND: return "X86ISD::BRCOND";
18004 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
18005 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
18006 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
18007 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
18008 case X86ISD::Wrapper: return "X86ISD::Wrapper";
18009 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
18010 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
18011 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
18012 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
18013 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
18014 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
18015 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
18016 case X86ISD::PINSRB: return "X86ISD::PINSRB";
18017 case X86ISD::PINSRW: return "X86ISD::PINSRW";
18018 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
18019 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
18020 case X86ISD::ANDNP: return "X86ISD::ANDNP";
18021 case X86ISD::PSIGN: return "X86ISD::PSIGN";
18022 case X86ISD::BLENDI: return "X86ISD::BLENDI";
18023 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
18024 case X86ISD::ADDUS: return "X86ISD::ADDUS";
18025 case X86ISD::SUBUS: return "X86ISD::SUBUS";
18026 case X86ISD::HADD: return "X86ISD::HADD";
18027 case X86ISD::HSUB: return "X86ISD::HSUB";
18028 case X86ISD::FHADD: return "X86ISD::FHADD";
18029 case X86ISD::FHSUB: return "X86ISD::FHSUB";
18030 case X86ISD::UMAX: return "X86ISD::UMAX";
18031 case X86ISD::UMIN: return "X86ISD::UMIN";
18032 case X86ISD::SMAX: return "X86ISD::SMAX";
18033 case X86ISD::SMIN: return "X86ISD::SMIN";
18034 case X86ISD::FMAX: return "X86ISD::FMAX";
18035 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
18036 case X86ISD::FMIN: return "X86ISD::FMIN";
18037 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
18038 case X86ISD::FMAXC: return "X86ISD::FMAXC";
18039 case X86ISD::FMINC: return "X86ISD::FMINC";
18040 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
18041 case X86ISD::FRCP: return "X86ISD::FRCP";
18042 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
18043 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
18044 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
18045 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
18046 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
18047 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
18048 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
18049 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
18050 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
18051 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
18052 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
18053 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
18054 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
18055 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
18056 case X86ISD::VZEXT: return "X86ISD::VZEXT";
18057 case X86ISD::VSEXT: return "X86ISD::VSEXT";
18058 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
18059 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
18060 case X86ISD::VINSERT: return "X86ISD::VINSERT";
18061 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
18062 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
18063 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
18064 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
18065 case X86ISD::VSHL: return "X86ISD::VSHL";
18066 case X86ISD::VSRL: return "X86ISD::VSRL";
18067 case X86ISD::VSRA: return "X86ISD::VSRA";
18068 case X86ISD::VSHLI: return "X86ISD::VSHLI";
18069 case X86ISD::VSRLI: return "X86ISD::VSRLI";
18070 case X86ISD::VSRAI: return "X86ISD::VSRAI";
18071 case X86ISD::CMPP: return "X86ISD::CMPP";
18072 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
18073 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
18074 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
18075 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
18076 case X86ISD::ADD: return "X86ISD::ADD";
18077 case X86ISD::SUB: return "X86ISD::SUB";
18078 case X86ISD::ADC: return "X86ISD::ADC";
18079 case X86ISD::SBB: return "X86ISD::SBB";
18080 case X86ISD::SMUL: return "X86ISD::SMUL";
18081 case X86ISD::UMUL: return "X86ISD::UMUL";
18082 case X86ISD::SMUL8: return "X86ISD::SMUL8";
18083 case X86ISD::UMUL8: return "X86ISD::UMUL8";
18084 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18085 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18086 case X86ISD::INC: return "X86ISD::INC";
18087 case X86ISD::DEC: return "X86ISD::DEC";
18088 case X86ISD::OR: return "X86ISD::OR";
18089 case X86ISD::XOR: return "X86ISD::XOR";
18090 case X86ISD::AND: return "X86ISD::AND";
18091 case X86ISD::BEXTR: return "X86ISD::BEXTR";
18092 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
18093 case X86ISD::PTEST: return "X86ISD::PTEST";
18094 case X86ISD::TESTP: return "X86ISD::TESTP";
18095 case X86ISD::TESTM: return "X86ISD::TESTM";
18096 case X86ISD::TESTNM: return "X86ISD::TESTNM";
18097 case X86ISD::KORTEST: return "X86ISD::KORTEST";
18098 case X86ISD::PACKSS: return "X86ISD::PACKSS";
18099 case X86ISD::PACKUS: return "X86ISD::PACKUS";
18100 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
18101 case X86ISD::VALIGN: return "X86ISD::VALIGN";
18102 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
18103 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
18104 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
18105 case X86ISD::SHUFP: return "X86ISD::SHUFP";
18106 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
18107 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
18108 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
18109 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
18110 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
18111 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
18112 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
18113 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
18114 case X86ISD::MOVSD: return "X86ISD::MOVSD";
18115 case X86ISD::MOVSS: return "X86ISD::MOVSS";
18116 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
18117 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
18118 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
18119 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
18120 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
18121 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
18122 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
18123 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
18124 case X86ISD::VPERMV: return "X86ISD::VPERMV";
18125 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
18126 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
18127 case X86ISD::VPERMI: return "X86ISD::VPERMI";
18128 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
18129 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
18130 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18131 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
18132 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
18133 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
18134 case X86ISD::MFENCE: return "X86ISD::MFENCE";
18135 case X86ISD::SFENCE: return "X86ISD::SFENCE";
18136 case X86ISD::LFENCE: return "X86ISD::LFENCE";
18137 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
18138 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
18139 case X86ISD::SAHF: return "X86ISD::SAHF";
18140 case X86ISD::RDRAND: return "X86ISD::RDRAND";
18141 case X86ISD::RDSEED: return "X86ISD::RDSEED";
18142 case X86ISD::FMADD: return "X86ISD::FMADD";
18143 case X86ISD::FMSUB: return "X86ISD::FMSUB";
18144 case X86ISD::FNMADD: return "X86ISD::FNMADD";
18145 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
18146 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
18147 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
18148 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
18149 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
18150 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
18151 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
18152 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
18153 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
18154 case X86ISD::RNDSCALE: return "X86ISD::RNDSCALE";
18155 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
18156 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
18157 case X86ISD::XTEST: return "X86ISD::XTEST";
18158 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
18159 case X86ISD::EXPAND: return "X86ISD::EXPAND";
18160 case X86ISD::SELECT: return "X86ISD::SELECT";
18161 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
18162 case X86ISD::RCP28: return "X86ISD::RCP28";
18163 case X86ISD::EXP2: return "X86ISD::EXP2";
18164 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
18165 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
18166 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
18167 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
18168 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
18169 case X86ISD::ADDS: return "X86ISD::ADDS";
18170 case X86ISD::SUBS: return "X86ISD::SUBS";
18175 // isLegalAddressingMode - Return true if the addressing mode represented
18176 // by AM is legal for this target, for a load/store of the specified type.
18177 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18179 // X86 supports extremely general addressing modes.
18180 CodeModel::Model M = getTargetMachine().getCodeModel();
18181 Reloc::Model R = getTargetMachine().getRelocationModel();
18183 // X86 allows a sign-extended 32-bit immediate field as a displacement.
18184 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18189 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18191 // If a reference to this global requires an extra load, we can't fold it.
18192 if (isGlobalStubReference(GVFlags))
18195 // If BaseGV requires a register for the PIC base, we cannot also have a
18196 // BaseReg specified.
18197 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18200 // If lower 4G is not available, then we must use rip-relative addressing.
18201 if ((M != CodeModel::Small || R != Reloc::Static) &&
18202 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18206 switch (AM.Scale) {
18212 // These scales always work.
18217 // These scales are formed with basereg+scalereg. Only accept if there is
18222 default: // Other stuff never works.
18229 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18230 unsigned Bits = Ty->getScalarSizeInBits();
18232 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18233 // particularly cheaper than those without.
18237 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18238 // variable shifts just as cheap as scalar ones.
18239 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18242 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18243 // fully general vector.
18247 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18248 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18250 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18251 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18252 return NumBits1 > NumBits2;
18255 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18256 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18259 if (!isTypeLegal(EVT::getEVT(Ty1)))
18262 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18264 // Assuming the caller doesn't have a zeroext or signext return parameter,
18265 // truncation all the way down to i1 is valid.
18269 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18270 return isInt<32>(Imm);
18273 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18274 // Can also use sub to handle negated immediates.
18275 return isInt<32>(Imm);
18278 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18279 if (!VT1.isInteger() || !VT2.isInteger())
18281 unsigned NumBits1 = VT1.getSizeInBits();
18282 unsigned NumBits2 = VT2.getSizeInBits();
18283 return NumBits1 > NumBits2;
18286 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18287 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18288 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18291 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18292 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18293 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18296 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18297 EVT VT1 = Val.getValueType();
18298 if (isZExtFree(VT1, VT2))
18301 if (Val.getOpcode() != ISD::LOAD)
18304 if (!VT1.isSimple() || !VT1.isInteger() ||
18305 !VT2.isSimple() || !VT2.isInteger())
18308 switch (VT1.getSimpleVT().SimpleTy) {
18313 // X86 has 8, 16, and 32-bit zero-extending loads.
18320 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18323 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18324 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18327 VT = VT.getScalarType();
18329 if (!VT.isSimple())
18332 switch (VT.getSimpleVT().SimpleTy) {
18343 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18344 // i16 instructions are longer (0x66 prefix) and potentially slower.
18345 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18348 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18349 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18350 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18351 /// are assumed to be legal.
18353 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18355 if (!VT.isSimple())
18358 // Not for i1 vectors
18359 if (VT.getScalarType() == MVT::i1)
18362 // Very little shuffling can be done for 64-bit vectors right now.
18363 if (VT.getSizeInBits() == 64)
18366 // We only care that the types being shuffled are legal. The lowering can
18367 // handle any possible shuffle mask that results.
18368 return isTypeLegal(VT.getSimpleVT());
18372 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18374 // Just delegate to the generic legality, clear masks aren't special.
18375 return isShuffleMaskLegal(Mask, VT);
18378 //===----------------------------------------------------------------------===//
18379 // X86 Scheduler Hooks
18380 //===----------------------------------------------------------------------===//
18382 /// Utility function to emit xbegin specifying the start of an RTM region.
18383 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18384 const TargetInstrInfo *TII) {
18385 DebugLoc DL = MI->getDebugLoc();
18387 const BasicBlock *BB = MBB->getBasicBlock();
18388 MachineFunction::iterator I = MBB;
18391 // For the v = xbegin(), we generate
18402 MachineBasicBlock *thisMBB = MBB;
18403 MachineFunction *MF = MBB->getParent();
18404 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18405 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18406 MF->insert(I, mainMBB);
18407 MF->insert(I, sinkMBB);
18409 // Transfer the remainder of BB and its successor edges to sinkMBB.
18410 sinkMBB->splice(sinkMBB->begin(), MBB,
18411 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18412 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18416 // # fallthrough to mainMBB
18417 // # abortion to sinkMBB
18418 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18419 thisMBB->addSuccessor(mainMBB);
18420 thisMBB->addSuccessor(sinkMBB);
18424 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18425 mainMBB->addSuccessor(sinkMBB);
18428 // EAX is live into the sinkMBB
18429 sinkMBB->addLiveIn(X86::EAX);
18430 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18431 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18434 MI->eraseFromParent();
18438 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18439 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18440 // in the .td file.
18441 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18442 const TargetInstrInfo *TII) {
18444 switch (MI->getOpcode()) {
18445 default: llvm_unreachable("illegal opcode!");
18446 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
18447 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18448 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
18449 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18450 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
18451 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18452 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
18453 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18456 DebugLoc dl = MI->getDebugLoc();
18457 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18459 unsigned NumArgs = MI->getNumOperands();
18460 for (unsigned i = 1; i < NumArgs; ++i) {
18461 MachineOperand &Op = MI->getOperand(i);
18462 if (!(Op.isReg() && Op.isImplicit()))
18463 MIB.addOperand(Op);
18465 if (MI->hasOneMemOperand())
18466 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18468 BuildMI(*BB, MI, dl,
18469 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18470 .addReg(X86::XMM0);
18472 MI->eraseFromParent();
18476 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18477 // defs in an instruction pattern
18478 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18479 const TargetInstrInfo *TII) {
18481 switch (MI->getOpcode()) {
18482 default: llvm_unreachable("illegal opcode!");
18483 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
18484 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18485 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
18486 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18487 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
18488 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18489 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
18490 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18493 DebugLoc dl = MI->getDebugLoc();
18494 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18496 unsigned NumArgs = MI->getNumOperands(); // remove the results
18497 for (unsigned i = 1; i < NumArgs; ++i) {
18498 MachineOperand &Op = MI->getOperand(i);
18499 if (!(Op.isReg() && Op.isImplicit()))
18500 MIB.addOperand(Op);
18502 if (MI->hasOneMemOperand())
18503 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18505 BuildMI(*BB, MI, dl,
18506 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18509 MI->eraseFromParent();
18513 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18514 const X86Subtarget *Subtarget) {
18515 DebugLoc dl = MI->getDebugLoc();
18516 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18517 // Address into RAX/EAX, other two args into ECX, EDX.
18518 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18519 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18520 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18521 for (int i = 0; i < X86::AddrNumOperands; ++i)
18522 MIB.addOperand(MI->getOperand(i));
18524 unsigned ValOps = X86::AddrNumOperands;
18525 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18526 .addReg(MI->getOperand(ValOps).getReg());
18527 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18528 .addReg(MI->getOperand(ValOps+1).getReg());
18530 // The instruction doesn't actually take any operands though.
18531 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18533 MI->eraseFromParent(); // The pseudo is gone now.
18537 MachineBasicBlock *
18538 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18539 MachineBasicBlock *MBB) const {
18540 // Emit va_arg instruction on X86-64.
18542 // Operands to this pseudo-instruction:
18543 // 0 ) Output : destination address (reg)
18544 // 1-5) Input : va_list address (addr, i64mem)
18545 // 6 ) ArgSize : Size (in bytes) of vararg type
18546 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18547 // 8 ) Align : Alignment of type
18548 // 9 ) EFLAGS (implicit-def)
18550 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18551 static_assert(X86::AddrNumOperands == 5,
18552 "VAARG_64 assumes 5 address operands");
18554 unsigned DestReg = MI->getOperand(0).getReg();
18555 MachineOperand &Base = MI->getOperand(1);
18556 MachineOperand &Scale = MI->getOperand(2);
18557 MachineOperand &Index = MI->getOperand(3);
18558 MachineOperand &Disp = MI->getOperand(4);
18559 MachineOperand &Segment = MI->getOperand(5);
18560 unsigned ArgSize = MI->getOperand(6).getImm();
18561 unsigned ArgMode = MI->getOperand(7).getImm();
18562 unsigned Align = MI->getOperand(8).getImm();
18564 // Memory Reference
18565 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18566 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18567 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18569 // Machine Information
18570 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18571 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18572 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18573 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18574 DebugLoc DL = MI->getDebugLoc();
18576 // struct va_list {
18579 // i64 overflow_area (address)
18580 // i64 reg_save_area (address)
18582 // sizeof(va_list) = 24
18583 // alignment(va_list) = 8
18585 unsigned TotalNumIntRegs = 6;
18586 unsigned TotalNumXMMRegs = 8;
18587 bool UseGPOffset = (ArgMode == 1);
18588 bool UseFPOffset = (ArgMode == 2);
18589 unsigned MaxOffset = TotalNumIntRegs * 8 +
18590 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18592 /* Align ArgSize to a multiple of 8 */
18593 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18594 bool NeedsAlign = (Align > 8);
18596 MachineBasicBlock *thisMBB = MBB;
18597 MachineBasicBlock *overflowMBB;
18598 MachineBasicBlock *offsetMBB;
18599 MachineBasicBlock *endMBB;
18601 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
18602 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
18603 unsigned OffsetReg = 0;
18605 if (!UseGPOffset && !UseFPOffset) {
18606 // If we only pull from the overflow region, we don't create a branch.
18607 // We don't need to alter control flow.
18608 OffsetDestReg = 0; // unused
18609 OverflowDestReg = DestReg;
18611 offsetMBB = nullptr;
18612 overflowMBB = thisMBB;
18615 // First emit code to check if gp_offset (or fp_offset) is below the bound.
18616 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18617 // If not, pull from overflow_area. (branch to overflowMBB)
18622 // offsetMBB overflowMBB
18627 // Registers for the PHI in endMBB
18628 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18629 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18631 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18632 MachineFunction *MF = MBB->getParent();
18633 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18634 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18635 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18637 MachineFunction::iterator MBBIter = MBB;
18640 // Insert the new basic blocks
18641 MF->insert(MBBIter, offsetMBB);
18642 MF->insert(MBBIter, overflowMBB);
18643 MF->insert(MBBIter, endMBB);
18645 // Transfer the remainder of MBB and its successor edges to endMBB.
18646 endMBB->splice(endMBB->begin(), thisMBB,
18647 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18648 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18650 // Make offsetMBB and overflowMBB successors of thisMBB
18651 thisMBB->addSuccessor(offsetMBB);
18652 thisMBB->addSuccessor(overflowMBB);
18654 // endMBB is a successor of both offsetMBB and overflowMBB
18655 offsetMBB->addSuccessor(endMBB);
18656 overflowMBB->addSuccessor(endMBB);
18658 // Load the offset value into a register
18659 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18660 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18664 .addDisp(Disp, UseFPOffset ? 4 : 0)
18665 .addOperand(Segment)
18666 .setMemRefs(MMOBegin, MMOEnd);
18668 // Check if there is enough room left to pull this argument.
18669 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18671 .addImm(MaxOffset + 8 - ArgSizeA8);
18673 // Branch to "overflowMBB" if offset >= max
18674 // Fall through to "offsetMBB" otherwise
18675 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18676 .addMBB(overflowMBB);
18679 // In offsetMBB, emit code to use the reg_save_area.
18681 assert(OffsetReg != 0);
18683 // Read the reg_save_area address.
18684 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18685 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18690 .addOperand(Segment)
18691 .setMemRefs(MMOBegin, MMOEnd);
18693 // Zero-extend the offset
18694 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18695 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18698 .addImm(X86::sub_32bit);
18700 // Add the offset to the reg_save_area to get the final address.
18701 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18702 .addReg(OffsetReg64)
18703 .addReg(RegSaveReg);
18705 // Compute the offset for the next argument
18706 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18707 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18709 .addImm(UseFPOffset ? 16 : 8);
18711 // Store it back into the va_list.
18712 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18716 .addDisp(Disp, UseFPOffset ? 4 : 0)
18717 .addOperand(Segment)
18718 .addReg(NextOffsetReg)
18719 .setMemRefs(MMOBegin, MMOEnd);
18722 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18727 // Emit code to use overflow area
18730 // Load the overflow_area address into a register.
18731 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18732 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18737 .addOperand(Segment)
18738 .setMemRefs(MMOBegin, MMOEnd);
18740 // If we need to align it, do so. Otherwise, just copy the address
18741 // to OverflowDestReg.
18743 // Align the overflow address
18744 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18745 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18747 // aligned_addr = (addr + (align-1)) & ~(align-1)
18748 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18749 .addReg(OverflowAddrReg)
18752 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18754 .addImm(~(uint64_t)(Align-1));
18756 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18757 .addReg(OverflowAddrReg);
18760 // Compute the next overflow address after this argument.
18761 // (the overflow address should be kept 8-byte aligned)
18762 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18763 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18764 .addReg(OverflowDestReg)
18765 .addImm(ArgSizeA8);
18767 // Store the new overflow address.
18768 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18773 .addOperand(Segment)
18774 .addReg(NextAddrReg)
18775 .setMemRefs(MMOBegin, MMOEnd);
18777 // If we branched, emit the PHI to the front of endMBB.
18779 BuildMI(*endMBB, endMBB->begin(), DL,
18780 TII->get(X86::PHI), DestReg)
18781 .addReg(OffsetDestReg).addMBB(offsetMBB)
18782 .addReg(OverflowDestReg).addMBB(overflowMBB);
18785 // Erase the pseudo instruction
18786 MI->eraseFromParent();
18791 MachineBasicBlock *
18792 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18794 MachineBasicBlock *MBB) const {
18795 // Emit code to save XMM registers to the stack. The ABI says that the
18796 // number of registers to save is given in %al, so it's theoretically
18797 // possible to do an indirect jump trick to avoid saving all of them,
18798 // however this code takes a simpler approach and just executes all
18799 // of the stores if %al is non-zero. It's less code, and it's probably
18800 // easier on the hardware branch predictor, and stores aren't all that
18801 // expensive anyway.
18803 // Create the new basic blocks. One block contains all the XMM stores,
18804 // and one block is the final destination regardless of whether any
18805 // stores were performed.
18806 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18807 MachineFunction *F = MBB->getParent();
18808 MachineFunction::iterator MBBIter = MBB;
18810 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18811 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18812 F->insert(MBBIter, XMMSaveMBB);
18813 F->insert(MBBIter, EndMBB);
18815 // Transfer the remainder of MBB and its successor edges to EndMBB.
18816 EndMBB->splice(EndMBB->begin(), MBB,
18817 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18818 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18820 // The original block will now fall through to the XMM save block.
18821 MBB->addSuccessor(XMMSaveMBB);
18822 // The XMMSaveMBB will fall through to the end block.
18823 XMMSaveMBB->addSuccessor(EndMBB);
18825 // Now add the instructions.
18826 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18827 DebugLoc DL = MI->getDebugLoc();
18829 unsigned CountReg = MI->getOperand(0).getReg();
18830 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18831 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18833 if (!Subtarget->isTargetWin64()) {
18834 // If %al is 0, branch around the XMM save block.
18835 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18836 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18837 MBB->addSuccessor(EndMBB);
18840 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18841 // that was just emitted, but clearly shouldn't be "saved".
18842 assert((MI->getNumOperands() <= 3 ||
18843 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18844 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18845 && "Expected last argument to be EFLAGS");
18846 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18847 // In the XMM save block, save all the XMM argument registers.
18848 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18849 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18850 MachineMemOperand *MMO =
18851 F->getMachineMemOperand(
18852 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18853 MachineMemOperand::MOStore,
18854 /*Size=*/16, /*Align=*/16);
18855 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18856 .addFrameIndex(RegSaveFrameIndex)
18857 .addImm(/*Scale=*/1)
18858 .addReg(/*IndexReg=*/0)
18859 .addImm(/*Disp=*/Offset)
18860 .addReg(/*Segment=*/0)
18861 .addReg(MI->getOperand(i).getReg())
18862 .addMemOperand(MMO);
18865 MI->eraseFromParent(); // The pseudo instruction is gone now.
18870 // The EFLAGS operand of SelectItr might be missing a kill marker
18871 // because there were multiple uses of EFLAGS, and ISel didn't know
18872 // which to mark. Figure out whether SelectItr should have had a
18873 // kill marker, and set it if it should. Returns the correct kill
18875 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18876 MachineBasicBlock* BB,
18877 const TargetRegisterInfo* TRI) {
18878 // Scan forward through BB for a use/def of EFLAGS.
18879 MachineBasicBlock::iterator miI(std::next(SelectItr));
18880 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18881 const MachineInstr& mi = *miI;
18882 if (mi.readsRegister(X86::EFLAGS))
18884 if (mi.definesRegister(X86::EFLAGS))
18885 break; // Should have kill-flag - update below.
18888 // If we hit the end of the block, check whether EFLAGS is live into a
18890 if (miI == BB->end()) {
18891 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18892 sEnd = BB->succ_end();
18893 sItr != sEnd; ++sItr) {
18894 MachineBasicBlock* succ = *sItr;
18895 if (succ->isLiveIn(X86::EFLAGS))
18900 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18901 // out. SelectMI should have a kill flag on EFLAGS.
18902 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18906 MachineBasicBlock *
18907 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18908 MachineBasicBlock *BB) const {
18909 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18910 DebugLoc DL = MI->getDebugLoc();
18912 // To "insert" a SELECT_CC instruction, we actually have to insert the
18913 // diamond control-flow pattern. The incoming instruction knows the
18914 // destination vreg to set, the condition code register to branch on, the
18915 // true/false values to select between, and a branch opcode to use.
18916 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18917 MachineFunction::iterator It = BB;
18923 // cmpTY ccX, r1, r2
18925 // fallthrough --> copy0MBB
18926 MachineBasicBlock *thisMBB = BB;
18927 MachineFunction *F = BB->getParent();
18929 // We also lower double CMOVs:
18930 // (CMOV (CMOV F, T, cc1), T, cc2)
18931 // to two successives branches. For that, we look for another CMOV as the
18932 // following instruction.
18934 // Without this, we would add a PHI between the two jumps, which ends up
18935 // creating a few copies all around. For instance, for
18937 // (sitofp (zext (fcmp une)))
18939 // we would generate:
18941 // ucomiss %xmm1, %xmm0
18942 // movss <1.0f>, %xmm0
18943 // movaps %xmm0, %xmm1
18945 // xorps %xmm1, %xmm1
18948 // movaps %xmm1, %xmm0
18952 // because this custom-inserter would have generated:
18964 // A: X = ...; Y = ...
18966 // C: Z = PHI [X, A], [Y, B]
18968 // E: PHI [X, C], [Z, D]
18970 // If we lower both CMOVs in a single step, we can instead generate:
18982 // A: X = ...; Y = ...
18984 // E: PHI [X, A], [X, C], [Y, D]
18986 // Which, in our sitofp/fcmp example, gives us something like:
18988 // ucomiss %xmm1, %xmm0
18989 // movss <1.0f>, %xmm0
18992 // xorps %xmm0, %xmm0
18996 MachineInstr *NextCMOV = nullptr;
18997 MachineBasicBlock::iterator NextMIIt =
18998 std::next(MachineBasicBlock::iterator(MI));
18999 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19000 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19001 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19002 NextCMOV = &*NextMIIt;
19004 MachineBasicBlock *jcc1MBB = nullptr;
19006 // If we have a double CMOV, we lower it to two successive branches to
19007 // the same block. EFLAGS is used by both, so mark it as live in the second.
19009 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19010 F->insert(It, jcc1MBB);
19011 jcc1MBB->addLiveIn(X86::EFLAGS);
19014 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19015 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19016 F->insert(It, copy0MBB);
19017 F->insert(It, sinkMBB);
19019 // If the EFLAGS register isn't dead in the terminator, then claim that it's
19020 // live into the sink and copy blocks.
19021 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19023 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19024 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19025 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19026 copy0MBB->addLiveIn(X86::EFLAGS);
19027 sinkMBB->addLiveIn(X86::EFLAGS);
19030 // Transfer the remainder of BB and its successor edges to sinkMBB.
19031 sinkMBB->splice(sinkMBB->begin(), BB,
19032 std::next(MachineBasicBlock::iterator(MI)), BB->end());
19033 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19035 // Add the true and fallthrough blocks as its successors.
19037 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19038 BB->addSuccessor(jcc1MBB);
19040 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19041 // jump to the sinkMBB.
19042 jcc1MBB->addSuccessor(copy0MBB);
19043 jcc1MBB->addSuccessor(sinkMBB);
19045 BB->addSuccessor(copy0MBB);
19048 // The true block target of the first (or only) branch is always sinkMBB.
19049 BB->addSuccessor(sinkMBB);
19051 // Create the conditional branch instruction.
19053 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19054 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19057 unsigned Opc2 = X86::GetCondBranchFromCond(
19058 (X86::CondCode)NextCMOV->getOperand(3).getImm());
19059 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19063 // %FalseValue = ...
19064 // # fallthrough to sinkMBB
19065 copy0MBB->addSuccessor(sinkMBB);
19068 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19070 MachineInstrBuilder MIB =
19071 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19072 MI->getOperand(0).getReg())
19073 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19074 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19076 // If we have a double CMOV, the second Jcc provides the same incoming
19077 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19079 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19080 // Copy the PHI result to the register defined by the second CMOV.
19081 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19082 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19083 .addReg(MI->getOperand(0).getReg());
19084 NextCMOV->eraseFromParent();
19087 MI->eraseFromParent(); // The pseudo instruction is gone now.
19091 MachineBasicBlock *
19092 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19093 MachineBasicBlock *BB) const {
19094 MachineFunction *MF = BB->getParent();
19095 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19096 DebugLoc DL = MI->getDebugLoc();
19097 const BasicBlock *LLVM_BB = BB->getBasicBlock();
19099 assert(MF->shouldSplitStack());
19101 const bool Is64Bit = Subtarget->is64Bit();
19102 const bool IsLP64 = Subtarget->isTarget64BitLP64();
19104 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19105 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19108 // ... [Till the alloca]
19109 // If stacklet is not large enough, jump to mallocMBB
19112 // Allocate by subtracting from RSP
19113 // Jump to continueMBB
19116 // Allocate by call to runtime
19120 // [rest of original BB]
19123 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19124 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19125 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19127 MachineRegisterInfo &MRI = MF->getRegInfo();
19128 const TargetRegisterClass *AddrRegClass =
19129 getRegClassFor(getPointerTy());
19131 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19132 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19133 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19134 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19135 sizeVReg = MI->getOperand(1).getReg(),
19136 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19138 MachineFunction::iterator MBBIter = BB;
19141 MF->insert(MBBIter, bumpMBB);
19142 MF->insert(MBBIter, mallocMBB);
19143 MF->insert(MBBIter, continueMBB);
19145 continueMBB->splice(continueMBB->begin(), BB,
19146 std::next(MachineBasicBlock::iterator(MI)), BB->end());
19147 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19149 // Add code to the main basic block to check if the stack limit has been hit,
19150 // and if so, jump to mallocMBB otherwise to bumpMBB.
19151 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19152 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19153 .addReg(tmpSPVReg).addReg(sizeVReg);
19154 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19155 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19156 .addReg(SPLimitVReg);
19157 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19159 // bumpMBB simply decreases the stack pointer, since we know the current
19160 // stacklet has enough space.
19161 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19162 .addReg(SPLimitVReg);
19163 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19164 .addReg(SPLimitVReg);
19165 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19167 // Calls into a routine in libgcc to allocate more space from the heap.
19168 const uint32_t *RegMask =
19169 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19171 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19173 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19174 .addExternalSymbol("__morestack_allocate_stack_space")
19175 .addRegMask(RegMask)
19176 .addReg(X86::RDI, RegState::Implicit)
19177 .addReg(X86::RAX, RegState::ImplicitDefine);
19178 } else if (Is64Bit) {
19179 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19181 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19182 .addExternalSymbol("__morestack_allocate_stack_space")
19183 .addRegMask(RegMask)
19184 .addReg(X86::EDI, RegState::Implicit)
19185 .addReg(X86::EAX, RegState::ImplicitDefine);
19187 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19189 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19190 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19191 .addExternalSymbol("__morestack_allocate_stack_space")
19192 .addRegMask(RegMask)
19193 .addReg(X86::EAX, RegState::ImplicitDefine);
19197 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19200 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19201 .addReg(IsLP64 ? X86::RAX : X86::EAX);
19202 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19204 // Set up the CFG correctly.
19205 BB->addSuccessor(bumpMBB);
19206 BB->addSuccessor(mallocMBB);
19207 mallocMBB->addSuccessor(continueMBB);
19208 bumpMBB->addSuccessor(continueMBB);
19210 // Take care of the PHI nodes.
19211 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19212 MI->getOperand(0).getReg())
19213 .addReg(mallocPtrVReg).addMBB(mallocMBB)
19214 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19216 // Delete the original pseudo instruction.
19217 MI->eraseFromParent();
19220 return continueMBB;
19223 MachineBasicBlock *
19224 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19225 MachineBasicBlock *BB) const {
19226 DebugLoc DL = MI->getDebugLoc();
19228 assert(!Subtarget->isTargetMachO());
19230 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19232 MI->eraseFromParent(); // The pseudo instruction is gone now.
19236 MachineBasicBlock *
19237 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19238 MachineBasicBlock *BB) const {
19239 // This is pretty easy. We're taking the value that we received from
19240 // our load from the relocation, sticking it in either RDI (x86-64)
19241 // or EAX and doing an indirect call. The return value will then
19242 // be in the normal return register.
19243 MachineFunction *F = BB->getParent();
19244 const X86InstrInfo *TII = Subtarget->getInstrInfo();
19245 DebugLoc DL = MI->getDebugLoc();
19247 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19248 assert(MI->getOperand(3).isGlobal() && "This should be a global");
19250 // Get a register mask for the lowered call.
19251 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19252 // proper register mask.
19253 const uint32_t *RegMask =
19254 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19255 if (Subtarget->is64Bit()) {
19256 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19257 TII->get(X86::MOV64rm), X86::RDI)
19259 .addImm(0).addReg(0)
19260 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19261 MI->getOperand(3).getTargetFlags())
19263 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19264 addDirectMem(MIB, X86::RDI);
19265 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19266 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19267 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19268 TII->get(X86::MOV32rm), X86::EAX)
19270 .addImm(0).addReg(0)
19271 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19272 MI->getOperand(3).getTargetFlags())
19274 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19275 addDirectMem(MIB, X86::EAX);
19276 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19278 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19279 TII->get(X86::MOV32rm), X86::EAX)
19280 .addReg(TII->getGlobalBaseReg(F))
19281 .addImm(0).addReg(0)
19282 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19283 MI->getOperand(3).getTargetFlags())
19285 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19286 addDirectMem(MIB, X86::EAX);
19287 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19290 MI->eraseFromParent(); // The pseudo instruction is gone now.
19294 MachineBasicBlock *
19295 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19296 MachineBasicBlock *MBB) const {
19297 DebugLoc DL = MI->getDebugLoc();
19298 MachineFunction *MF = MBB->getParent();
19299 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19300 MachineRegisterInfo &MRI = MF->getRegInfo();
19302 const BasicBlock *BB = MBB->getBasicBlock();
19303 MachineFunction::iterator I = MBB;
19306 // Memory Reference
19307 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19308 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19311 unsigned MemOpndSlot = 0;
19313 unsigned CurOp = 0;
19315 DstReg = MI->getOperand(CurOp++).getReg();
19316 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19317 assert(RC->hasType(MVT::i32) && "Invalid destination!");
19318 unsigned mainDstReg = MRI.createVirtualRegister(RC);
19319 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19321 MemOpndSlot = CurOp;
19323 MVT PVT = getPointerTy();
19324 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19325 "Invalid Pointer Size!");
19327 // For v = setjmp(buf), we generate
19330 // buf[LabelOffset] = restoreMBB
19331 // SjLjSetup restoreMBB
19337 // v = phi(main, restore)
19340 // if base pointer being used, load it from frame
19343 MachineBasicBlock *thisMBB = MBB;
19344 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19345 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19346 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19347 MF->insert(I, mainMBB);
19348 MF->insert(I, sinkMBB);
19349 MF->push_back(restoreMBB);
19351 MachineInstrBuilder MIB;
19353 // Transfer the remainder of BB and its successor edges to sinkMBB.
19354 sinkMBB->splice(sinkMBB->begin(), MBB,
19355 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19356 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19359 unsigned PtrStoreOpc = 0;
19360 unsigned LabelReg = 0;
19361 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19362 Reloc::Model RM = MF->getTarget().getRelocationModel();
19363 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19364 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19366 // Prepare IP either in reg or imm.
19367 if (!UseImmLabel) {
19368 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19369 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19370 LabelReg = MRI.createVirtualRegister(PtrRC);
19371 if (Subtarget->is64Bit()) {
19372 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19376 .addMBB(restoreMBB)
19379 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19380 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19381 .addReg(XII->getGlobalBaseReg(MF))
19384 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19388 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19390 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19391 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19392 if (i == X86::AddrDisp)
19393 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19395 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19398 MIB.addReg(LabelReg);
19400 MIB.addMBB(restoreMBB);
19401 MIB.setMemRefs(MMOBegin, MMOEnd);
19403 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19404 .addMBB(restoreMBB);
19406 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19407 MIB.addRegMask(RegInfo->getNoPreservedMask());
19408 thisMBB->addSuccessor(mainMBB);
19409 thisMBB->addSuccessor(restoreMBB);
19413 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19414 mainMBB->addSuccessor(sinkMBB);
19417 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19418 TII->get(X86::PHI), DstReg)
19419 .addReg(mainDstReg).addMBB(mainMBB)
19420 .addReg(restoreDstReg).addMBB(restoreMBB);
19423 if (RegInfo->hasBasePointer(*MF)) {
19424 const bool Uses64BitFramePtr =
19425 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19426 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19427 X86FI->setRestoreBasePointer(MF);
19428 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19429 unsigned BasePtr = RegInfo->getBaseRegister();
19430 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19431 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19432 FramePtr, true, X86FI->getRestoreBasePointerOffset())
19433 .setMIFlag(MachineInstr::FrameSetup);
19435 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19436 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19437 restoreMBB->addSuccessor(sinkMBB);
19439 MI->eraseFromParent();
19443 MachineBasicBlock *
19444 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19445 MachineBasicBlock *MBB) const {
19446 DebugLoc DL = MI->getDebugLoc();
19447 MachineFunction *MF = MBB->getParent();
19448 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19449 MachineRegisterInfo &MRI = MF->getRegInfo();
19451 // Memory Reference
19452 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19453 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19455 MVT PVT = getPointerTy();
19456 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19457 "Invalid Pointer Size!");
19459 const TargetRegisterClass *RC =
19460 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19461 unsigned Tmp = MRI.createVirtualRegister(RC);
19462 // Since FP is only updated here but NOT referenced, it's treated as GPR.
19463 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19464 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19465 unsigned SP = RegInfo->getStackRegister();
19467 MachineInstrBuilder MIB;
19469 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19470 const int64_t SPOffset = 2 * PVT.getStoreSize();
19472 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19473 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19476 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19477 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19478 MIB.addOperand(MI->getOperand(i));
19479 MIB.setMemRefs(MMOBegin, MMOEnd);
19481 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19482 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19483 if (i == X86::AddrDisp)
19484 MIB.addDisp(MI->getOperand(i), LabelOffset);
19486 MIB.addOperand(MI->getOperand(i));
19488 MIB.setMemRefs(MMOBegin, MMOEnd);
19490 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19491 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19492 if (i == X86::AddrDisp)
19493 MIB.addDisp(MI->getOperand(i), SPOffset);
19495 MIB.addOperand(MI->getOperand(i));
19497 MIB.setMemRefs(MMOBegin, MMOEnd);
19499 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19501 MI->eraseFromParent();
19505 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19506 // accumulator loops. Writing back to the accumulator allows the coalescer
19507 // to remove extra copies in the loop.
19508 MachineBasicBlock *
19509 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19510 MachineBasicBlock *MBB) const {
19511 MachineOperand &AddendOp = MI->getOperand(3);
19513 // Bail out early if the addend isn't a register - we can't switch these.
19514 if (!AddendOp.isReg())
19517 MachineFunction &MF = *MBB->getParent();
19518 MachineRegisterInfo &MRI = MF.getRegInfo();
19520 // Check whether the addend is defined by a PHI:
19521 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19522 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19523 if (!AddendDef.isPHI())
19526 // Look for the following pattern:
19528 // %addend = phi [%entry, 0], [%loop, %result]
19530 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19534 // %addend = phi [%entry, 0], [%loop, %result]
19536 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19538 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19539 assert(AddendDef.getOperand(i).isReg());
19540 MachineOperand PHISrcOp = AddendDef.getOperand(i);
19541 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19542 if (&PHISrcInst == MI) {
19543 // Found a matching instruction.
19544 unsigned NewFMAOpc = 0;
19545 switch (MI->getOpcode()) {
19546 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19547 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19548 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19549 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19550 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19551 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19552 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19553 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19554 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19555 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19556 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19557 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19558 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19559 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19560 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19561 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19562 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19563 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19564 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19565 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19567 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19568 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19569 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19570 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19571 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19572 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19573 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19574 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19575 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19576 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19577 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19578 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19579 default: llvm_unreachable("Unrecognized FMA variant.");
19582 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19583 MachineInstrBuilder MIB =
19584 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19585 .addOperand(MI->getOperand(0))
19586 .addOperand(MI->getOperand(3))
19587 .addOperand(MI->getOperand(2))
19588 .addOperand(MI->getOperand(1));
19589 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19590 MI->eraseFromParent();
19597 MachineBasicBlock *
19598 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19599 MachineBasicBlock *BB) const {
19600 switch (MI->getOpcode()) {
19601 default: llvm_unreachable("Unexpected instr type to insert");
19602 case X86::TAILJMPd64:
19603 case X86::TAILJMPr64:
19604 case X86::TAILJMPm64:
19605 case X86::TAILJMPd64_REX:
19606 case X86::TAILJMPr64_REX:
19607 case X86::TAILJMPm64_REX:
19608 llvm_unreachable("TAILJMP64 would not be touched here.");
19609 case X86::TCRETURNdi64:
19610 case X86::TCRETURNri64:
19611 case X86::TCRETURNmi64:
19613 case X86::WIN_ALLOCA:
19614 return EmitLoweredWinAlloca(MI, BB);
19615 case X86::SEG_ALLOCA_32:
19616 case X86::SEG_ALLOCA_64:
19617 return EmitLoweredSegAlloca(MI, BB);
19618 case X86::TLSCall_32:
19619 case X86::TLSCall_64:
19620 return EmitLoweredTLSCall(MI, BB);
19621 case X86::CMOV_GR8:
19622 case X86::CMOV_FR32:
19623 case X86::CMOV_FR64:
19624 case X86::CMOV_V4F32:
19625 case X86::CMOV_V2F64:
19626 case X86::CMOV_V2I64:
19627 case X86::CMOV_V8F32:
19628 case X86::CMOV_V4F64:
19629 case X86::CMOV_V4I64:
19630 case X86::CMOV_V16F32:
19631 case X86::CMOV_V8F64:
19632 case X86::CMOV_V8I64:
19633 case X86::CMOV_GR16:
19634 case X86::CMOV_GR32:
19635 case X86::CMOV_RFP32:
19636 case X86::CMOV_RFP64:
19637 case X86::CMOV_RFP80:
19638 case X86::CMOV_V8I1:
19639 case X86::CMOV_V16I1:
19640 case X86::CMOV_V32I1:
19641 case X86::CMOV_V64I1:
19642 return EmitLoweredSelect(MI, BB);
19644 case X86::FP32_TO_INT16_IN_MEM:
19645 case X86::FP32_TO_INT32_IN_MEM:
19646 case X86::FP32_TO_INT64_IN_MEM:
19647 case X86::FP64_TO_INT16_IN_MEM:
19648 case X86::FP64_TO_INT32_IN_MEM:
19649 case X86::FP64_TO_INT64_IN_MEM:
19650 case X86::FP80_TO_INT16_IN_MEM:
19651 case X86::FP80_TO_INT32_IN_MEM:
19652 case X86::FP80_TO_INT64_IN_MEM: {
19653 MachineFunction *F = BB->getParent();
19654 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19655 DebugLoc DL = MI->getDebugLoc();
19657 // Change the floating point control register to use "round towards zero"
19658 // mode when truncating to an integer value.
19659 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19660 addFrameReference(BuildMI(*BB, MI, DL,
19661 TII->get(X86::FNSTCW16m)), CWFrameIdx);
19663 // Load the old value of the high byte of the control word...
19665 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19666 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19669 // Set the high part to be round to zero...
19670 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19673 // Reload the modified control word now...
19674 addFrameReference(BuildMI(*BB, MI, DL,
19675 TII->get(X86::FLDCW16m)), CWFrameIdx);
19677 // Restore the memory image of control word to original value
19678 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19681 // Get the X86 opcode to use.
19683 switch (MI->getOpcode()) {
19684 default: llvm_unreachable("illegal opcode!");
19685 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19686 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19687 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19688 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19689 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19690 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19691 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19692 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19693 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19697 MachineOperand &Op = MI->getOperand(0);
19699 AM.BaseType = X86AddressMode::RegBase;
19700 AM.Base.Reg = Op.getReg();
19702 AM.BaseType = X86AddressMode::FrameIndexBase;
19703 AM.Base.FrameIndex = Op.getIndex();
19705 Op = MI->getOperand(1);
19707 AM.Scale = Op.getImm();
19708 Op = MI->getOperand(2);
19710 AM.IndexReg = Op.getImm();
19711 Op = MI->getOperand(3);
19712 if (Op.isGlobal()) {
19713 AM.GV = Op.getGlobal();
19715 AM.Disp = Op.getImm();
19717 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19718 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19720 // Reload the original control word now.
19721 addFrameReference(BuildMI(*BB, MI, DL,
19722 TII->get(X86::FLDCW16m)), CWFrameIdx);
19724 MI->eraseFromParent(); // The pseudo instruction is gone now.
19727 // String/text processing lowering.
19728 case X86::PCMPISTRM128REG:
19729 case X86::VPCMPISTRM128REG:
19730 case X86::PCMPISTRM128MEM:
19731 case X86::VPCMPISTRM128MEM:
19732 case X86::PCMPESTRM128REG:
19733 case X86::VPCMPESTRM128REG:
19734 case X86::PCMPESTRM128MEM:
19735 case X86::VPCMPESTRM128MEM:
19736 assert(Subtarget->hasSSE42() &&
19737 "Target must have SSE4.2 or AVX features enabled");
19738 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19740 // String/text processing lowering.
19741 case X86::PCMPISTRIREG:
19742 case X86::VPCMPISTRIREG:
19743 case X86::PCMPISTRIMEM:
19744 case X86::VPCMPISTRIMEM:
19745 case X86::PCMPESTRIREG:
19746 case X86::VPCMPESTRIREG:
19747 case X86::PCMPESTRIMEM:
19748 case X86::VPCMPESTRIMEM:
19749 assert(Subtarget->hasSSE42() &&
19750 "Target must have SSE4.2 or AVX features enabled");
19751 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19753 // Thread synchronization.
19755 return EmitMonitor(MI, BB, Subtarget);
19759 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19761 case X86::VASTART_SAVE_XMM_REGS:
19762 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19764 case X86::VAARG_64:
19765 return EmitVAARG64WithCustomInserter(MI, BB);
19767 case X86::EH_SjLj_SetJmp32:
19768 case X86::EH_SjLj_SetJmp64:
19769 return emitEHSjLjSetJmp(MI, BB);
19771 case X86::EH_SjLj_LongJmp32:
19772 case X86::EH_SjLj_LongJmp64:
19773 return emitEHSjLjLongJmp(MI, BB);
19775 case TargetOpcode::STATEPOINT:
19776 // As an implementation detail, STATEPOINT shares the STACKMAP format at
19777 // this point in the process. We diverge later.
19778 return emitPatchPoint(MI, BB);
19780 case TargetOpcode::STACKMAP:
19781 case TargetOpcode::PATCHPOINT:
19782 return emitPatchPoint(MI, BB);
19784 case X86::VFMADDPDr213r:
19785 case X86::VFMADDPSr213r:
19786 case X86::VFMADDSDr213r:
19787 case X86::VFMADDSSr213r:
19788 case X86::VFMSUBPDr213r:
19789 case X86::VFMSUBPSr213r:
19790 case X86::VFMSUBSDr213r:
19791 case X86::VFMSUBSSr213r:
19792 case X86::VFNMADDPDr213r:
19793 case X86::VFNMADDPSr213r:
19794 case X86::VFNMADDSDr213r:
19795 case X86::VFNMADDSSr213r:
19796 case X86::VFNMSUBPDr213r:
19797 case X86::VFNMSUBPSr213r:
19798 case X86::VFNMSUBSDr213r:
19799 case X86::VFNMSUBSSr213r:
19800 case X86::VFMADDSUBPDr213r:
19801 case X86::VFMADDSUBPSr213r:
19802 case X86::VFMSUBADDPDr213r:
19803 case X86::VFMSUBADDPSr213r:
19804 case X86::VFMADDPDr213rY:
19805 case X86::VFMADDPSr213rY:
19806 case X86::VFMSUBPDr213rY:
19807 case X86::VFMSUBPSr213rY:
19808 case X86::VFNMADDPDr213rY:
19809 case X86::VFNMADDPSr213rY:
19810 case X86::VFNMSUBPDr213rY:
19811 case X86::VFNMSUBPSr213rY:
19812 case X86::VFMADDSUBPDr213rY:
19813 case X86::VFMADDSUBPSr213rY:
19814 case X86::VFMSUBADDPDr213rY:
19815 case X86::VFMSUBADDPSr213rY:
19816 return emitFMA3Instr(MI, BB);
19820 //===----------------------------------------------------------------------===//
19821 // X86 Optimization Hooks
19822 //===----------------------------------------------------------------------===//
19824 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19827 const SelectionDAG &DAG,
19828 unsigned Depth) const {
19829 unsigned BitWidth = KnownZero.getBitWidth();
19830 unsigned Opc = Op.getOpcode();
19831 assert((Opc >= ISD::BUILTIN_OP_END ||
19832 Opc == ISD::INTRINSIC_WO_CHAIN ||
19833 Opc == ISD::INTRINSIC_W_CHAIN ||
19834 Opc == ISD::INTRINSIC_VOID) &&
19835 "Should use MaskedValueIsZero if you don't know whether Op"
19836 " is a target node!");
19838 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19852 // These nodes' second result is a boolean.
19853 if (Op.getResNo() == 0)
19856 case X86ISD::SETCC:
19857 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19859 case ISD::INTRINSIC_WO_CHAIN: {
19860 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19861 unsigned NumLoBits = 0;
19864 case Intrinsic::x86_sse_movmsk_ps:
19865 case Intrinsic::x86_avx_movmsk_ps_256:
19866 case Intrinsic::x86_sse2_movmsk_pd:
19867 case Intrinsic::x86_avx_movmsk_pd_256:
19868 case Intrinsic::x86_mmx_pmovmskb:
19869 case Intrinsic::x86_sse2_pmovmskb_128:
19870 case Intrinsic::x86_avx2_pmovmskb: {
19871 // High bits of movmskp{s|d}, pmovmskb are known zero.
19873 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19874 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19875 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19876 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19877 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19878 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19879 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19880 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19882 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19891 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19893 const SelectionDAG &,
19894 unsigned Depth) const {
19895 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19896 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19897 return Op.getValueType().getScalarType().getSizeInBits();
19903 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19904 /// node is a GlobalAddress + offset.
19905 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19906 const GlobalValue* &GA,
19907 int64_t &Offset) const {
19908 if (N->getOpcode() == X86ISD::Wrapper) {
19909 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19910 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19911 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19915 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19918 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19919 /// same as extracting the high 128-bit part of 256-bit vector and then
19920 /// inserting the result into the low part of a new 256-bit vector
19921 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19922 EVT VT = SVOp->getValueType(0);
19923 unsigned NumElems = VT.getVectorNumElements();
19925 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19926 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19927 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19928 SVOp->getMaskElt(j) >= 0)
19934 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19935 /// same as extracting the low 128-bit part of 256-bit vector and then
19936 /// inserting the result into the high part of a new 256-bit vector
19937 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19938 EVT VT = SVOp->getValueType(0);
19939 unsigned NumElems = VT.getVectorNumElements();
19941 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19942 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19943 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19944 SVOp->getMaskElt(j) >= 0)
19950 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19951 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19952 TargetLowering::DAGCombinerInfo &DCI,
19953 const X86Subtarget* Subtarget) {
19955 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19956 SDValue V1 = SVOp->getOperand(0);
19957 SDValue V2 = SVOp->getOperand(1);
19958 EVT VT = SVOp->getValueType(0);
19959 unsigned NumElems = VT.getVectorNumElements();
19961 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19962 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19966 // V UNDEF BUILD_VECTOR UNDEF
19968 // CONCAT_VECTOR CONCAT_VECTOR
19971 // RESULT: V + zero extended
19973 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19974 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19975 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19978 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19981 // To match the shuffle mask, the first half of the mask should
19982 // be exactly the first vector, and all the rest a splat with the
19983 // first element of the second one.
19984 for (unsigned i = 0; i != NumElems/2; ++i)
19985 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19986 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19989 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19990 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19991 if (Ld->hasNUsesOfValue(1, 0)) {
19992 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19993 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19995 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19997 Ld->getPointerInfo(),
19998 Ld->getAlignment(),
19999 false/*isVolatile*/, true/*ReadMem*/,
20000 false/*WriteMem*/);
20002 // Make sure the newly-created LOAD is in the same position as Ld in
20003 // terms of dependency. We create a TokenFactor for Ld and ResNode,
20004 // and update uses of Ld's output chain to use the TokenFactor.
20005 if (Ld->hasAnyUseOfValue(1)) {
20006 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20007 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20008 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20009 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20010 SDValue(ResNode.getNode(), 1));
20013 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
20017 // Emit a zeroed vector and insert the desired subvector on its
20019 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20020 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20021 return DCI.CombineTo(N, InsV);
20024 //===--------------------------------------------------------------------===//
20025 // Combine some shuffles into subvector extracts and inserts:
20028 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20029 if (isShuffleHigh128VectorInsertLow(SVOp)) {
20030 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20031 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20032 return DCI.CombineTo(N, InsV);
20035 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20036 if (isShuffleLow128VectorInsertHigh(SVOp)) {
20037 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20038 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20039 return DCI.CombineTo(N, InsV);
20045 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20048 /// This is the leaf of the recursive combinine below. When we have found some
20049 /// chain of single-use x86 shuffle instructions and accumulated the combined
20050 /// shuffle mask represented by them, this will try to pattern match that mask
20051 /// into either a single instruction if there is a special purpose instruction
20052 /// for this operation, or into a PSHUFB instruction which is a fully general
20053 /// instruction but should only be used to replace chains over a certain depth.
20054 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20055 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20056 TargetLowering::DAGCombinerInfo &DCI,
20057 const X86Subtarget *Subtarget) {
20058 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20060 // Find the operand that enters the chain. Note that multiple uses are OK
20061 // here, we're not going to remove the operand we find.
20062 SDValue Input = Op.getOperand(0);
20063 while (Input.getOpcode() == ISD::BITCAST)
20064 Input = Input.getOperand(0);
20066 MVT VT = Input.getSimpleValueType();
20067 MVT RootVT = Root.getSimpleValueType();
20070 // Just remove no-op shuffle masks.
20071 if (Mask.size() == 1) {
20072 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
20077 // Use the float domain if the operand type is a floating point type.
20078 bool FloatDomain = VT.isFloatingPoint();
20080 // For floating point shuffles, we don't have free copies in the shuffle
20081 // instructions or the ability to load as part of the instruction, so
20082 // canonicalize their shuffles to UNPCK or MOV variants.
20084 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20085 // vectors because it can have a load folded into it that UNPCK cannot. This
20086 // doesn't preclude something switching to the shorter encoding post-RA.
20088 // FIXME: Should teach these routines about AVX vector widths.
20089 if (FloatDomain && VT.getSizeInBits() == 128) {
20090 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20091 bool Lo = Mask.equals({0, 0});
20094 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20095 // is no slower than UNPCKLPD but has the option to fold the input operand
20096 // into even an unaligned memory load.
20097 if (Lo && Subtarget->hasSSE3()) {
20098 Shuffle = X86ISD::MOVDDUP;
20099 ShuffleVT = MVT::v2f64;
20101 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20102 // than the UNPCK variants.
20103 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20104 ShuffleVT = MVT::v4f32;
20106 if (Depth == 1 && Root->getOpcode() == Shuffle)
20107 return false; // Nothing to do!
20108 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20109 DCI.AddToWorklist(Op.getNode());
20110 if (Shuffle == X86ISD::MOVDDUP)
20111 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20113 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20114 DCI.AddToWorklist(Op.getNode());
20115 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20119 if (Subtarget->hasSSE3() &&
20120 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20121 bool Lo = Mask.equals({0, 0, 2, 2});
20122 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20123 MVT ShuffleVT = MVT::v4f32;
20124 if (Depth == 1 && Root->getOpcode() == Shuffle)
20125 return false; // Nothing to do!
20126 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20127 DCI.AddToWorklist(Op.getNode());
20128 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20129 DCI.AddToWorklist(Op.getNode());
20130 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20134 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20135 bool Lo = Mask.equals({0, 0, 1, 1});
20136 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20137 MVT ShuffleVT = MVT::v4f32;
20138 if (Depth == 1 && Root->getOpcode() == Shuffle)
20139 return false; // Nothing to do!
20140 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20141 DCI.AddToWorklist(Op.getNode());
20142 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20143 DCI.AddToWorklist(Op.getNode());
20144 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20150 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20151 // variants as none of these have single-instruction variants that are
20152 // superior to the UNPCK formulation.
20153 if (!FloatDomain && VT.getSizeInBits() == 128 &&
20154 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20155 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20156 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20158 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20159 bool Lo = Mask[0] == 0;
20160 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20161 if (Depth == 1 && Root->getOpcode() == Shuffle)
20162 return false; // Nothing to do!
20164 switch (Mask.size()) {
20166 ShuffleVT = MVT::v8i16;
20169 ShuffleVT = MVT::v16i8;
20172 llvm_unreachable("Impossible mask size!");
20174 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20175 DCI.AddToWorklist(Op.getNode());
20176 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20177 DCI.AddToWorklist(Op.getNode());
20178 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20183 // Don't try to re-form single instruction chains under any circumstances now
20184 // that we've done encoding canonicalization for them.
20188 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20189 // can replace them with a single PSHUFB instruction profitably. Intel's
20190 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20191 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20192 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20193 SmallVector<SDValue, 16> PSHUFBMask;
20194 int NumBytes = VT.getSizeInBits() / 8;
20195 int Ratio = NumBytes / Mask.size();
20196 for (int i = 0; i < NumBytes; ++i) {
20197 if (Mask[i / Ratio] == SM_SentinelUndef) {
20198 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20201 int M = Mask[i / Ratio] != SM_SentinelZero
20202 ? Ratio * Mask[i / Ratio] + i % Ratio
20204 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20206 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20207 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20208 DCI.AddToWorklist(Op.getNode());
20209 SDValue PSHUFBMaskOp =
20210 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20211 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20212 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20213 DCI.AddToWorklist(Op.getNode());
20214 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20219 // Failed to find any combines.
20223 /// \brief Fully generic combining of x86 shuffle instructions.
20225 /// This should be the last combine run over the x86 shuffle instructions. Once
20226 /// they have been fully optimized, this will recursively consider all chains
20227 /// of single-use shuffle instructions, build a generic model of the cumulative
20228 /// shuffle operation, and check for simpler instructions which implement this
20229 /// operation. We use this primarily for two purposes:
20231 /// 1) Collapse generic shuffles to specialized single instructions when
20232 /// equivalent. In most cases, this is just an encoding size win, but
20233 /// sometimes we will collapse multiple generic shuffles into a single
20234 /// special-purpose shuffle.
20235 /// 2) Look for sequences of shuffle instructions with 3 or more total
20236 /// instructions, and replace them with the slightly more expensive SSSE3
20237 /// PSHUFB instruction if available. We do this as the last combining step
20238 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
20239 /// a suitable short sequence of other instructions. The PHUFB will either
20240 /// use a register or have to read from memory and so is slightly (but only
20241 /// slightly) more expensive than the other shuffle instructions.
20243 /// Because this is inherently a quadratic operation (for each shuffle in
20244 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20245 /// This should never be an issue in practice as the shuffle lowering doesn't
20246 /// produce sequences of more than 8 instructions.
20248 /// FIXME: We will currently miss some cases where the redundant shuffling
20249 /// would simplify under the threshold for PSHUFB formation because of
20250 /// combine-ordering. To fix this, we should do the redundant instruction
20251 /// combining in this recursive walk.
20252 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20253 ArrayRef<int> RootMask,
20254 int Depth, bool HasPSHUFB,
20256 TargetLowering::DAGCombinerInfo &DCI,
20257 const X86Subtarget *Subtarget) {
20258 // Bound the depth of our recursive combine because this is ultimately
20259 // quadratic in nature.
20263 // Directly rip through bitcasts to find the underlying operand.
20264 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20265 Op = Op.getOperand(0);
20267 MVT VT = Op.getSimpleValueType();
20268 if (!VT.isVector())
20269 return false; // Bail if we hit a non-vector.
20271 assert(Root.getSimpleValueType().isVector() &&
20272 "Shuffles operate on vector types!");
20273 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20274 "Can only combine shuffles of the same vector register size.");
20276 if (!isTargetShuffle(Op.getOpcode()))
20278 SmallVector<int, 16> OpMask;
20280 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20281 // We only can combine unary shuffles which we can decode the mask for.
20282 if (!HaveMask || !IsUnary)
20285 assert(VT.getVectorNumElements() == OpMask.size() &&
20286 "Different mask size from vector size!");
20287 assert(((RootMask.size() > OpMask.size() &&
20288 RootMask.size() % OpMask.size() == 0) ||
20289 (OpMask.size() > RootMask.size() &&
20290 OpMask.size() % RootMask.size() == 0) ||
20291 OpMask.size() == RootMask.size()) &&
20292 "The smaller number of elements must divide the larger.");
20293 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20294 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20295 assert(((RootRatio == 1 && OpRatio == 1) ||
20296 (RootRatio == 1) != (OpRatio == 1)) &&
20297 "Must not have a ratio for both incoming and op masks!");
20299 SmallVector<int, 16> Mask;
20300 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20302 // Merge this shuffle operation's mask into our accumulated mask. Note that
20303 // this shuffle's mask will be the first applied to the input, followed by the
20304 // root mask to get us all the way to the root value arrangement. The reason
20305 // for this order is that we are recursing up the operation chain.
20306 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20307 int RootIdx = i / RootRatio;
20308 if (RootMask[RootIdx] < 0) {
20309 // This is a zero or undef lane, we're done.
20310 Mask.push_back(RootMask[RootIdx]);
20314 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20315 int OpIdx = RootMaskedIdx / OpRatio;
20316 if (OpMask[OpIdx] < 0) {
20317 // The incoming lanes are zero or undef, it doesn't matter which ones we
20319 Mask.push_back(OpMask[OpIdx]);
20323 // Ok, we have non-zero lanes, map them through.
20324 Mask.push_back(OpMask[OpIdx] * OpRatio +
20325 RootMaskedIdx % OpRatio);
20328 // See if we can recurse into the operand to combine more things.
20329 switch (Op.getOpcode()) {
20330 case X86ISD::PSHUFB:
20332 case X86ISD::PSHUFD:
20333 case X86ISD::PSHUFHW:
20334 case X86ISD::PSHUFLW:
20335 if (Op.getOperand(0).hasOneUse() &&
20336 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20337 HasPSHUFB, DAG, DCI, Subtarget))
20341 case X86ISD::UNPCKL:
20342 case X86ISD::UNPCKH:
20343 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20344 // We can't check for single use, we have to check that this shuffle is the only user.
20345 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20346 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20347 HasPSHUFB, DAG, DCI, Subtarget))
20352 // Minor canonicalization of the accumulated shuffle mask to make it easier
20353 // to match below. All this does is detect masks with squential pairs of
20354 // elements, and shrink them to the half-width mask. It does this in a loop
20355 // so it will reduce the size of the mask to the minimal width mask which
20356 // performs an equivalent shuffle.
20357 SmallVector<int, 16> WidenedMask;
20358 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20359 Mask = std::move(WidenedMask);
20360 WidenedMask.clear();
20363 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20367 /// \brief Get the PSHUF-style mask from PSHUF node.
20369 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20370 /// PSHUF-style masks that can be reused with such instructions.
20371 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20372 MVT VT = N.getSimpleValueType();
20373 SmallVector<int, 4> Mask;
20375 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20379 // If we have more than 128-bits, only the low 128-bits of shuffle mask
20380 // matter. Check that the upper masks are repeats and remove them.
20381 if (VT.getSizeInBits() > 128) {
20382 int LaneElts = 128 / VT.getScalarSizeInBits();
20384 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20385 for (int j = 0; j < LaneElts; ++j)
20386 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20387 "Mask doesn't repeat in high 128-bit lanes!");
20389 Mask.resize(LaneElts);
20392 switch (N.getOpcode()) {
20393 case X86ISD::PSHUFD:
20395 case X86ISD::PSHUFLW:
20398 case X86ISD::PSHUFHW:
20399 Mask.erase(Mask.begin(), Mask.begin() + 4);
20400 for (int &M : Mask)
20404 llvm_unreachable("No valid shuffle instruction found!");
20408 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20410 /// We walk up the chain and look for a combinable shuffle, skipping over
20411 /// shuffles that we could hoist this shuffle's transformation past without
20412 /// altering anything.
20414 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20416 TargetLowering::DAGCombinerInfo &DCI) {
20417 assert(N.getOpcode() == X86ISD::PSHUFD &&
20418 "Called with something other than an x86 128-bit half shuffle!");
20421 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20422 // of the shuffles in the chain so that we can form a fresh chain to replace
20424 SmallVector<SDValue, 8> Chain;
20425 SDValue V = N.getOperand(0);
20426 for (; V.hasOneUse(); V = V.getOperand(0)) {
20427 switch (V.getOpcode()) {
20429 return SDValue(); // Nothing combined!
20432 // Skip bitcasts as we always know the type for the target specific
20436 case X86ISD::PSHUFD:
20437 // Found another dword shuffle.
20440 case X86ISD::PSHUFLW:
20441 // Check that the low words (being shuffled) are the identity in the
20442 // dword shuffle, and the high words are self-contained.
20443 if (Mask[0] != 0 || Mask[1] != 1 ||
20444 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20447 Chain.push_back(V);
20450 case X86ISD::PSHUFHW:
20451 // Check that the high words (being shuffled) are the identity in the
20452 // dword shuffle, and the low words are self-contained.
20453 if (Mask[2] != 2 || Mask[3] != 3 ||
20454 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20457 Chain.push_back(V);
20460 case X86ISD::UNPCKL:
20461 case X86ISD::UNPCKH:
20462 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20463 // shuffle into a preceding word shuffle.
20464 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20465 V.getSimpleValueType().getScalarType() != MVT::i16)
20468 // Search for a half-shuffle which we can combine with.
20469 unsigned CombineOp =
20470 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20471 if (V.getOperand(0) != V.getOperand(1) ||
20472 !V->isOnlyUserOf(V.getOperand(0).getNode()))
20474 Chain.push_back(V);
20475 V = V.getOperand(0);
20477 switch (V.getOpcode()) {
20479 return SDValue(); // Nothing to combine.
20481 case X86ISD::PSHUFLW:
20482 case X86ISD::PSHUFHW:
20483 if (V.getOpcode() == CombineOp)
20486 Chain.push_back(V);
20490 V = V.getOperand(0);
20494 } while (V.hasOneUse());
20497 // Break out of the loop if we break out of the switch.
20501 if (!V.hasOneUse())
20502 // We fell out of the loop without finding a viable combining instruction.
20505 // Merge this node's mask and our incoming mask.
20506 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20507 for (int &M : Mask)
20509 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20510 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20512 // Rebuild the chain around this new shuffle.
20513 while (!Chain.empty()) {
20514 SDValue W = Chain.pop_back_val();
20516 if (V.getValueType() != W.getOperand(0).getValueType())
20517 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20519 switch (W.getOpcode()) {
20521 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20523 case X86ISD::UNPCKL:
20524 case X86ISD::UNPCKH:
20525 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20528 case X86ISD::PSHUFD:
20529 case X86ISD::PSHUFLW:
20530 case X86ISD::PSHUFHW:
20531 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20535 if (V.getValueType() != N.getValueType())
20536 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20538 // Return the new chain to replace N.
20542 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20544 /// We walk up the chain, skipping shuffles of the other half and looking
20545 /// through shuffles which switch halves trying to find a shuffle of the same
20546 /// pair of dwords.
20547 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20549 TargetLowering::DAGCombinerInfo &DCI) {
20551 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20552 "Called with something other than an x86 128-bit half shuffle!");
20554 unsigned CombineOpcode = N.getOpcode();
20556 // Walk up a single-use chain looking for a combinable shuffle.
20557 SDValue V = N.getOperand(0);
20558 for (; V.hasOneUse(); V = V.getOperand(0)) {
20559 switch (V.getOpcode()) {
20561 return false; // Nothing combined!
20564 // Skip bitcasts as we always know the type for the target specific
20568 case X86ISD::PSHUFLW:
20569 case X86ISD::PSHUFHW:
20570 if (V.getOpcode() == CombineOpcode)
20573 // Other-half shuffles are no-ops.
20576 // Break out of the loop if we break out of the switch.
20580 if (!V.hasOneUse())
20581 // We fell out of the loop without finding a viable combining instruction.
20584 // Combine away the bottom node as its shuffle will be accumulated into
20585 // a preceding shuffle.
20586 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20588 // Record the old value.
20591 // Merge this node's mask and our incoming mask (adjusted to account for all
20592 // the pshufd instructions encountered).
20593 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20594 for (int &M : Mask)
20596 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20597 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20599 // Check that the shuffles didn't cancel each other out. If not, we need to
20600 // combine to the new one.
20602 // Replace the combinable shuffle with the combined one, updating all users
20603 // so that we re-evaluate the chain here.
20604 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20609 /// \brief Try to combine x86 target specific shuffles.
20610 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20611 TargetLowering::DAGCombinerInfo &DCI,
20612 const X86Subtarget *Subtarget) {
20614 MVT VT = N.getSimpleValueType();
20615 SmallVector<int, 4> Mask;
20617 switch (N.getOpcode()) {
20618 case X86ISD::PSHUFD:
20619 case X86ISD::PSHUFLW:
20620 case X86ISD::PSHUFHW:
20621 Mask = getPSHUFShuffleMask(N);
20622 assert(Mask.size() == 4);
20628 // Nuke no-op shuffles that show up after combining.
20629 if (isNoopShuffleMask(Mask))
20630 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20632 // Look for simplifications involving one or two shuffle instructions.
20633 SDValue V = N.getOperand(0);
20634 switch (N.getOpcode()) {
20637 case X86ISD::PSHUFLW:
20638 case X86ISD::PSHUFHW:
20639 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20641 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20642 return SDValue(); // We combined away this shuffle, so we're done.
20644 // See if this reduces to a PSHUFD which is no more expensive and can
20645 // combine with more operations. Note that it has to at least flip the
20646 // dwords as otherwise it would have been removed as a no-op.
20647 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20648 int DMask[] = {0, 1, 2, 3};
20649 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20650 DMask[DOffset + 0] = DOffset + 1;
20651 DMask[DOffset + 1] = DOffset + 0;
20652 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20653 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20654 DCI.AddToWorklist(V.getNode());
20655 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20656 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20657 DCI.AddToWorklist(V.getNode());
20658 return DAG.getNode(ISD::BITCAST, DL, VT, V);
20661 // Look for shuffle patterns which can be implemented as a single unpack.
20662 // FIXME: This doesn't handle the location of the PSHUFD generically, and
20663 // only works when we have a PSHUFD followed by two half-shuffles.
20664 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20665 (V.getOpcode() == X86ISD::PSHUFLW ||
20666 V.getOpcode() == X86ISD::PSHUFHW) &&
20667 V.getOpcode() != N.getOpcode() &&
20669 SDValue D = V.getOperand(0);
20670 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20671 D = D.getOperand(0);
20672 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20673 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20674 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20675 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20676 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20678 for (int i = 0; i < 4; ++i) {
20679 WordMask[i + NOffset] = Mask[i] + NOffset;
20680 WordMask[i + VOffset] = VMask[i] + VOffset;
20682 // Map the word mask through the DWord mask.
20684 for (int i = 0; i < 8; ++i)
20685 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20686 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20687 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20688 // We can replace all three shuffles with an unpack.
20689 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20690 DCI.AddToWorklist(V.getNode());
20691 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20700 case X86ISD::PSHUFD:
20701 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20710 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20712 /// We combine this directly on the abstract vector shuffle nodes so it is
20713 /// easier to generically match. We also insert dummy vector shuffle nodes for
20714 /// the operands which explicitly discard the lanes which are unused by this
20715 /// operation to try to flow through the rest of the combiner the fact that
20716 /// they're unused.
20717 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20719 EVT VT = N->getValueType(0);
20721 // We only handle target-independent shuffles.
20722 // FIXME: It would be easy and harmless to use the target shuffle mask
20723 // extraction tool to support more.
20724 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20727 auto *SVN = cast<ShuffleVectorSDNode>(N);
20728 ArrayRef<int> Mask = SVN->getMask();
20729 SDValue V1 = N->getOperand(0);
20730 SDValue V2 = N->getOperand(1);
20732 // We require the first shuffle operand to be the SUB node, and the second to
20733 // be the ADD node.
20734 // FIXME: We should support the commuted patterns.
20735 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20738 // If there are other uses of these operations we can't fold them.
20739 if (!V1->hasOneUse() || !V2->hasOneUse())
20742 // Ensure that both operations have the same operands. Note that we can
20743 // commute the FADD operands.
20744 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20745 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20746 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20749 // We're looking for blends between FADD and FSUB nodes. We insist on these
20750 // nodes being lined up in a specific expected pattern.
20751 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20752 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20753 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20756 // Only specific types are legal at this point, assert so we notice if and
20757 // when these change.
20758 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20759 VT == MVT::v4f64) &&
20760 "Unknown vector type encountered!");
20762 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20765 /// PerformShuffleCombine - Performs several different shuffle combines.
20766 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20767 TargetLowering::DAGCombinerInfo &DCI,
20768 const X86Subtarget *Subtarget) {
20770 SDValue N0 = N->getOperand(0);
20771 SDValue N1 = N->getOperand(1);
20772 EVT VT = N->getValueType(0);
20774 // Don't create instructions with illegal types after legalize types has run.
20775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20776 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20779 // If we have legalized the vector types, look for blends of FADD and FSUB
20780 // nodes that we can fuse into an ADDSUB node.
20781 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20782 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20785 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20786 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20787 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20788 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20790 // During Type Legalization, when promoting illegal vector types,
20791 // the backend might introduce new shuffle dag nodes and bitcasts.
20793 // This code performs the following transformation:
20794 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20795 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20797 // We do this only if both the bitcast and the BINOP dag nodes have
20798 // one use. Also, perform this transformation only if the new binary
20799 // operation is legal. This is to avoid introducing dag nodes that
20800 // potentially need to be further expanded (or custom lowered) into a
20801 // less optimal sequence of dag nodes.
20802 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20803 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20804 N0.getOpcode() == ISD::BITCAST) {
20805 SDValue BC0 = N0.getOperand(0);
20806 EVT SVT = BC0.getValueType();
20807 unsigned Opcode = BC0.getOpcode();
20808 unsigned NumElts = VT.getVectorNumElements();
20810 if (BC0.hasOneUse() && SVT.isVector() &&
20811 SVT.getVectorNumElements() * 2 == NumElts &&
20812 TLI.isOperationLegal(Opcode, VT)) {
20813 bool CanFold = false;
20825 unsigned SVTNumElts = SVT.getVectorNumElements();
20826 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20827 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20828 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20829 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20830 CanFold = SVOp->getMaskElt(i) < 0;
20833 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20834 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20835 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20836 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20841 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20842 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20843 // consecutive, non-overlapping, and in the right order.
20844 SmallVector<SDValue, 16> Elts;
20845 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20846 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20848 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20852 if (isTargetShuffle(N->getOpcode())) {
20854 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20855 if (Shuffle.getNode())
20858 // Try recursively combining arbitrary sequences of x86 shuffle
20859 // instructions into higher-order shuffles. We do this after combining
20860 // specific PSHUF instruction sequences into their minimal form so that we
20861 // can evaluate how many specialized shuffle instructions are involved in
20862 // a particular chain.
20863 SmallVector<int, 1> NonceMask; // Just a placeholder.
20864 NonceMask.push_back(0);
20865 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20866 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20868 return SDValue(); // This routine will use CombineTo to replace N.
20874 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20875 /// specific shuffle of a load can be folded into a single element load.
20876 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20877 /// shuffles have been custom lowered so we need to handle those here.
20878 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20879 TargetLowering::DAGCombinerInfo &DCI) {
20880 if (DCI.isBeforeLegalizeOps())
20883 SDValue InVec = N->getOperand(0);
20884 SDValue EltNo = N->getOperand(1);
20886 if (!isa<ConstantSDNode>(EltNo))
20889 EVT OriginalVT = InVec.getValueType();
20891 if (InVec.getOpcode() == ISD::BITCAST) {
20892 // Don't duplicate a load with other uses.
20893 if (!InVec.hasOneUse())
20895 EVT BCVT = InVec.getOperand(0).getValueType();
20896 if (!BCVT.isVector() ||
20897 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20899 InVec = InVec.getOperand(0);
20902 EVT CurrentVT = InVec.getValueType();
20904 if (!isTargetShuffle(InVec.getOpcode()))
20907 // Don't duplicate a load with other uses.
20908 if (!InVec.hasOneUse())
20911 SmallVector<int, 16> ShuffleMask;
20913 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20914 ShuffleMask, UnaryShuffle))
20917 // Select the input vector, guarding against out of range extract vector.
20918 unsigned NumElems = CurrentVT.getVectorNumElements();
20919 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20920 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20921 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20922 : InVec.getOperand(1);
20924 // If inputs to shuffle are the same for both ops, then allow 2 uses
20925 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20926 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20928 if (LdNode.getOpcode() == ISD::BITCAST) {
20929 // Don't duplicate a load with other uses.
20930 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20933 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20934 LdNode = LdNode.getOperand(0);
20937 if (!ISD::isNormalLoad(LdNode.getNode()))
20940 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20942 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20945 EVT EltVT = N->getValueType(0);
20946 // If there's a bitcast before the shuffle, check if the load type and
20947 // alignment is valid.
20948 unsigned Align = LN0->getAlignment();
20949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20950 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20951 EltVT.getTypeForEVT(*DAG.getContext()));
20953 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20956 // All checks match so transform back to vector_shuffle so that DAG combiner
20957 // can finish the job
20960 // Create shuffle node taking into account the case that its a unary shuffle
20961 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20962 : InVec.getOperand(1);
20963 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20964 InVec.getOperand(0), Shuffle,
20966 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20967 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20971 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20972 /// special and don't usually play with other vector types, it's better to
20973 /// handle them early to be sure we emit efficient code by avoiding
20974 /// store-load conversions.
20975 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20976 if (N->getValueType(0) != MVT::x86mmx ||
20977 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20978 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20981 SDValue V = N->getOperand(0);
20982 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20983 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20984 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20985 N->getValueType(0), V.getOperand(0));
20990 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20991 /// generation and convert it from being a bunch of shuffles and extracts
20992 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20993 /// storing the value and loading scalars back, while for x64 we should
20994 /// use 64-bit extracts and shifts.
20995 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20996 TargetLowering::DAGCombinerInfo &DCI) {
20997 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20998 if (NewOp.getNode())
21001 SDValue InputVector = N->getOperand(0);
21002 SDLoc dl(InputVector);
21003 // Detect mmx to i32 conversion through a v2i32 elt extract.
21004 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21005 N->getValueType(0) == MVT::i32 &&
21006 InputVector.getValueType() == MVT::v2i32) {
21008 // The bitcast source is a direct mmx result.
21009 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21010 if (MMXSrc.getValueType() == MVT::x86mmx)
21011 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21012 N->getValueType(0),
21013 InputVector.getNode()->getOperand(0));
21015 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21016 SDValue MMXSrcOp = MMXSrc.getOperand(0);
21017 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21018 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21019 MMXSrcOp.getOpcode() == ISD::BITCAST &&
21020 MMXSrcOp.getValueType() == MVT::v1i64 &&
21021 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21022 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21023 N->getValueType(0),
21024 MMXSrcOp.getOperand(0));
21027 EVT VT = N->getValueType(0);
21029 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21030 InputVector.getOpcode() == ISD::BITCAST &&
21031 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21032 uint64_t ExtractedElt =
21033 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21034 uint64_t InputValue =
21035 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21036 uint64_t Res = (InputValue >> ExtractedElt) & 1;
21037 return DAG.getConstant(Res, dl, MVT::i1);
21039 // Only operate on vectors of 4 elements, where the alternative shuffling
21040 // gets to be more expensive.
21041 if (InputVector.getValueType() != MVT::v4i32)
21044 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21045 // single use which is a sign-extend or zero-extend, and all elements are
21047 SmallVector<SDNode *, 4> Uses;
21048 unsigned ExtractedElements = 0;
21049 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21050 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21051 if (UI.getUse().getResNo() != InputVector.getResNo())
21054 SDNode *Extract = *UI;
21055 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21058 if (Extract->getValueType(0) != MVT::i32)
21060 if (!Extract->hasOneUse())
21062 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21063 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21065 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21068 // Record which element was extracted.
21069 ExtractedElements |=
21070 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21072 Uses.push_back(Extract);
21075 // If not all the elements were used, this may not be worthwhile.
21076 if (ExtractedElements != 15)
21079 // Ok, we've now decided to do the transformation.
21080 // If 64-bit shifts are legal, use the extract-shift sequence,
21081 // otherwise bounce the vector off the cache.
21082 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21085 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21086 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
21087 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21088 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21089 DAG.getConstant(0, dl, VecIdxTy));
21090 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21091 DAG.getConstant(1, dl, VecIdxTy));
21093 SDValue ShAmt = DAG.getConstant(32, dl,
21094 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21095 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21096 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21097 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21098 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21099 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21100 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21102 // Store the value to a temporary stack slot.
21103 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21104 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21105 MachinePointerInfo(), false, false, 0);
21107 EVT ElementType = InputVector.getValueType().getVectorElementType();
21108 unsigned EltSize = ElementType.getSizeInBits() / 8;
21110 // Replace each use (extract) with a load of the appropriate element.
21111 for (unsigned i = 0; i < 4; ++i) {
21112 uint64_t Offset = EltSize * i;
21113 SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21115 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21116 StackPtr, OffsetVal);
21118 // Load the scalar.
21119 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21120 ScalarAddr, MachinePointerInfo(),
21121 false, false, false, 0);
21126 // Replace the extracts
21127 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21128 UE = Uses.end(); UI != UE; ++UI) {
21129 SDNode *Extract = *UI;
21131 SDValue Idx = Extract->getOperand(1);
21132 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21133 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21136 // The replacement was made in place; don't return anything.
21140 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21141 static std::pair<unsigned, bool>
21142 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21143 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21144 if (!VT.isVector())
21145 return std::make_pair(0, false);
21147 bool NeedSplit = false;
21148 switch (VT.getSimpleVT().SimpleTy) {
21149 default: return std::make_pair(0, false);
21152 if (!Subtarget->hasVLX())
21153 return std::make_pair(0, false);
21157 if (!Subtarget->hasBWI())
21158 return std::make_pair(0, false);
21162 if (!Subtarget->hasAVX512())
21163 return std::make_pair(0, false);
21168 if (!Subtarget->hasAVX2())
21170 if (!Subtarget->hasAVX())
21171 return std::make_pair(0, false);
21176 if (!Subtarget->hasSSE2())
21177 return std::make_pair(0, false);
21180 // SSE2 has only a small subset of the operations.
21181 bool hasUnsigned = Subtarget->hasSSE41() ||
21182 (Subtarget->hasSSE2() && VT == MVT::v16i8);
21183 bool hasSigned = Subtarget->hasSSE41() ||
21184 (Subtarget->hasSSE2() && VT == MVT::v8i16);
21186 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21189 // Check for x CC y ? x : y.
21190 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21191 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21196 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21199 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21202 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21205 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21207 // Check for x CC y ? y : x -- a min/max with reversed arms.
21208 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21209 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21214 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21217 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21220 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21223 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21227 return std::make_pair(Opc, NeedSplit);
21231 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21232 const X86Subtarget *Subtarget) {
21234 SDValue Cond = N->getOperand(0);
21235 SDValue LHS = N->getOperand(1);
21236 SDValue RHS = N->getOperand(2);
21238 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21239 SDValue CondSrc = Cond->getOperand(0);
21240 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21241 Cond = CondSrc->getOperand(0);
21244 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21247 // A vselect where all conditions and data are constants can be optimized into
21248 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21249 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21250 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21253 unsigned MaskValue = 0;
21254 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21257 MVT VT = N->getSimpleValueType(0);
21258 unsigned NumElems = VT.getVectorNumElements();
21259 SmallVector<int, 8> ShuffleMask(NumElems, -1);
21260 for (unsigned i = 0; i < NumElems; ++i) {
21261 // Be sure we emit undef where we can.
21262 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21263 ShuffleMask[i] = -1;
21265 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21268 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21269 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21271 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21274 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21276 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21277 TargetLowering::DAGCombinerInfo &DCI,
21278 const X86Subtarget *Subtarget) {
21280 SDValue Cond = N->getOperand(0);
21281 // Get the LHS/RHS of the select.
21282 SDValue LHS = N->getOperand(1);
21283 SDValue RHS = N->getOperand(2);
21284 EVT VT = LHS.getValueType();
21285 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21287 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21288 // instructions match the semantics of the common C idiom x<y?x:y but not
21289 // x<=y?x:y, because of how they handle negative zero (which can be
21290 // ignored in unsafe-math mode).
21291 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21292 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21293 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21294 (Subtarget->hasSSE2() ||
21295 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21296 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21298 unsigned Opcode = 0;
21299 // Check for x CC y ? x : y.
21300 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21301 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21305 // Converting this to a min would handle NaNs incorrectly, and swapping
21306 // the operands would cause it to handle comparisons between positive
21307 // and negative zero incorrectly.
21308 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21309 if (!DAG.getTarget().Options.UnsafeFPMath &&
21310 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21312 std::swap(LHS, RHS);
21314 Opcode = X86ISD::FMIN;
21317 // Converting this to a min would handle comparisons between positive
21318 // and negative zero incorrectly.
21319 if (!DAG.getTarget().Options.UnsafeFPMath &&
21320 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21322 Opcode = X86ISD::FMIN;
21325 // Converting this to a min would handle both negative zeros and NaNs
21326 // incorrectly, but we can swap the operands to fix both.
21327 std::swap(LHS, RHS);
21331 Opcode = X86ISD::FMIN;
21335 // Converting this to a max would handle comparisons between positive
21336 // and negative zero incorrectly.
21337 if (!DAG.getTarget().Options.UnsafeFPMath &&
21338 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21340 Opcode = X86ISD::FMAX;
21343 // Converting this to a max would handle NaNs incorrectly, and swapping
21344 // the operands would cause it to handle comparisons between positive
21345 // and negative zero incorrectly.
21346 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21347 if (!DAG.getTarget().Options.UnsafeFPMath &&
21348 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21350 std::swap(LHS, RHS);
21352 Opcode = X86ISD::FMAX;
21355 // Converting this to a max would handle both negative zeros and NaNs
21356 // incorrectly, but we can swap the operands to fix both.
21357 std::swap(LHS, RHS);
21361 Opcode = X86ISD::FMAX;
21364 // Check for x CC y ? y : x -- a min/max with reversed arms.
21365 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21366 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21370 // Converting this to a min would handle comparisons between positive
21371 // and negative zero incorrectly, and swapping the operands would
21372 // cause it to handle NaNs incorrectly.
21373 if (!DAG.getTarget().Options.UnsafeFPMath &&
21374 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21375 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21377 std::swap(LHS, RHS);
21379 Opcode = X86ISD::FMIN;
21382 // Converting this to a min would handle NaNs incorrectly.
21383 if (!DAG.getTarget().Options.UnsafeFPMath &&
21384 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21386 Opcode = X86ISD::FMIN;
21389 // Converting this to a min would handle both negative zeros and NaNs
21390 // incorrectly, but we can swap the operands to fix both.
21391 std::swap(LHS, RHS);
21395 Opcode = X86ISD::FMIN;
21399 // Converting this to a max would handle NaNs incorrectly.
21400 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21402 Opcode = X86ISD::FMAX;
21405 // Converting this to a max would handle comparisons between positive
21406 // and negative zero incorrectly, and swapping the operands would
21407 // cause it to handle NaNs incorrectly.
21408 if (!DAG.getTarget().Options.UnsafeFPMath &&
21409 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21410 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21412 std::swap(LHS, RHS);
21414 Opcode = X86ISD::FMAX;
21417 // Converting this to a max would handle both negative zeros and NaNs
21418 // incorrectly, but we can swap the operands to fix both.
21419 std::swap(LHS, RHS);
21423 Opcode = X86ISD::FMAX;
21429 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21432 EVT CondVT = Cond.getValueType();
21433 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21434 CondVT.getVectorElementType() == MVT::i1) {
21435 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21436 // lowering on KNL. In this case we convert it to
21437 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21438 // The same situation for all 128 and 256-bit vectors of i8 and i16.
21439 // Since SKX these selects have a proper lowering.
21440 EVT OpVT = LHS.getValueType();
21441 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21442 (OpVT.getVectorElementType() == MVT::i8 ||
21443 OpVT.getVectorElementType() == MVT::i16) &&
21444 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21445 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21446 DCI.AddToWorklist(Cond.getNode());
21447 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21450 // If this is a select between two integer constants, try to do some
21452 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21453 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21454 // Don't do this for crazy integer types.
21455 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21456 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21457 // so that TrueC (the true value) is larger than FalseC.
21458 bool NeedsCondInvert = false;
21460 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21461 // Efficiently invertible.
21462 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
21463 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
21464 isa<ConstantSDNode>(Cond.getOperand(1))))) {
21465 NeedsCondInvert = true;
21466 std::swap(TrueC, FalseC);
21469 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
21470 if (FalseC->getAPIntValue() == 0 &&
21471 TrueC->getAPIntValue().isPowerOf2()) {
21472 if (NeedsCondInvert) // Invert the condition if needed.
21473 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21474 DAG.getConstant(1, DL, Cond.getValueType()));
21476 // Zero extend the condition if needed.
21477 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21479 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21480 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21481 DAG.getConstant(ShAmt, DL, MVT::i8));
21484 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21485 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21486 if (NeedsCondInvert) // Invert the condition if needed.
21487 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21488 DAG.getConstant(1, DL, Cond.getValueType()));
21490 // Zero extend the condition if needed.
21491 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21492 FalseC->getValueType(0), Cond);
21493 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21494 SDValue(FalseC, 0));
21497 // Optimize cases that will turn into an LEA instruction. This requires
21498 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21499 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21500 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21501 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21503 bool isFastMultiplier = false;
21505 switch ((unsigned char)Diff) {
21507 case 1: // result = add base, cond
21508 case 2: // result = lea base( , cond*2)
21509 case 3: // result = lea base(cond, cond*2)
21510 case 4: // result = lea base( , cond*4)
21511 case 5: // result = lea base(cond, cond*4)
21512 case 8: // result = lea base( , cond*8)
21513 case 9: // result = lea base(cond, cond*8)
21514 isFastMultiplier = true;
21519 if (isFastMultiplier) {
21520 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21521 if (NeedsCondInvert) // Invert the condition if needed.
21522 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21523 DAG.getConstant(1, DL, Cond.getValueType()));
21525 // Zero extend the condition if needed.
21526 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21528 // Scale the condition by the difference.
21530 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21531 DAG.getConstant(Diff, DL,
21532 Cond.getValueType()));
21534 // Add the base if non-zero.
21535 if (FalseC->getAPIntValue() != 0)
21536 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21537 SDValue(FalseC, 0));
21544 // Canonicalize max and min:
21545 // (x > y) ? x : y -> (x >= y) ? x : y
21546 // (x < y) ? x : y -> (x <= y) ? x : y
21547 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21548 // the need for an extra compare
21549 // against zero. e.g.
21550 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21552 // testl %edi, %edi
21554 // cmovgl %edi, %eax
21558 // cmovsl %eax, %edi
21559 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21560 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21561 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21562 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21567 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21568 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21569 Cond.getOperand(0), Cond.getOperand(1), NewCC);
21570 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21575 // Early exit check
21576 if (!TLI.isTypeLegal(VT))
21579 // Match VSELECTs into subs with unsigned saturation.
21580 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21581 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21582 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21583 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21584 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21586 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21587 // left side invert the predicate to simplify logic below.
21589 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21591 CC = ISD::getSetCCInverse(CC, true);
21592 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21596 if (Other.getNode() && Other->getNumOperands() == 2 &&
21597 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21598 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21599 SDValue CondRHS = Cond->getOperand(1);
21601 // Look for a general sub with unsigned saturation first.
21602 // x >= y ? x-y : 0 --> subus x, y
21603 // x > y ? x-y : 0 --> subus x, y
21604 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21605 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21606 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21608 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21609 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21610 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21611 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21612 // If the RHS is a constant we have to reverse the const
21613 // canonicalization.
21614 // x > C-1 ? x+-C : 0 --> subus x, C
21615 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21616 CondRHSConst->getAPIntValue() ==
21617 (-OpRHSConst->getAPIntValue() - 1))
21618 return DAG.getNode(
21619 X86ISD::SUBUS, DL, VT, OpLHS,
21620 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21622 // Another special case: If C was a sign bit, the sub has been
21623 // canonicalized into a xor.
21624 // FIXME: Would it be better to use computeKnownBits to determine
21625 // whether it's safe to decanonicalize the xor?
21626 // x s< 0 ? x^C : 0 --> subus x, C
21627 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21628 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21629 OpRHSConst->getAPIntValue().isSignBit())
21630 // Note that we have to rebuild the RHS constant here to ensure we
21631 // don't rely on particular values of undef lanes.
21632 return DAG.getNode(
21633 X86ISD::SUBUS, DL, VT, OpLHS,
21634 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21639 // Try to match a min/max vector operation.
21640 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21641 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21642 unsigned Opc = ret.first;
21643 bool NeedSplit = ret.second;
21645 if (Opc && NeedSplit) {
21646 unsigned NumElems = VT.getVectorNumElements();
21647 // Extract the LHS vectors
21648 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21649 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21651 // Extract the RHS vectors
21652 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21653 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21655 // Create min/max for each subvector
21656 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21657 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21659 // Merge the result
21660 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21662 return DAG.getNode(Opc, DL, VT, LHS, RHS);
21665 // Simplify vector selection if condition value type matches vselect
21667 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21668 assert(Cond.getValueType().isVector() &&
21669 "vector select expects a vector selector!");
21671 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21672 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21674 // Try invert the condition if true value is not all 1s and false value
21676 if (!TValIsAllOnes && !FValIsAllZeros &&
21677 // Check if the selector will be produced by CMPP*/PCMP*
21678 Cond.getOpcode() == ISD::SETCC &&
21679 // Check if SETCC has already been promoted
21680 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21681 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21682 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21684 if (TValIsAllZeros || FValIsAllOnes) {
21685 SDValue CC = Cond.getOperand(2);
21686 ISD::CondCode NewCC =
21687 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21688 Cond.getOperand(0).getValueType().isInteger());
21689 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21690 std::swap(LHS, RHS);
21691 TValIsAllOnes = FValIsAllOnes;
21692 FValIsAllZeros = TValIsAllZeros;
21696 if (TValIsAllOnes || FValIsAllZeros) {
21699 if (TValIsAllOnes && FValIsAllZeros)
21701 else if (TValIsAllOnes)
21702 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21703 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21704 else if (FValIsAllZeros)
21705 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21706 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21708 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21712 // We should generate an X86ISD::BLENDI from a vselect if its argument
21713 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21714 // constants. This specific pattern gets generated when we split a
21715 // selector for a 512 bit vector in a machine without AVX512 (but with
21716 // 256-bit vectors), during legalization:
21718 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21720 // Iff we find this pattern and the build_vectors are built from
21721 // constants, we translate the vselect into a shuffle_vector that we
21722 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21723 if ((N->getOpcode() == ISD::VSELECT ||
21724 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21725 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
21726 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21727 if (Shuffle.getNode())
21731 // If this is a *dynamic* select (non-constant condition) and we can match
21732 // this node with one of the variable blend instructions, restructure the
21733 // condition so that the blends can use the high bit of each element and use
21734 // SimplifyDemandedBits to simplify the condition operand.
21735 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21736 !DCI.isBeforeLegalize() &&
21737 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21738 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21740 // Don't optimize vector selects that map to mask-registers.
21744 // We can only handle the cases where VSELECT is directly legal on the
21745 // subtarget. We custom lower VSELECT nodes with constant conditions and
21746 // this makes it hard to see whether a dynamic VSELECT will correctly
21747 // lower, so we both check the operation's status and explicitly handle the
21748 // cases where a *dynamic* blend will fail even though a constant-condition
21749 // blend could be custom lowered.
21750 // FIXME: We should find a better way to handle this class of problems.
21751 // Potentially, we should combine constant-condition vselect nodes
21752 // pre-legalization into shuffles and not mark as many types as custom
21754 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21756 // FIXME: We don't support i16-element blends currently. We could and
21757 // should support them by making *all* the bits in the condition be set
21758 // rather than just the high bit and using an i8-element blend.
21759 if (VT.getScalarType() == MVT::i16)
21761 // Dynamic blending was only available from SSE4.1 onward.
21762 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21764 // Byte blends are only available in AVX2
21765 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21766 !Subtarget->hasAVX2())
21769 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21770 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21772 APInt KnownZero, KnownOne;
21773 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21774 DCI.isBeforeLegalizeOps());
21775 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21776 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21778 // If we changed the computation somewhere in the DAG, this change
21779 // will affect all users of Cond.
21780 // Make sure it is fine and update all the nodes so that we do not
21781 // use the generic VSELECT anymore. Otherwise, we may perform
21782 // wrong optimizations as we messed up with the actual expectation
21783 // for the vector boolean values.
21784 if (Cond != TLO.Old) {
21785 // Check all uses of that condition operand to check whether it will be
21786 // consumed by non-BLEND instructions, which may depend on all bits are
21788 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21790 if (I->getOpcode() != ISD::VSELECT)
21791 // TODO: Add other opcodes eventually lowered into BLEND.
21794 // Update all the users of the condition, before committing the change,
21795 // so that the VSELECT optimizations that expect the correct vector
21796 // boolean value will not be triggered.
21797 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21799 DAG.ReplaceAllUsesOfValueWith(
21801 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21802 Cond, I->getOperand(1), I->getOperand(2)));
21803 DCI.CommitTargetLoweringOpt(TLO);
21806 // At this point, only Cond is changed. Change the condition
21807 // just for N to keep the opportunity to optimize all other
21808 // users their own way.
21809 DAG.ReplaceAllUsesOfValueWith(
21811 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21812 TLO.New, N->getOperand(1), N->getOperand(2)));
21820 // Check whether a boolean test is testing a boolean value generated by
21821 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21824 // Simplify the following patterns:
21825 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21826 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21827 // to (Op EFLAGS Cond)
21829 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21830 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21831 // to (Op EFLAGS !Cond)
21833 // where Op could be BRCOND or CMOV.
21835 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21836 // Quit if not CMP and SUB with its value result used.
21837 if (Cmp.getOpcode() != X86ISD::CMP &&
21838 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21841 // Quit if not used as a boolean value.
21842 if (CC != X86::COND_E && CC != X86::COND_NE)
21845 // Check CMP operands. One of them should be 0 or 1 and the other should be
21846 // an SetCC or extended from it.
21847 SDValue Op1 = Cmp.getOperand(0);
21848 SDValue Op2 = Cmp.getOperand(1);
21851 const ConstantSDNode* C = nullptr;
21852 bool needOppositeCond = (CC == X86::COND_E);
21853 bool checkAgainstTrue = false; // Is it a comparison against 1?
21855 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21857 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21859 else // Quit if all operands are not constants.
21862 if (C->getZExtValue() == 1) {
21863 needOppositeCond = !needOppositeCond;
21864 checkAgainstTrue = true;
21865 } else if (C->getZExtValue() != 0)
21866 // Quit if the constant is neither 0 or 1.
21869 bool truncatedToBoolWithAnd = false;
21870 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21871 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21872 SetCC.getOpcode() == ISD::TRUNCATE ||
21873 SetCC.getOpcode() == ISD::AND) {
21874 if (SetCC.getOpcode() == ISD::AND) {
21876 ConstantSDNode *CS;
21877 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21878 CS->getZExtValue() == 1)
21880 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21881 CS->getZExtValue() == 1)
21885 SetCC = SetCC.getOperand(OpIdx);
21886 truncatedToBoolWithAnd = true;
21888 SetCC = SetCC.getOperand(0);
21891 switch (SetCC.getOpcode()) {
21892 case X86ISD::SETCC_CARRY:
21893 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21894 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21895 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21896 // truncated to i1 using 'and'.
21897 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21899 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21900 "Invalid use of SETCC_CARRY!");
21902 case X86ISD::SETCC:
21903 // Set the condition code or opposite one if necessary.
21904 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21905 if (needOppositeCond)
21906 CC = X86::GetOppositeBranchCondition(CC);
21907 return SetCC.getOperand(1);
21908 case X86ISD::CMOV: {
21909 // Check whether false/true value has canonical one, i.e. 0 or 1.
21910 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21911 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21912 // Quit if true value is not a constant.
21915 // Quit if false value is not a constant.
21917 SDValue Op = SetCC.getOperand(0);
21918 // Skip 'zext' or 'trunc' node.
21919 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21920 Op.getOpcode() == ISD::TRUNCATE)
21921 Op = Op.getOperand(0);
21922 // A special case for rdrand/rdseed, where 0 is set if false cond is
21924 if ((Op.getOpcode() != X86ISD::RDRAND &&
21925 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21928 // Quit if false value is not the constant 0 or 1.
21929 bool FValIsFalse = true;
21930 if (FVal && FVal->getZExtValue() != 0) {
21931 if (FVal->getZExtValue() != 1)
21933 // If FVal is 1, opposite cond is needed.
21934 needOppositeCond = !needOppositeCond;
21935 FValIsFalse = false;
21937 // Quit if TVal is not the constant opposite of FVal.
21938 if (FValIsFalse && TVal->getZExtValue() != 1)
21940 if (!FValIsFalse && TVal->getZExtValue() != 0)
21942 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21943 if (needOppositeCond)
21944 CC = X86::GetOppositeBranchCondition(CC);
21945 return SetCC.getOperand(3);
21952 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21954 /// (X86or (X86setcc) (X86setcc))
21955 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21956 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21957 X86::CondCode &CC1, SDValue &Flags,
21959 if (Cond->getOpcode() == X86ISD::CMP) {
21960 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21961 if (!CondOp1C || !CondOp1C->isNullValue())
21964 Cond = Cond->getOperand(0);
21969 SDValue SetCC0, SetCC1;
21970 switch (Cond->getOpcode()) {
21971 default: return false;
21978 SetCC0 = Cond->getOperand(0);
21979 SetCC1 = Cond->getOperand(1);
21983 // Make sure we have SETCC nodes, using the same flags value.
21984 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21985 SetCC1.getOpcode() != X86ISD::SETCC ||
21986 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21989 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21990 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21991 Flags = SetCC0->getOperand(1);
21995 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21996 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21997 TargetLowering::DAGCombinerInfo &DCI,
21998 const X86Subtarget *Subtarget) {
22001 // If the flag operand isn't dead, don't touch this CMOV.
22002 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22005 SDValue FalseOp = N->getOperand(0);
22006 SDValue TrueOp = N->getOperand(1);
22007 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22008 SDValue Cond = N->getOperand(3);
22010 if (CC == X86::COND_E || CC == X86::COND_NE) {
22011 switch (Cond.getOpcode()) {
22015 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22016 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22017 return (CC == X86::COND_E) ? FalseOp : TrueOp;
22023 Flags = checkBoolTestSetCCCombine(Cond, CC);
22024 if (Flags.getNode() &&
22025 // Extra check as FCMOV only supports a subset of X86 cond.
22026 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22027 SDValue Ops[] = { FalseOp, TrueOp,
22028 DAG.getConstant(CC, DL, MVT::i8), Flags };
22029 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22032 // If this is a select between two integer constants, try to do some
22033 // optimizations. Note that the operands are ordered the opposite of SELECT
22035 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22036 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22037 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22038 // larger than FalseC (the false value).
22039 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22040 CC = X86::GetOppositeBranchCondition(CC);
22041 std::swap(TrueC, FalseC);
22042 std::swap(TrueOp, FalseOp);
22045 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
22046 // This is efficient for any integer data type (including i8/i16) and
22048 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22049 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22050 DAG.getConstant(CC, DL, MVT::i8), Cond);
22052 // Zero extend the condition if needed.
22053 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22055 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22056 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22057 DAG.getConstant(ShAmt, DL, MVT::i8));
22058 if (N->getNumValues() == 2) // Dead flag value?
22059 return DCI.CombineTo(N, Cond, SDValue());
22063 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
22064 // for any integer data type, including i8/i16.
22065 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22066 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22067 DAG.getConstant(CC, DL, MVT::i8), Cond);
22069 // Zero extend the condition if needed.
22070 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22071 FalseC->getValueType(0), Cond);
22072 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22073 SDValue(FalseC, 0));
22075 if (N->getNumValues() == 2) // Dead flag value?
22076 return DCI.CombineTo(N, Cond, SDValue());
22080 // Optimize cases that will turn into an LEA instruction. This requires
22081 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22082 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22083 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22084 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22086 bool isFastMultiplier = false;
22088 switch ((unsigned char)Diff) {
22090 case 1: // result = add base, cond
22091 case 2: // result = lea base( , cond*2)
22092 case 3: // result = lea base(cond, cond*2)
22093 case 4: // result = lea base( , cond*4)
22094 case 5: // result = lea base(cond, cond*4)
22095 case 8: // result = lea base( , cond*8)
22096 case 9: // result = lea base(cond, cond*8)
22097 isFastMultiplier = true;
22102 if (isFastMultiplier) {
22103 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22104 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22105 DAG.getConstant(CC, DL, MVT::i8), Cond);
22106 // Zero extend the condition if needed.
22107 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22109 // Scale the condition by the difference.
22111 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22112 DAG.getConstant(Diff, DL, Cond.getValueType()));
22114 // Add the base if non-zero.
22115 if (FalseC->getAPIntValue() != 0)
22116 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22117 SDValue(FalseC, 0));
22118 if (N->getNumValues() == 2) // Dead flag value?
22119 return DCI.CombineTo(N, Cond, SDValue());
22126 // Handle these cases:
22127 // (select (x != c), e, c) -> select (x != c), e, x),
22128 // (select (x == c), c, e) -> select (x == c), x, e)
22129 // where the c is an integer constant, and the "select" is the combination
22130 // of CMOV and CMP.
22132 // The rationale for this change is that the conditional-move from a constant
22133 // needs two instructions, however, conditional-move from a register needs
22134 // only one instruction.
22136 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22137 // some instruction-combining opportunities. This opt needs to be
22138 // postponed as late as possible.
22140 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22141 // the DCI.xxxx conditions are provided to postpone the optimization as
22142 // late as possible.
22144 ConstantSDNode *CmpAgainst = nullptr;
22145 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22146 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22147 !isa<ConstantSDNode>(Cond.getOperand(0))) {
22149 if (CC == X86::COND_NE &&
22150 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22151 CC = X86::GetOppositeBranchCondition(CC);
22152 std::swap(TrueOp, FalseOp);
22155 if (CC == X86::COND_E &&
22156 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22157 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22158 DAG.getConstant(CC, DL, MVT::i8), Cond };
22159 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22164 // Fold and/or of setcc's to double CMOV:
22165 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22166 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22168 // This combine lets us generate:
22169 // cmovcc1 (jcc1 if we don't have CMOV)
22175 // cmovne (jne if we don't have CMOV)
22176 // When we can't use the CMOV instruction, it might increase branch
22178 // When we can use CMOV, or when there is no mispredict, this improves
22179 // throughput and reduces register pressure.
22181 if (CC == X86::COND_NE) {
22183 X86::CondCode CC0, CC1;
22185 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22187 std::swap(FalseOp, TrueOp);
22188 CC0 = X86::GetOppositeBranchCondition(CC0);
22189 CC1 = X86::GetOppositeBranchCondition(CC1);
22192 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22194 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22195 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22196 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22197 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22205 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22206 const X86Subtarget *Subtarget) {
22207 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22209 default: return SDValue();
22210 // SSE/AVX/AVX2 blend intrinsics.
22211 case Intrinsic::x86_avx2_pblendvb:
22212 // Don't try to simplify this intrinsic if we don't have AVX2.
22213 if (!Subtarget->hasAVX2())
22216 case Intrinsic::x86_avx_blendv_pd_256:
22217 case Intrinsic::x86_avx_blendv_ps_256:
22218 // Don't try to simplify this intrinsic if we don't have AVX.
22219 if (!Subtarget->hasAVX())
22222 case Intrinsic::x86_sse41_blendvps:
22223 case Intrinsic::x86_sse41_blendvpd:
22224 case Intrinsic::x86_sse41_pblendvb: {
22225 SDValue Op0 = N->getOperand(1);
22226 SDValue Op1 = N->getOperand(2);
22227 SDValue Mask = N->getOperand(3);
22229 // Don't try to simplify this intrinsic if we don't have SSE4.1.
22230 if (!Subtarget->hasSSE41())
22233 // fold (blend A, A, Mask) -> A
22236 // fold (blend A, B, allZeros) -> A
22237 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22239 // fold (blend A, B, allOnes) -> B
22240 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22243 // Simplify the case where the mask is a constant i32 value.
22244 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22245 if (C->isNullValue())
22247 if (C->isAllOnesValue())
22254 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22255 case Intrinsic::x86_sse2_psrai_w:
22256 case Intrinsic::x86_sse2_psrai_d:
22257 case Intrinsic::x86_avx2_psrai_w:
22258 case Intrinsic::x86_avx2_psrai_d:
22259 case Intrinsic::x86_sse2_psra_w:
22260 case Intrinsic::x86_sse2_psra_d:
22261 case Intrinsic::x86_avx2_psra_w:
22262 case Intrinsic::x86_avx2_psra_d: {
22263 SDValue Op0 = N->getOperand(1);
22264 SDValue Op1 = N->getOperand(2);
22265 EVT VT = Op0.getValueType();
22266 assert(VT.isVector() && "Expected a vector type!");
22268 if (isa<BuildVectorSDNode>(Op1))
22269 Op1 = Op1.getOperand(0);
22271 if (!isa<ConstantSDNode>(Op1))
22274 EVT SVT = VT.getVectorElementType();
22275 unsigned SVTBits = SVT.getSizeInBits();
22277 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22278 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22279 uint64_t ShAmt = C.getZExtValue();
22281 // Don't try to convert this shift into a ISD::SRA if the shift
22282 // count is bigger than or equal to the element size.
22283 if (ShAmt >= SVTBits)
22286 // Trivial case: if the shift count is zero, then fold this
22287 // into the first operand.
22291 // Replace this packed shift intrinsic with a target independent
22294 SDValue Splat = DAG.getConstant(C, DL, VT);
22295 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22300 /// PerformMulCombine - Optimize a single multiply with constant into two
22301 /// in order to implement it with two cheaper instructions, e.g.
22302 /// LEA + SHL, LEA + LEA.
22303 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22304 TargetLowering::DAGCombinerInfo &DCI) {
22305 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22308 EVT VT = N->getValueType(0);
22309 if (VT != MVT::i64 && VT != MVT::i32)
22312 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22315 uint64_t MulAmt = C->getZExtValue();
22316 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22319 uint64_t MulAmt1 = 0;
22320 uint64_t MulAmt2 = 0;
22321 if ((MulAmt % 9) == 0) {
22323 MulAmt2 = MulAmt / 9;
22324 } else if ((MulAmt % 5) == 0) {
22326 MulAmt2 = MulAmt / 5;
22327 } else if ((MulAmt % 3) == 0) {
22329 MulAmt2 = MulAmt / 3;
22332 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22335 if (isPowerOf2_64(MulAmt2) &&
22336 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22337 // If second multiplifer is pow2, issue it first. We want the multiply by
22338 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22340 std::swap(MulAmt1, MulAmt2);
22343 if (isPowerOf2_64(MulAmt1))
22344 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22345 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22347 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22348 DAG.getConstant(MulAmt1, DL, VT));
22350 if (isPowerOf2_64(MulAmt2))
22351 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22352 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22354 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22355 DAG.getConstant(MulAmt2, DL, VT));
22357 // Do not add new nodes to DAG combiner worklist.
22358 DCI.CombineTo(N, NewMul, false);
22363 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22364 SDValue N0 = N->getOperand(0);
22365 SDValue N1 = N->getOperand(1);
22366 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22367 EVT VT = N0.getValueType();
22369 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22370 // since the result of setcc_c is all zero's or all ones.
22371 if (VT.isInteger() && !VT.isVector() &&
22372 N1C && N0.getOpcode() == ISD::AND &&
22373 N0.getOperand(1).getOpcode() == ISD::Constant) {
22374 SDValue N00 = N0.getOperand(0);
22375 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22376 ((N00.getOpcode() == ISD::ANY_EXTEND ||
22377 N00.getOpcode() == ISD::ZERO_EXTEND) &&
22378 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22379 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22380 APInt ShAmt = N1C->getAPIntValue();
22381 Mask = Mask.shl(ShAmt);
22384 return DAG.getNode(ISD::AND, DL, VT,
22385 N00, DAG.getConstant(Mask, DL, VT));
22390 // Hardware support for vector shifts is sparse which makes us scalarize the
22391 // vector operations in many cases. Also, on sandybridge ADD is faster than
22393 // (shl V, 1) -> add V,V
22394 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22395 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22396 assert(N0.getValueType().isVector() && "Invalid vector shift type");
22397 // We shift all of the values by one. In many cases we do not have
22398 // hardware support for this operation. This is better expressed as an ADD
22400 if (N1SplatC->getZExtValue() == 1)
22401 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22407 /// \brief Returns a vector of 0s if the node in input is a vector logical
22408 /// shift by a constant amount which is known to be bigger than or equal
22409 /// to the vector element size in bits.
22410 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22411 const X86Subtarget *Subtarget) {
22412 EVT VT = N->getValueType(0);
22414 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22415 (!Subtarget->hasInt256() ||
22416 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22419 SDValue Amt = N->getOperand(1);
22421 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22422 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22423 APInt ShiftAmt = AmtSplat->getAPIntValue();
22424 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22426 // SSE2/AVX2 logical shifts always return a vector of 0s
22427 // if the shift amount is bigger than or equal to
22428 // the element size. The constant shift amount will be
22429 // encoded as a 8-bit immediate.
22430 if (ShiftAmt.trunc(8).uge(MaxAmount))
22431 return getZeroVector(VT, Subtarget, DAG, DL);
22437 /// PerformShiftCombine - Combine shifts.
22438 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22439 TargetLowering::DAGCombinerInfo &DCI,
22440 const X86Subtarget *Subtarget) {
22441 if (N->getOpcode() == ISD::SHL) {
22442 SDValue V = PerformSHLCombine(N, DAG);
22443 if (V.getNode()) return V;
22446 if (N->getOpcode() != ISD::SRA) {
22447 // Try to fold this logical shift into a zero vector.
22448 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22449 if (V.getNode()) return V;
22455 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
22456 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22457 // and friends. Likewise for OR -> CMPNEQSS.
22458 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22459 TargetLowering::DAGCombinerInfo &DCI,
22460 const X86Subtarget *Subtarget) {
22463 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22464 // we're requiring SSE2 for both.
22465 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22466 SDValue N0 = N->getOperand(0);
22467 SDValue N1 = N->getOperand(1);
22468 SDValue CMP0 = N0->getOperand(1);
22469 SDValue CMP1 = N1->getOperand(1);
22472 // The SETCCs should both refer to the same CMP.
22473 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22476 SDValue CMP00 = CMP0->getOperand(0);
22477 SDValue CMP01 = CMP0->getOperand(1);
22478 EVT VT = CMP00.getValueType();
22480 if (VT == MVT::f32 || VT == MVT::f64) {
22481 bool ExpectingFlags = false;
22482 // Check for any users that want flags:
22483 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22484 !ExpectingFlags && UI != UE; ++UI)
22485 switch (UI->getOpcode()) {
22490 ExpectingFlags = true;
22492 case ISD::CopyToReg:
22493 case ISD::SIGN_EXTEND:
22494 case ISD::ZERO_EXTEND:
22495 case ISD::ANY_EXTEND:
22499 if (!ExpectingFlags) {
22500 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22501 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22503 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22504 X86::CondCode tmp = cc0;
22509 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
22510 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22511 // FIXME: need symbolic constants for these magic numbers.
22512 // See X86ATTInstPrinter.cpp:printSSECC().
22513 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22514 if (Subtarget->hasAVX512()) {
22515 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22517 DAG.getConstant(x86cc, DL, MVT::i8));
22518 if (N->getValueType(0) != MVT::i1)
22519 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22523 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22524 CMP00.getValueType(), CMP00, CMP01,
22525 DAG.getConstant(x86cc, DL,
22528 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22529 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22531 if (is64BitFP && !Subtarget->is64Bit()) {
22532 // On a 32-bit target, we cannot bitcast the 64-bit float to a
22533 // 64-bit integer, since that's not a legal type. Since
22534 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22535 // bits, but can do this little dance to extract the lowest 32 bits
22536 // and work with those going forward.
22537 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22539 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22541 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22542 Vector32, DAG.getIntPtrConstant(0, DL));
22546 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22548 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22549 DAG.getConstant(1, DL, IntVT));
22550 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22552 return OneBitOfTruth;
22560 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22561 /// so it can be folded inside ANDNP.
22562 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22563 EVT VT = N->getValueType(0);
22565 // Match direct AllOnes for 128 and 256-bit vectors
22566 if (ISD::isBuildVectorAllOnes(N))
22569 // Look through a bit convert.
22570 if (N->getOpcode() == ISD::BITCAST)
22571 N = N->getOperand(0).getNode();
22573 // Sometimes the operand may come from a insert_subvector building a 256-bit
22575 if (VT.is256BitVector() &&
22576 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22577 SDValue V1 = N->getOperand(0);
22578 SDValue V2 = N->getOperand(1);
22580 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22581 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22582 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22583 ISD::isBuildVectorAllOnes(V2.getNode()))
22590 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22591 // register. In most cases we actually compare or select YMM-sized registers
22592 // and mixing the two types creates horrible code. This method optimizes
22593 // some of the transition sequences.
22594 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22595 TargetLowering::DAGCombinerInfo &DCI,
22596 const X86Subtarget *Subtarget) {
22597 EVT VT = N->getValueType(0);
22598 if (!VT.is256BitVector())
22601 assert((N->getOpcode() == ISD::ANY_EXTEND ||
22602 N->getOpcode() == ISD::ZERO_EXTEND ||
22603 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22605 SDValue Narrow = N->getOperand(0);
22606 EVT NarrowVT = Narrow->getValueType(0);
22607 if (!NarrowVT.is128BitVector())
22610 if (Narrow->getOpcode() != ISD::XOR &&
22611 Narrow->getOpcode() != ISD::AND &&
22612 Narrow->getOpcode() != ISD::OR)
22615 SDValue N0 = Narrow->getOperand(0);
22616 SDValue N1 = Narrow->getOperand(1);
22619 // The Left side has to be a trunc.
22620 if (N0.getOpcode() != ISD::TRUNCATE)
22623 // The type of the truncated inputs.
22624 EVT WideVT = N0->getOperand(0)->getValueType(0);
22628 // The right side has to be a 'trunc' or a constant vector.
22629 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22630 ConstantSDNode *RHSConstSplat = nullptr;
22631 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22632 RHSConstSplat = RHSBV->getConstantSplatNode();
22633 if (!RHSTrunc && !RHSConstSplat)
22636 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22638 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22641 // Set N0 and N1 to hold the inputs to the new wide operation.
22642 N0 = N0->getOperand(0);
22643 if (RHSConstSplat) {
22644 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22645 SDValue(RHSConstSplat, 0));
22646 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22647 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22648 } else if (RHSTrunc) {
22649 N1 = N1->getOperand(0);
22652 // Generate the wide operation.
22653 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22654 unsigned Opcode = N->getOpcode();
22656 case ISD::ANY_EXTEND:
22658 case ISD::ZERO_EXTEND: {
22659 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22660 APInt Mask = APInt::getAllOnesValue(InBits);
22661 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22662 return DAG.getNode(ISD::AND, DL, VT,
22663 Op, DAG.getConstant(Mask, DL, VT));
22665 case ISD::SIGN_EXTEND:
22666 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22667 Op, DAG.getValueType(NarrowVT));
22669 llvm_unreachable("Unexpected opcode");
22673 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22674 TargetLowering::DAGCombinerInfo &DCI,
22675 const X86Subtarget *Subtarget) {
22676 SDValue N0 = N->getOperand(0);
22677 SDValue N1 = N->getOperand(1);
22680 // A vector zext_in_reg may be represented as a shuffle,
22681 // feeding into a bitcast (this represents anyext) feeding into
22682 // an and with a mask.
22683 // We'd like to try to combine that into a shuffle with zero
22684 // plus a bitcast, removing the and.
22685 if (N0.getOpcode() != ISD::BITCAST ||
22686 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22689 // The other side of the AND should be a splat of 2^C, where C
22690 // is the number of bits in the source type.
22691 if (N1.getOpcode() == ISD::BITCAST)
22692 N1 = N1.getOperand(0);
22693 if (N1.getOpcode() != ISD::BUILD_VECTOR)
22695 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22697 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22698 EVT SrcType = Shuffle->getValueType(0);
22700 // We expect a single-source shuffle
22701 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22704 unsigned SrcSize = SrcType.getScalarSizeInBits();
22706 APInt SplatValue, SplatUndef;
22707 unsigned SplatBitSize;
22709 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22710 SplatBitSize, HasAnyUndefs))
22713 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22714 // Make sure the splat matches the mask we expect
22715 if (SplatBitSize > ResSize ||
22716 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22719 // Make sure the input and output size make sense
22720 if (SrcSize >= ResSize || ResSize % SrcSize)
22723 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22724 // The number of u's between each two values depends on the ratio between
22725 // the source and dest type.
22726 unsigned ZextRatio = ResSize / SrcSize;
22727 bool IsZext = true;
22728 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22729 if (i % ZextRatio) {
22730 if (Shuffle->getMaskElt(i) > 0) {
22736 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22737 // Expected element number
22747 // Ok, perform the transformation - replace the shuffle with
22748 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22749 // (instead of undef) where the k elements come from the zero vector.
22750 SmallVector<int, 8> Mask;
22751 unsigned NumElems = SrcType.getVectorNumElements();
22752 for (unsigned i = 0; i < NumElems; ++i)
22754 Mask.push_back(NumElems);
22756 Mask.push_back(i / ZextRatio);
22758 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22759 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22760 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22763 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22764 TargetLowering::DAGCombinerInfo &DCI,
22765 const X86Subtarget *Subtarget) {
22766 if (DCI.isBeforeLegalizeOps())
22769 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22772 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22775 EVT VT = N->getValueType(0);
22776 SDValue N0 = N->getOperand(0);
22777 SDValue N1 = N->getOperand(1);
22780 // Create BEXTR instructions
22781 // BEXTR is ((X >> imm) & (2**size-1))
22782 if (VT == MVT::i32 || VT == MVT::i64) {
22783 // Check for BEXTR.
22784 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22785 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22786 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22787 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22788 if (MaskNode && ShiftNode) {
22789 uint64_t Mask = MaskNode->getZExtValue();
22790 uint64_t Shift = ShiftNode->getZExtValue();
22791 if (isMask_64(Mask)) {
22792 uint64_t MaskSize = countPopulation(Mask);
22793 if (Shift + MaskSize <= VT.getSizeInBits())
22794 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22795 DAG.getConstant(Shift | (MaskSize << 8), DL,
22804 // Want to form ANDNP nodes:
22805 // 1) In the hopes of then easily combining them with OR and AND nodes
22806 // to form PBLEND/PSIGN.
22807 // 2) To match ANDN packed intrinsics
22808 if (VT != MVT::v2i64 && VT != MVT::v4i64)
22811 // Check LHS for vnot
22812 if (N0.getOpcode() == ISD::XOR &&
22813 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22814 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22815 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22817 // Check RHS for vnot
22818 if (N1.getOpcode() == ISD::XOR &&
22819 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22820 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22821 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22826 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22827 TargetLowering::DAGCombinerInfo &DCI,
22828 const X86Subtarget *Subtarget) {
22829 if (DCI.isBeforeLegalizeOps())
22832 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22836 SDValue N0 = N->getOperand(0);
22837 SDValue N1 = N->getOperand(1);
22838 EVT VT = N->getValueType(0);
22840 // look for psign/blend
22841 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22842 if (!Subtarget->hasSSSE3() ||
22843 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22846 // Canonicalize pandn to RHS
22847 if (N0.getOpcode() == X86ISD::ANDNP)
22849 // or (and (m, y), (pandn m, x))
22850 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22851 SDValue Mask = N1.getOperand(0);
22852 SDValue X = N1.getOperand(1);
22854 if (N0.getOperand(0) == Mask)
22855 Y = N0.getOperand(1);
22856 if (N0.getOperand(1) == Mask)
22857 Y = N0.getOperand(0);
22859 // Check to see if the mask appeared in both the AND and ANDNP and
22863 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22864 // Look through mask bitcast.
22865 if (Mask.getOpcode() == ISD::BITCAST)
22866 Mask = Mask.getOperand(0);
22867 if (X.getOpcode() == ISD::BITCAST)
22868 X = X.getOperand(0);
22869 if (Y.getOpcode() == ISD::BITCAST)
22870 Y = Y.getOperand(0);
22872 EVT MaskVT = Mask.getValueType();
22874 // Validate that the Mask operand is a vector sra node.
22875 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22876 // there is no psrai.b
22877 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22878 unsigned SraAmt = ~0;
22879 if (Mask.getOpcode() == ISD::SRA) {
22880 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22881 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22882 SraAmt = AmtConst->getZExtValue();
22883 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22884 SDValue SraC = Mask.getOperand(1);
22885 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22887 if ((SraAmt + 1) != EltBits)
22892 // Now we know we at least have a plendvb with the mask val. See if
22893 // we can form a psignb/w/d.
22894 // psign = x.type == y.type == mask.type && y = sub(0, x);
22895 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22896 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22897 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22898 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22899 "Unsupported VT for PSIGN");
22900 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22901 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22903 // PBLENDVB only available on SSE 4.1
22904 if (!Subtarget->hasSSE41())
22907 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22909 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22910 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22911 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22912 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22913 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22917 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22920 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22921 MachineFunction &MF = DAG.getMachineFunction();
22923 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22925 // SHLD/SHRD instructions have lower register pressure, but on some
22926 // platforms they have higher latency than the equivalent
22927 // series of shifts/or that would otherwise be generated.
22928 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22929 // have higher latencies and we are not optimizing for size.
22930 if (!OptForSize && Subtarget->isSHLDSlow())
22933 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22935 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22937 if (!N0.hasOneUse() || !N1.hasOneUse())
22940 SDValue ShAmt0 = N0.getOperand(1);
22941 if (ShAmt0.getValueType() != MVT::i8)
22943 SDValue ShAmt1 = N1.getOperand(1);
22944 if (ShAmt1.getValueType() != MVT::i8)
22946 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22947 ShAmt0 = ShAmt0.getOperand(0);
22948 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22949 ShAmt1 = ShAmt1.getOperand(0);
22952 unsigned Opc = X86ISD::SHLD;
22953 SDValue Op0 = N0.getOperand(0);
22954 SDValue Op1 = N1.getOperand(0);
22955 if (ShAmt0.getOpcode() == ISD::SUB) {
22956 Opc = X86ISD::SHRD;
22957 std::swap(Op0, Op1);
22958 std::swap(ShAmt0, ShAmt1);
22961 unsigned Bits = VT.getSizeInBits();
22962 if (ShAmt1.getOpcode() == ISD::SUB) {
22963 SDValue Sum = ShAmt1.getOperand(0);
22964 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22965 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22966 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22967 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22968 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22969 return DAG.getNode(Opc, DL, VT,
22971 DAG.getNode(ISD::TRUNCATE, DL,
22974 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22975 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22977 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22978 return DAG.getNode(Opc, DL, VT,
22979 N0.getOperand(0), N1.getOperand(0),
22980 DAG.getNode(ISD::TRUNCATE, DL,
22987 // Generate NEG and CMOV for integer abs.
22988 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22989 EVT VT = N->getValueType(0);
22991 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22992 // 8-bit integer abs to NEG and CMOV.
22993 if (VT.isInteger() && VT.getSizeInBits() == 8)
22996 SDValue N0 = N->getOperand(0);
22997 SDValue N1 = N->getOperand(1);
23000 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23001 // and change it to SUB and CMOV.
23002 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23003 N0.getOpcode() == ISD::ADD &&
23004 N0.getOperand(1) == N1 &&
23005 N1.getOpcode() == ISD::SRA &&
23006 N1.getOperand(0) == N0.getOperand(0))
23007 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23008 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23009 // Generate SUB & CMOV.
23010 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23011 DAG.getConstant(0, DL, VT), N0.getOperand(0));
23013 SDValue Ops[] = { N0.getOperand(0), Neg,
23014 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23015 SDValue(Neg.getNode(), 1) };
23016 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23021 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23022 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23023 TargetLowering::DAGCombinerInfo &DCI,
23024 const X86Subtarget *Subtarget) {
23025 if (DCI.isBeforeLegalizeOps())
23028 if (Subtarget->hasCMov()) {
23029 SDValue RV = performIntegerAbsCombine(N, DAG);
23037 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23038 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23039 TargetLowering::DAGCombinerInfo &DCI,
23040 const X86Subtarget *Subtarget) {
23041 LoadSDNode *Ld = cast<LoadSDNode>(N);
23042 EVT RegVT = Ld->getValueType(0);
23043 EVT MemVT = Ld->getMemoryVT();
23045 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23047 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23048 // into two 16-byte operations.
23049 ISD::LoadExtType Ext = Ld->getExtensionType();
23050 unsigned Alignment = Ld->getAlignment();
23051 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23052 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23053 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23054 unsigned NumElems = RegVT.getVectorNumElements();
23058 SDValue Ptr = Ld->getBasePtr();
23059 SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23061 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23063 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23064 Ld->getPointerInfo(), Ld->isVolatile(),
23065 Ld->isNonTemporal(), Ld->isInvariant(),
23067 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23068 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23069 Ld->getPointerInfo(), Ld->isVolatile(),
23070 Ld->isNonTemporal(), Ld->isInvariant(),
23071 std::min(16U, Alignment));
23072 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23074 Load2.getValue(1));
23076 SDValue NewVec = DAG.getUNDEF(RegVT);
23077 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23078 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23079 return DCI.CombineTo(N, NewVec, TF, true);
23085 /// PerformMLOADCombine - Resolve extending loads
23086 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23087 TargetLowering::DAGCombinerInfo &DCI,
23088 const X86Subtarget *Subtarget) {
23089 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23090 if (Mld->getExtensionType() != ISD::SEXTLOAD)
23093 EVT VT = Mld->getValueType(0);
23094 unsigned NumElems = VT.getVectorNumElements();
23095 EVT LdVT = Mld->getMemoryVT();
23098 assert(LdVT != VT && "Cannot extend to the same type");
23099 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23100 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23101 // From, To sizes and ElemCount must be pow of two
23102 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23103 "Unexpected size for extending masked load");
23105 unsigned SizeRatio = ToSz / FromSz;
23106 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23108 // Create a type on which we perform the shuffle
23109 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23110 LdVT.getScalarType(), NumElems*SizeRatio);
23111 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23113 // Convert Src0 value
23114 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
23115 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23116 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23117 for (unsigned i = 0; i != NumElems; ++i)
23118 ShuffleVec[i] = i * SizeRatio;
23120 // Can't shuffle using an illegal type.
23121 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23122 && "WideVecVT should be legal");
23123 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23124 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23126 // Prepare the new mask
23128 SDValue Mask = Mld->getMask();
23129 if (Mask.getValueType() == VT) {
23130 // Mask and original value have the same type
23131 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23132 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23133 for (unsigned i = 0; i != NumElems; ++i)
23134 ShuffleVec[i] = i * SizeRatio;
23135 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23136 ShuffleVec[i] = NumElems*SizeRatio;
23137 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23138 DAG.getConstant(0, dl, WideVecVT),
23142 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23143 unsigned WidenNumElts = NumElems*SizeRatio;
23144 unsigned MaskNumElts = VT.getVectorNumElements();
23145 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23148 unsigned NumConcat = WidenNumElts / MaskNumElts;
23149 SmallVector<SDValue, 16> Ops(NumConcat);
23150 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23152 for (unsigned i = 1; i != NumConcat; ++i)
23155 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23158 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23159 Mld->getBasePtr(), NewMask, WideSrc0,
23160 Mld->getMemoryVT(), Mld->getMemOperand(),
23162 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23163 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23166 /// PerformMSTORECombine - Resolve truncating stores
23167 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23168 const X86Subtarget *Subtarget) {
23169 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23170 if (!Mst->isTruncatingStore())
23173 EVT VT = Mst->getValue().getValueType();
23174 unsigned NumElems = VT.getVectorNumElements();
23175 EVT StVT = Mst->getMemoryVT();
23178 assert(StVT != VT && "Cannot truncate to the same type");
23179 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23180 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23182 // From, To sizes and ElemCount must be pow of two
23183 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23184 "Unexpected size for truncating masked store");
23185 // We are going to use the original vector elt for storing.
23186 // Accumulated smaller vector elements must be a multiple of the store size.
23187 assert (((NumElems * FromSz) % ToSz) == 0 &&
23188 "Unexpected ratio for truncating masked store");
23190 unsigned SizeRatio = FromSz / ToSz;
23191 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23193 // Create a type on which we perform the shuffle
23194 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23195 StVT.getScalarType(), NumElems*SizeRatio);
23197 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23199 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23200 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23201 for (unsigned i = 0; i != NumElems; ++i)
23202 ShuffleVec[i] = i * SizeRatio;
23204 // Can't shuffle using an illegal type.
23205 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23206 && "WideVecVT should be legal");
23208 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23209 DAG.getUNDEF(WideVecVT),
23213 SDValue Mask = Mst->getMask();
23214 if (Mask.getValueType() == VT) {
23215 // Mask and original value have the same type
23216 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23217 for (unsigned i = 0; i != NumElems; ++i)
23218 ShuffleVec[i] = i * SizeRatio;
23219 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23220 ShuffleVec[i] = NumElems*SizeRatio;
23221 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23222 DAG.getConstant(0, dl, WideVecVT),
23226 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23227 unsigned WidenNumElts = NumElems*SizeRatio;
23228 unsigned MaskNumElts = VT.getVectorNumElements();
23229 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23232 unsigned NumConcat = WidenNumElts / MaskNumElts;
23233 SmallVector<SDValue, 16> Ops(NumConcat);
23234 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23236 for (unsigned i = 1; i != NumConcat; ++i)
23239 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23242 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23243 NewMask, StVT, Mst->getMemOperand(), false);
23245 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23246 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23247 const X86Subtarget *Subtarget) {
23248 StoreSDNode *St = cast<StoreSDNode>(N);
23249 EVT VT = St->getValue().getValueType();
23250 EVT StVT = St->getMemoryVT();
23252 SDValue StoredVal = St->getOperand(1);
23253 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23255 // If we are saving a concatenation of two XMM registers and 32-byte stores
23256 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23257 unsigned Alignment = St->getAlignment();
23258 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23259 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23260 StVT == VT && !IsAligned) {
23261 unsigned NumElems = VT.getVectorNumElements();
23265 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23266 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23268 SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23269 SDValue Ptr0 = St->getBasePtr();
23270 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23272 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23273 St->getPointerInfo(), St->isVolatile(),
23274 St->isNonTemporal(), Alignment);
23275 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23276 St->getPointerInfo(), St->isVolatile(),
23277 St->isNonTemporal(),
23278 std::min(16U, Alignment));
23279 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23282 // Optimize trunc store (of multiple scalars) to shuffle and store.
23283 // First, pack all of the elements in one place. Next, store to memory
23284 // in fewer chunks.
23285 if (St->isTruncatingStore() && VT.isVector()) {
23286 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23287 unsigned NumElems = VT.getVectorNumElements();
23288 assert(StVT != VT && "Cannot truncate to the same type");
23289 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23290 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23292 // From, To sizes and ElemCount must be pow of two
23293 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23294 // We are going to use the original vector elt for storing.
23295 // Accumulated smaller vector elements must be a multiple of the store size.
23296 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23298 unsigned SizeRatio = FromSz / ToSz;
23300 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23302 // Create a type on which we perform the shuffle
23303 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23304 StVT.getScalarType(), NumElems*SizeRatio);
23306 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23308 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23309 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23310 for (unsigned i = 0; i != NumElems; ++i)
23311 ShuffleVec[i] = i * SizeRatio;
23313 // Can't shuffle using an illegal type.
23314 if (!TLI.isTypeLegal(WideVecVT))
23317 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23318 DAG.getUNDEF(WideVecVT),
23320 // At this point all of the data is stored at the bottom of the
23321 // register. We now need to save it to mem.
23323 // Find the largest store unit
23324 MVT StoreType = MVT::i8;
23325 for (MVT Tp : MVT::integer_valuetypes()) {
23326 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23330 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23331 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23332 (64 <= NumElems * ToSz))
23333 StoreType = MVT::f64;
23335 // Bitcast the original vector into a vector of store-size units
23336 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23337 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23338 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23339 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23340 SmallVector<SDValue, 8> Chains;
23341 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23342 TLI.getPointerTy());
23343 SDValue Ptr = St->getBasePtr();
23345 // Perform one or more big stores into memory.
23346 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23347 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23348 StoreType, ShuffWide,
23349 DAG.getIntPtrConstant(i, dl));
23350 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23351 St->getPointerInfo(), St->isVolatile(),
23352 St->isNonTemporal(), St->getAlignment());
23353 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23354 Chains.push_back(Ch);
23357 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23360 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
23361 // the FP state in cases where an emms may be missing.
23362 // A preferable solution to the general problem is to figure out the right
23363 // places to insert EMMS. This qualifies as a quick hack.
23365 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23366 if (VT.getSizeInBits() != 64)
23369 const Function *F = DAG.getMachineFunction().getFunction();
23370 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23372 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23373 if ((VT.isVector() ||
23374 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23375 isa<LoadSDNode>(St->getValue()) &&
23376 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23377 St->getChain().hasOneUse() && !St->isVolatile()) {
23378 SDNode* LdVal = St->getValue().getNode();
23379 LoadSDNode *Ld = nullptr;
23380 int TokenFactorIndex = -1;
23381 SmallVector<SDValue, 8> Ops;
23382 SDNode* ChainVal = St->getChain().getNode();
23383 // Must be a store of a load. We currently handle two cases: the load
23384 // is a direct child, and it's under an intervening TokenFactor. It is
23385 // possible to dig deeper under nested TokenFactors.
23386 if (ChainVal == LdVal)
23387 Ld = cast<LoadSDNode>(St->getChain());
23388 else if (St->getValue().hasOneUse() &&
23389 ChainVal->getOpcode() == ISD::TokenFactor) {
23390 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23391 if (ChainVal->getOperand(i).getNode() == LdVal) {
23392 TokenFactorIndex = i;
23393 Ld = cast<LoadSDNode>(St->getValue());
23395 Ops.push_back(ChainVal->getOperand(i));
23399 if (!Ld || !ISD::isNormalLoad(Ld))
23402 // If this is not the MMX case, i.e. we are just turning i64 load/store
23403 // into f64 load/store, avoid the transformation if there are multiple
23404 // uses of the loaded value.
23405 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23410 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23411 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23413 if (Subtarget->is64Bit() || F64IsLegal) {
23414 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23415 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23416 Ld->getPointerInfo(), Ld->isVolatile(),
23417 Ld->isNonTemporal(), Ld->isInvariant(),
23418 Ld->getAlignment());
23419 SDValue NewChain = NewLd.getValue(1);
23420 if (TokenFactorIndex != -1) {
23421 Ops.push_back(NewChain);
23422 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23424 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23425 St->getPointerInfo(),
23426 St->isVolatile(), St->isNonTemporal(),
23427 St->getAlignment());
23430 // Otherwise, lower to two pairs of 32-bit loads / stores.
23431 SDValue LoAddr = Ld->getBasePtr();
23432 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23433 DAG.getConstant(4, LdDL, MVT::i32));
23435 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23436 Ld->getPointerInfo(),
23437 Ld->isVolatile(), Ld->isNonTemporal(),
23438 Ld->isInvariant(), Ld->getAlignment());
23439 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23440 Ld->getPointerInfo().getWithOffset(4),
23441 Ld->isVolatile(), Ld->isNonTemporal(),
23443 MinAlign(Ld->getAlignment(), 4));
23445 SDValue NewChain = LoLd.getValue(1);
23446 if (TokenFactorIndex != -1) {
23447 Ops.push_back(LoLd);
23448 Ops.push_back(HiLd);
23449 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23452 LoAddr = St->getBasePtr();
23453 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23454 DAG.getConstant(4, StDL, MVT::i32));
23456 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23457 St->getPointerInfo(),
23458 St->isVolatile(), St->isNonTemporal(),
23459 St->getAlignment());
23460 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23461 St->getPointerInfo().getWithOffset(4),
23463 St->isNonTemporal(),
23464 MinAlign(St->getAlignment(), 4));
23465 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23468 // This is similar to the above case, but here we handle a scalar 64-bit
23469 // integer store that is extracted from a vector on a 32-bit target.
23470 // If we have SSE2, then we can treat it like a floating-point double
23471 // to get past legalization. The execution dependencies fixup pass will
23472 // choose the optimal machine instruction for the store if this really is
23473 // an integer or v2f32 rather than an f64.
23474 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23475 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23476 SDValue OldExtract = St->getOperand(1);
23477 SDValue ExtOp0 = OldExtract.getOperand(0);
23478 unsigned VecSize = ExtOp0.getValueSizeInBits();
23479 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23480 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23481 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23482 BitCast, OldExtract.getOperand(1));
23483 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23484 St->getPointerInfo(), St->isVolatile(),
23485 St->isNonTemporal(), St->getAlignment());
23491 /// Return 'true' if this vector operation is "horizontal"
23492 /// and return the operands for the horizontal operation in LHS and RHS. A
23493 /// horizontal operation performs the binary operation on successive elements
23494 /// of its first operand, then on successive elements of its second operand,
23495 /// returning the resulting values in a vector. For example, if
23496 /// A = < float a0, float a1, float a2, float a3 >
23498 /// B = < float b0, float b1, float b2, float b3 >
23499 /// then the result of doing a horizontal operation on A and B is
23500 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23501 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23502 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23503 /// set to A, RHS to B, and the routine returns 'true'.
23504 /// Note that the binary operation should have the property that if one of the
23505 /// operands is UNDEF then the result is UNDEF.
23506 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23507 // Look for the following pattern: if
23508 // A = < float a0, float a1, float a2, float a3 >
23509 // B = < float b0, float b1, float b2, float b3 >
23511 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23512 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23513 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23514 // which is A horizontal-op B.
23516 // At least one of the operands should be a vector shuffle.
23517 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23518 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23521 MVT VT = LHS.getSimpleValueType();
23523 assert((VT.is128BitVector() || VT.is256BitVector()) &&
23524 "Unsupported vector type for horizontal add/sub");
23526 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23527 // operate independently on 128-bit lanes.
23528 unsigned NumElts = VT.getVectorNumElements();
23529 unsigned NumLanes = VT.getSizeInBits()/128;
23530 unsigned NumLaneElts = NumElts / NumLanes;
23531 assert((NumLaneElts % 2 == 0) &&
23532 "Vector type should have an even number of elements in each lane");
23533 unsigned HalfLaneElts = NumLaneElts/2;
23535 // View LHS in the form
23536 // LHS = VECTOR_SHUFFLE A, B, LMask
23537 // If LHS is not a shuffle then pretend it is the shuffle
23538 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23539 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23542 SmallVector<int, 16> LMask(NumElts);
23543 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23544 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23545 A = LHS.getOperand(0);
23546 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23547 B = LHS.getOperand(1);
23548 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23549 std::copy(Mask.begin(), Mask.end(), LMask.begin());
23551 if (LHS.getOpcode() != ISD::UNDEF)
23553 for (unsigned i = 0; i != NumElts; ++i)
23557 // Likewise, view RHS in the form
23558 // RHS = VECTOR_SHUFFLE C, D, RMask
23560 SmallVector<int, 16> RMask(NumElts);
23561 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23562 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23563 C = RHS.getOperand(0);
23564 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23565 D = RHS.getOperand(1);
23566 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23567 std::copy(Mask.begin(), Mask.end(), RMask.begin());
23569 if (RHS.getOpcode() != ISD::UNDEF)
23571 for (unsigned i = 0; i != NumElts; ++i)
23575 // Check that the shuffles are both shuffling the same vectors.
23576 if (!(A == C && B == D) && !(A == D && B == C))
23579 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23580 if (!A.getNode() && !B.getNode())
23583 // If A and B occur in reverse order in RHS, then "swap" them (which means
23584 // rewriting the mask).
23586 ShuffleVectorSDNode::commuteMask(RMask);
23588 // At this point LHS and RHS are equivalent to
23589 // LHS = VECTOR_SHUFFLE A, B, LMask
23590 // RHS = VECTOR_SHUFFLE A, B, RMask
23591 // Check that the masks correspond to performing a horizontal operation.
23592 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23593 for (unsigned i = 0; i != NumLaneElts; ++i) {
23594 int LIdx = LMask[i+l], RIdx = RMask[i+l];
23596 // Ignore any UNDEF components.
23597 if (LIdx < 0 || RIdx < 0 ||
23598 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23599 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23602 // Check that successive elements are being operated on. If not, this is
23603 // not a horizontal operation.
23604 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23605 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23606 if (!(LIdx == Index && RIdx == Index + 1) &&
23607 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23612 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23613 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23617 /// Do target-specific dag combines on floating point adds.
23618 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23619 const X86Subtarget *Subtarget) {
23620 EVT VT = N->getValueType(0);
23621 SDValue LHS = N->getOperand(0);
23622 SDValue RHS = N->getOperand(1);
23624 // Try to synthesize horizontal adds from adds of shuffles.
23625 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23626 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23627 isHorizontalBinOp(LHS, RHS, true))
23628 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23632 /// Do target-specific dag combines on floating point subs.
23633 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23634 const X86Subtarget *Subtarget) {
23635 EVT VT = N->getValueType(0);
23636 SDValue LHS = N->getOperand(0);
23637 SDValue RHS = N->getOperand(1);
23639 // Try to synthesize horizontal subs from subs of shuffles.
23640 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23641 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23642 isHorizontalBinOp(LHS, RHS, false))
23643 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23647 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23648 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23649 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23651 // F[X]OR(0.0, x) -> x
23652 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23653 if (C->getValueAPF().isPosZero())
23654 return N->getOperand(1);
23656 // F[X]OR(x, 0.0) -> x
23657 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23658 if (C->getValueAPF().isPosZero())
23659 return N->getOperand(0);
23663 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23664 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23665 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23667 // Only perform optimizations if UnsafeMath is used.
23668 if (!DAG.getTarget().Options.UnsafeFPMath)
23671 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23672 // into FMINC and FMAXC, which are Commutative operations.
23673 unsigned NewOp = 0;
23674 switch (N->getOpcode()) {
23675 default: llvm_unreachable("unknown opcode");
23676 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
23677 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
23680 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23681 N->getOperand(0), N->getOperand(1));
23684 /// Do target-specific dag combines on X86ISD::FAND nodes.
23685 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23686 // FAND(0.0, x) -> 0.0
23687 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23688 if (C->getValueAPF().isPosZero())
23689 return N->getOperand(0);
23691 // FAND(x, 0.0) -> 0.0
23692 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23693 if (C->getValueAPF().isPosZero())
23694 return N->getOperand(1);
23699 /// Do target-specific dag combines on X86ISD::FANDN nodes
23700 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23701 // FANDN(0.0, x) -> x
23702 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23703 if (C->getValueAPF().isPosZero())
23704 return N->getOperand(1);
23706 // FANDN(x, 0.0) -> 0.0
23707 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23708 if (C->getValueAPF().isPosZero())
23709 return N->getOperand(1);
23714 static SDValue PerformBTCombine(SDNode *N,
23716 TargetLowering::DAGCombinerInfo &DCI) {
23717 // BT ignores high bits in the bit index operand.
23718 SDValue Op1 = N->getOperand(1);
23719 if (Op1.hasOneUse()) {
23720 unsigned BitWidth = Op1.getValueSizeInBits();
23721 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23722 APInt KnownZero, KnownOne;
23723 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23724 !DCI.isBeforeLegalizeOps());
23725 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23726 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23727 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23728 DCI.CommitTargetLoweringOpt(TLO);
23733 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23734 SDValue Op = N->getOperand(0);
23735 if (Op.getOpcode() == ISD::BITCAST)
23736 Op = Op.getOperand(0);
23737 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23738 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23739 VT.getVectorElementType().getSizeInBits() ==
23740 OpVT.getVectorElementType().getSizeInBits()) {
23741 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23746 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23747 const X86Subtarget *Subtarget) {
23748 EVT VT = N->getValueType(0);
23749 if (!VT.isVector())
23752 SDValue N0 = N->getOperand(0);
23753 SDValue N1 = N->getOperand(1);
23754 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23757 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23758 // both SSE and AVX2 since there is no sign-extended shift right
23759 // operation on a vector with 64-bit elements.
23760 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23761 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23762 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23763 N0.getOpcode() == ISD::SIGN_EXTEND)) {
23764 SDValue N00 = N0.getOperand(0);
23766 // EXTLOAD has a better solution on AVX2,
23767 // it may be replaced with X86ISD::VSEXT node.
23768 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23769 if (!ISD::isNormalLoad(N00.getNode()))
23772 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23773 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23775 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23781 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23782 TargetLowering::DAGCombinerInfo &DCI,
23783 const X86Subtarget *Subtarget) {
23784 SDValue N0 = N->getOperand(0);
23785 EVT VT = N->getValueType(0);
23786 EVT SVT = VT.getScalarType();
23787 EVT InVT = N0->getValueType(0);
23788 EVT InSVT = InVT.getScalarType();
23791 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23792 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23793 // This exposes the sext to the sdivrem lowering, so that it directly extends
23794 // from AH (which we otherwise need to do contortions to access).
23795 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23796 InVT == MVT::i8 && VT == MVT::i32) {
23797 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23798 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
23799 N0.getOperand(0), N0.getOperand(1));
23800 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23801 return R.getValue(1);
23804 if (!DCI.isBeforeLegalizeOps()) {
23805 if (N0.getValueType() == MVT::i1) {
23806 SDValue Zero = DAG.getConstant(0, DL, VT);
23808 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
23809 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
23814 if (VT.isVector()) {
23815 auto ExtendToVec128 = [&DAG](SDLoc DL, SDValue N) {
23816 EVT InVT = N->getValueType(0);
23817 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
23818 128 / InVT.getScalarSizeInBits());
23819 SmallVector<SDValue, 8> Opnds(128 / InVT.getSizeInBits(),
23820 DAG.getUNDEF(InVT));
23822 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
23825 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
23826 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
23827 if (VT.getSizeInBits() == 128 &&
23828 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23829 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23830 SDValue ExOp = ExtendToVec128(DL, N0);
23831 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
23834 // On pre-AVX2 targets, split into 128-bit nodes of
23835 // ISD::SIGN_EXTEND_VECTOR_INREG.
23836 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
23837 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
23838 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
23839 unsigned NumVecs = VT.getSizeInBits() / 128;
23840 unsigned NumSubElts = 128 / SVT.getSizeInBits();
23841 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
23842 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
23844 SmallVector<SDValue, 8> Opnds;
23845 for (unsigned i = 0, Offset = 0; i != NumVecs;
23846 ++i, Offset += NumSubElts) {
23847 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
23848 DAG.getIntPtrConstant(Offset, DL));
23849 SrcVec = ExtendToVec128(DL, SrcVec);
23850 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
23851 Opnds.push_back(SrcVec);
23853 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
23857 if (!Subtarget->hasFp256())
23860 if (VT.isVector() && VT.getSizeInBits() == 256) {
23861 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23869 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23870 const X86Subtarget* Subtarget) {
23872 EVT VT = N->getValueType(0);
23874 // Let legalize expand this if it isn't a legal type yet.
23875 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23878 EVT ScalarVT = VT.getScalarType();
23879 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23880 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23883 SDValue A = N->getOperand(0);
23884 SDValue B = N->getOperand(1);
23885 SDValue C = N->getOperand(2);
23887 bool NegA = (A.getOpcode() == ISD::FNEG);
23888 bool NegB = (B.getOpcode() == ISD::FNEG);
23889 bool NegC = (C.getOpcode() == ISD::FNEG);
23891 // Negative multiplication when NegA xor NegB
23892 bool NegMul = (NegA != NegB);
23894 A = A.getOperand(0);
23896 B = B.getOperand(0);
23898 C = C.getOperand(0);
23902 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23904 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23906 return DAG.getNode(Opcode, dl, VT, A, B, C);
23909 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23910 TargetLowering::DAGCombinerInfo &DCI,
23911 const X86Subtarget *Subtarget) {
23912 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23913 // (and (i32 x86isd::setcc_carry), 1)
23914 // This eliminates the zext. This transformation is necessary because
23915 // ISD::SETCC is always legalized to i8.
23917 SDValue N0 = N->getOperand(0);
23918 EVT VT = N->getValueType(0);
23920 if (N0.getOpcode() == ISD::AND &&
23922 N0.getOperand(0).hasOneUse()) {
23923 SDValue N00 = N0.getOperand(0);
23924 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23925 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23926 if (!C || C->getZExtValue() != 1)
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));
23935 if (N0.getOpcode() == ISD::TRUNCATE &&
23937 N0.getOperand(0).hasOneUse()) {
23938 SDValue N00 = N0.getOperand(0);
23939 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23940 return DAG.getNode(ISD::AND, dl, VT,
23941 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23942 N00.getOperand(0), N00.getOperand(1)),
23943 DAG.getConstant(1, dl, VT));
23946 if (VT.is256BitVector()) {
23947 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23952 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23953 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23954 // This exposes the zext to the udivrem lowering, so that it directly extends
23955 // from AH (which we otherwise need to do contortions to access).
23956 if (N0.getOpcode() == ISD::UDIVREM &&
23957 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23958 (VT == MVT::i32 || VT == MVT::i64)) {
23959 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23960 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23961 N0.getOperand(0), N0.getOperand(1));
23962 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23963 return R.getValue(1);
23969 // Optimize x == -y --> x+y == 0
23970 // x != -y --> x+y != 0
23971 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23972 const X86Subtarget* Subtarget) {
23973 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23974 SDValue LHS = N->getOperand(0);
23975 SDValue RHS = N->getOperand(1);
23976 EVT VT = N->getValueType(0);
23979 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23980 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23981 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23982 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23983 LHS.getOperand(1));
23984 return DAG.getSetCC(DL, N->getValueType(0), addV,
23985 DAG.getConstant(0, DL, addV.getValueType()), CC);
23987 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23988 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23989 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23990 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23991 RHS.getOperand(1));
23992 return DAG.getSetCC(DL, N->getValueType(0), addV,
23993 DAG.getConstant(0, DL, addV.getValueType()), CC);
23996 if (VT.getScalarType() == MVT::i1 &&
23997 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23999 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24000 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24001 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24003 if (!IsSEXT0 || !IsVZero1) {
24004 // Swap the operands and update the condition code.
24005 std::swap(LHS, RHS);
24006 CC = ISD::getSetCCSwappedOperands(CC);
24008 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24009 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24010 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24013 if (IsSEXT0 && IsVZero1) {
24014 assert(VT == LHS.getOperand(0).getValueType() &&
24015 "Uexpected operand type");
24016 if (CC == ISD::SETGT)
24017 return DAG.getConstant(0, DL, VT);
24018 if (CC == ISD::SETLE)
24019 return DAG.getConstant(1, DL, VT);
24020 if (CC == ISD::SETEQ || CC == ISD::SETGE)
24021 return DAG.getNOT(DL, LHS.getOperand(0), VT);
24023 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24024 "Unexpected condition code!");
24025 return LHS.getOperand(0);
24032 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24033 SelectionDAG &DAG) {
24035 MVT VT = Load->getSimpleValueType(0);
24036 MVT EVT = VT.getVectorElementType();
24037 SDValue Addr = Load->getOperand(1);
24038 SDValue NewAddr = DAG.getNode(
24039 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24040 DAG.getConstant(Index * EVT.getStoreSize(), dl,
24041 Addr.getSimpleValueType()));
24044 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24045 DAG.getMachineFunction().getMachineMemOperand(
24046 Load->getMemOperand(), 0, EVT.getStoreSize()));
24050 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24051 const X86Subtarget *Subtarget) {
24053 MVT VT = N->getOperand(1)->getSimpleValueType(0);
24054 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24055 "X86insertps is only defined for v4x32");
24057 SDValue Ld = N->getOperand(1);
24058 if (MayFoldLoad(Ld)) {
24059 // Extract the countS bits from the immediate so we can get the proper
24060 // address when narrowing the vector load to a specific element.
24061 // When the second source op is a memory address, insertps doesn't use
24062 // countS and just gets an f32 from that address.
24063 unsigned DestIndex =
24064 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24066 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24068 // Create this as a scalar to vector to match the instruction pattern.
24069 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24070 // countS bits are ignored when loading from memory on insertps, which
24071 // means we don't need to explicitly set them to 0.
24072 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24073 LoadScalarToVector, N->getOperand(2));
24078 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24079 SDValue V0 = N->getOperand(0);
24080 SDValue V1 = N->getOperand(1);
24082 EVT VT = N->getValueType(0);
24084 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24085 // operands and changing the mask to 1. This saves us a bunch of
24086 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24087 // x86InstrInfo knows how to commute this back after instruction selection
24088 // if it would help register allocation.
24090 // TODO: If optimizing for size or a processor that doesn't suffer from
24091 // partial register update stalls, this should be transformed into a MOVSD
24092 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24094 if (VT == MVT::v2f64)
24095 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24096 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24097 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24098 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24104 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24105 // as "sbb reg,reg", since it can be extended without zext and produces
24106 // an all-ones bit which is more useful than 0/1 in some cases.
24107 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24110 return DAG.getNode(ISD::AND, DL, VT,
24111 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24112 DAG.getConstant(X86::COND_B, DL, MVT::i8),
24114 DAG.getConstant(1, DL, VT));
24115 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24116 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24117 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24118 DAG.getConstant(X86::COND_B, DL, MVT::i8),
24122 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24123 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24124 TargetLowering::DAGCombinerInfo &DCI,
24125 const X86Subtarget *Subtarget) {
24127 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24128 SDValue EFLAGS = N->getOperand(1);
24130 if (CC == X86::COND_A) {
24131 // Try to convert COND_A into COND_B in an attempt to facilitate
24132 // materializing "setb reg".
24134 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24135 // cannot take an immediate as its first operand.
24137 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24138 EFLAGS.getValueType().isInteger() &&
24139 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24140 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24141 EFLAGS.getNode()->getVTList(),
24142 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24143 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24144 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24148 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24149 // a zext and produces an all-ones bit which is more useful than 0/1 in some
24151 if (CC == X86::COND_B)
24152 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24156 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24157 if (Flags.getNode()) {
24158 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24159 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24165 // Optimize branch condition evaluation.
24167 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24168 TargetLowering::DAGCombinerInfo &DCI,
24169 const X86Subtarget *Subtarget) {
24171 SDValue Chain = N->getOperand(0);
24172 SDValue Dest = N->getOperand(1);
24173 SDValue EFLAGS = N->getOperand(3);
24174 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24178 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24179 if (Flags.getNode()) {
24180 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24181 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24188 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24189 SelectionDAG &DAG) {
24190 // Take advantage of vector comparisons producing 0 or -1 in each lane to
24191 // optimize away operation when it's from a constant.
24193 // The general transformation is:
24194 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24195 // AND(VECTOR_CMP(x,y), constant2)
24196 // constant2 = UNARYOP(constant)
24198 // Early exit if this isn't a vector operation, the operand of the
24199 // unary operation isn't a bitwise AND, or if the sizes of the operations
24200 // aren't the same.
24201 EVT VT = N->getValueType(0);
24202 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24203 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24204 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24207 // Now check that the other operand of the AND is a constant. We could
24208 // make the transformation for non-constant splats as well, but it's unclear
24209 // that would be a benefit as it would not eliminate any operations, just
24210 // perform one more step in scalar code before moving to the vector unit.
24211 if (BuildVectorSDNode *BV =
24212 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24213 // Bail out if the vector isn't a constant.
24214 if (!BV->isConstant())
24217 // Everything checks out. Build up the new and improved node.
24219 EVT IntVT = BV->getValueType(0);
24220 // Create a new constant of the appropriate type for the transformed
24222 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24223 // The AND node needs bitcasts to/from an integer vector type around it.
24224 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24225 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24226 N->getOperand(0)->getOperand(0), MaskConst);
24227 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24234 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24235 const X86Subtarget *Subtarget) {
24236 // First try to optimize away the conversion entirely when it's
24237 // conditionally from a constant. Vectors only.
24238 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24239 if (Res != SDValue())
24242 // Now move on to more general possibilities.
24243 SDValue Op0 = N->getOperand(0);
24244 EVT InVT = Op0->getValueType(0);
24246 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24247 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24249 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24250 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24251 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24254 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24255 // a 32-bit target where SSE doesn't support i64->FP operations.
24256 if (Op0.getOpcode() == ISD::LOAD) {
24257 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24258 EVT VT = Ld->getValueType(0);
24260 // This transformation is not supported if the result type is f16
24261 if (N->getValueType(0) == MVT::f16)
24264 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24265 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24266 !Subtarget->is64Bit() && VT == MVT::i64) {
24267 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24268 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24269 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24276 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24277 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24278 X86TargetLowering::DAGCombinerInfo &DCI) {
24279 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24280 // the result is either zero or one (depending on the input carry bit).
24281 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24282 if (X86::isZeroNode(N->getOperand(0)) &&
24283 X86::isZeroNode(N->getOperand(1)) &&
24284 // We don't have a good way to replace an EFLAGS use, so only do this when
24286 SDValue(N, 1).use_empty()) {
24288 EVT VT = N->getValueType(0);
24289 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24290 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24291 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24292 DAG.getConstant(X86::COND_B, DL,
24295 DAG.getConstant(1, DL, VT));
24296 return DCI.CombineTo(N, Res1, CarryOut);
24302 // fold (add Y, (sete X, 0)) -> adc 0, Y
24303 // (add Y, (setne X, 0)) -> sbb -1, Y
24304 // (sub (sete X, 0), Y) -> sbb 0, Y
24305 // (sub (setne X, 0), Y) -> adc -1, Y
24306 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24309 // Look through ZExts.
24310 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24311 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24314 SDValue SetCC = Ext.getOperand(0);
24315 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24318 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24319 if (CC != X86::COND_E && CC != X86::COND_NE)
24322 SDValue Cmp = SetCC.getOperand(1);
24323 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24324 !X86::isZeroNode(Cmp.getOperand(1)) ||
24325 !Cmp.getOperand(0).getValueType().isInteger())
24328 SDValue CmpOp0 = Cmp.getOperand(0);
24329 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24330 DAG.getConstant(1, DL, CmpOp0.getValueType()));
24332 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24333 if (CC == X86::COND_NE)
24334 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24335 DL, OtherVal.getValueType(), OtherVal,
24336 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24338 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24339 DL, OtherVal.getValueType(), OtherVal,
24340 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24343 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24344 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24345 const X86Subtarget *Subtarget) {
24346 EVT VT = N->getValueType(0);
24347 SDValue Op0 = N->getOperand(0);
24348 SDValue Op1 = N->getOperand(1);
24350 // Try to synthesize horizontal adds from adds of shuffles.
24351 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24352 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24353 isHorizontalBinOp(Op0, Op1, true))
24354 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24356 return OptimizeConditionalInDecrement(N, DAG);
24359 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24360 const X86Subtarget *Subtarget) {
24361 SDValue Op0 = N->getOperand(0);
24362 SDValue Op1 = N->getOperand(1);
24364 // X86 can't encode an immediate LHS of a sub. See if we can push the
24365 // negation into a preceding instruction.
24366 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24367 // If the RHS of the sub is a XOR with one use and a constant, invert the
24368 // immediate. Then add one to the LHS of the sub so we can turn
24369 // X-Y -> X+~Y+1, saving one register.
24370 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24371 isa<ConstantSDNode>(Op1.getOperand(1))) {
24372 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24373 EVT VT = Op0.getValueType();
24374 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24376 DAG.getConstant(~XorC, SDLoc(Op1), VT));
24377 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24378 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24382 // Try to synthesize horizontal adds from adds of shuffles.
24383 EVT VT = N->getValueType(0);
24384 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24385 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24386 isHorizontalBinOp(Op0, Op1, true))
24387 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24389 return OptimizeConditionalInDecrement(N, DAG);
24392 /// performVZEXTCombine - Performs build vector combines
24393 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24394 TargetLowering::DAGCombinerInfo &DCI,
24395 const X86Subtarget *Subtarget) {
24397 MVT VT = N->getSimpleValueType(0);
24398 SDValue Op = N->getOperand(0);
24399 MVT OpVT = Op.getSimpleValueType();
24400 MVT OpEltVT = OpVT.getVectorElementType();
24401 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24403 // (vzext (bitcast (vzext (x)) -> (vzext x)
24405 while (V.getOpcode() == ISD::BITCAST)
24406 V = V.getOperand(0);
24408 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24409 MVT InnerVT = V.getSimpleValueType();
24410 MVT InnerEltVT = InnerVT.getVectorElementType();
24412 // If the element sizes match exactly, we can just do one larger vzext. This
24413 // is always an exact type match as vzext operates on integer types.
24414 if (OpEltVT == InnerEltVT) {
24415 assert(OpVT == InnerVT && "Types must match for vzext!");
24416 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24419 // The only other way we can combine them is if only a single element of the
24420 // inner vzext is used in the input to the outer vzext.
24421 if (InnerEltVT.getSizeInBits() < InputBits)
24424 // In this case, the inner vzext is completely dead because we're going to
24425 // only look at bits inside of the low element. Just do the outer vzext on
24426 // a bitcast of the input to the inner.
24427 return DAG.getNode(X86ISD::VZEXT, DL, VT,
24428 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24431 // Check if we can bypass extracting and re-inserting an element of an input
24432 // vector. Essentialy:
24433 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24434 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24435 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24436 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24437 SDValue ExtractedV = V.getOperand(0);
24438 SDValue OrigV = ExtractedV.getOperand(0);
24439 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24440 if (ExtractIdx->getZExtValue() == 0) {
24441 MVT OrigVT = OrigV.getSimpleValueType();
24442 // Extract a subvector if necessary...
24443 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24444 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24445 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24446 OrigVT.getVectorNumElements() / Ratio);
24447 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24448 DAG.getIntPtrConstant(0, DL));
24450 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24451 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24458 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24459 DAGCombinerInfo &DCI) const {
24460 SelectionDAG &DAG = DCI.DAG;
24461 switch (N->getOpcode()) {
24463 case ISD::EXTRACT_VECTOR_ELT:
24464 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24467 case X86ISD::SHRUNKBLEND:
24468 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24469 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
24470 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24471 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
24472 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
24473 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
24474 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
24477 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
24478 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
24479 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
24480 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
24481 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
24482 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24483 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
24484 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
24485 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24486 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
24487 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
24489 case X86ISD::FOR: return PerformFORCombine(N, DAG);
24491 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
24492 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
24493 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
24494 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
24495 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
24496 case ISD::ANY_EXTEND:
24497 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
24498 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
24499 case ISD::SIGN_EXTEND_INREG:
24500 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24501 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
24502 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24503 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24504 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
24505 case X86ISD::SHUFP: // Handle all target specific shuffles
24506 case X86ISD::PALIGNR:
24507 case X86ISD::UNPCKH:
24508 case X86ISD::UNPCKL:
24509 case X86ISD::MOVHLPS:
24510 case X86ISD::MOVLHPS:
24511 case X86ISD::PSHUFB:
24512 case X86ISD::PSHUFD:
24513 case X86ISD::PSHUFHW:
24514 case X86ISD::PSHUFLW:
24515 case X86ISD::MOVSS:
24516 case X86ISD::MOVSD:
24517 case X86ISD::VPERMILPI:
24518 case X86ISD::VPERM2X128:
24519 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24520 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
24521 case ISD::INTRINSIC_WO_CHAIN:
24522 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24523 case X86ISD::INSERTPS: {
24524 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24525 return PerformINSERTPSCombine(N, DAG, Subtarget);
24528 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
24534 /// isTypeDesirableForOp - Return true if the target has native support for
24535 /// the specified value type and it is 'desirable' to use the type for the
24536 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24537 /// instruction encodings are longer and some i16 instructions are slow.
24538 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24539 if (!isTypeLegal(VT))
24541 if (VT != MVT::i16)
24548 case ISD::SIGN_EXTEND:
24549 case ISD::ZERO_EXTEND:
24550 case ISD::ANY_EXTEND:
24563 /// IsDesirableToPromoteOp - This method query the target whether it is
24564 /// beneficial for dag combiner to promote the specified node. If true, it
24565 /// should return the desired promotion type by reference.
24566 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24567 EVT VT = Op.getValueType();
24568 if (VT != MVT::i16)
24571 bool Promote = false;
24572 bool Commute = false;
24573 switch (Op.getOpcode()) {
24576 LoadSDNode *LD = cast<LoadSDNode>(Op);
24577 // If the non-extending load has a single use and it's not live out, then it
24578 // might be folded.
24579 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24580 Op.hasOneUse()*/) {
24581 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24582 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24583 // The only case where we'd want to promote LOAD (rather then it being
24584 // promoted as an operand is when it's only use is liveout.
24585 if (UI->getOpcode() != ISD::CopyToReg)
24592 case ISD::SIGN_EXTEND:
24593 case ISD::ZERO_EXTEND:
24594 case ISD::ANY_EXTEND:
24599 SDValue N0 = Op.getOperand(0);
24600 // Look out for (store (shl (load), x)).
24601 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24614 SDValue N0 = Op.getOperand(0);
24615 SDValue N1 = Op.getOperand(1);
24616 if (!Commute && MayFoldLoad(N1))
24618 // Avoid disabling potential load folding opportunities.
24619 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24621 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24631 //===----------------------------------------------------------------------===//
24632 // X86 Inline Assembly Support
24633 //===----------------------------------------------------------------------===//
24635 // Helper to match a string separated by whitespace.
24636 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24637 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24639 for (StringRef Piece : Pieces) {
24640 if (!S.startswith(Piece)) // Check if the piece matches.
24643 S = S.substr(Piece.size());
24644 StringRef::size_type Pos = S.find_first_not_of(" \t");
24645 if (Pos == 0) // We matched a prefix.
24654 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24656 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24657 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24658 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24659 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24661 if (AsmPieces.size() == 3)
24663 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24670 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24671 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24673 std::string AsmStr = IA->getAsmString();
24675 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24676 if (!Ty || Ty->getBitWidth() % 16 != 0)
24679 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24680 SmallVector<StringRef, 4> AsmPieces;
24681 SplitString(AsmStr, AsmPieces, ";\n");
24683 switch (AsmPieces.size()) {
24684 default: return false;
24686 // FIXME: this should verify that we are targeting a 486 or better. If not,
24687 // we will turn this bswap into something that will be lowered to logical
24688 // ops instead of emitting the bswap asm. For now, we don't support 486 or
24689 // lower so don't worry about this.
24691 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24692 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24693 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24694 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24695 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24696 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24697 // No need to check constraints, nothing other than the equivalent of
24698 // "=r,0" would be valid here.
24699 return IntrinsicLowering::LowerToByteSwap(CI);
24702 // rorw $$8, ${0:w} --> llvm.bswap.i16
24703 if (CI->getType()->isIntegerTy(16) &&
24704 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24705 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24706 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24708 const std::string &ConstraintsStr = IA->getConstraintString();
24709 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24710 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24711 if (clobbersFlagRegisters(AsmPieces))
24712 return IntrinsicLowering::LowerToByteSwap(CI);
24716 if (CI->getType()->isIntegerTy(32) &&
24717 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24718 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24719 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24720 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24722 const std::string &ConstraintsStr = IA->getConstraintString();
24723 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24724 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24725 if (clobbersFlagRegisters(AsmPieces))
24726 return IntrinsicLowering::LowerToByteSwap(CI);
24729 if (CI->getType()->isIntegerTy(64)) {
24730 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24731 if (Constraints.size() >= 2 &&
24732 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24733 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24734 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
24735 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24736 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24737 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24738 return IntrinsicLowering::LowerToByteSwap(CI);
24746 /// getConstraintType - Given a constraint letter, return the type of
24747 /// constraint it is for this target.
24748 X86TargetLowering::ConstraintType
24749 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24750 if (Constraint.size() == 1) {
24751 switch (Constraint[0]) {
24762 return C_RegisterClass;
24786 return TargetLowering::getConstraintType(Constraint);
24789 /// Examine constraint type and operand type and determine a weight value.
24790 /// This object must already have been set up with the operand type
24791 /// and the current alternative constraint selected.
24792 TargetLowering::ConstraintWeight
24793 X86TargetLowering::getSingleConstraintMatchWeight(
24794 AsmOperandInfo &info, const char *constraint) const {
24795 ConstraintWeight weight = CW_Invalid;
24796 Value *CallOperandVal = info.CallOperandVal;
24797 // If we don't have a value, we can't do a match,
24798 // but allow it at the lowest weight.
24799 if (!CallOperandVal)
24801 Type *type = CallOperandVal->getType();
24802 // Look at the constraint type.
24803 switch (*constraint) {
24805 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24816 if (CallOperandVal->getType()->isIntegerTy())
24817 weight = CW_SpecificReg;
24822 if (type->isFloatingPointTy())
24823 weight = CW_SpecificReg;
24826 if (type->isX86_MMXTy() && Subtarget->hasMMX())
24827 weight = CW_SpecificReg;
24831 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24832 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24833 weight = CW_Register;
24836 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24837 if (C->getZExtValue() <= 31)
24838 weight = CW_Constant;
24842 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24843 if (C->getZExtValue() <= 63)
24844 weight = CW_Constant;
24848 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24849 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24850 weight = CW_Constant;
24854 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24855 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24856 weight = CW_Constant;
24860 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24861 if (C->getZExtValue() <= 3)
24862 weight = CW_Constant;
24866 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24867 if (C->getZExtValue() <= 0xff)
24868 weight = CW_Constant;
24873 if (isa<ConstantFP>(CallOperandVal)) {
24874 weight = CW_Constant;
24878 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24879 if ((C->getSExtValue() >= -0x80000000LL) &&
24880 (C->getSExtValue() <= 0x7fffffffLL))
24881 weight = CW_Constant;
24885 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24886 if (C->getZExtValue() <= 0xffffffff)
24887 weight = CW_Constant;
24894 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24895 /// with another that has more specific requirements based on the type of the
24896 /// corresponding operand.
24897 const char *X86TargetLowering::
24898 LowerXConstraint(EVT ConstraintVT) const {
24899 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24900 // 'f' like normal targets.
24901 if (ConstraintVT.isFloatingPoint()) {
24902 if (Subtarget->hasSSE2())
24904 if (Subtarget->hasSSE1())
24908 return TargetLowering::LowerXConstraint(ConstraintVT);
24911 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24912 /// vector. If it is invalid, don't add anything to Ops.
24913 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24914 std::string &Constraint,
24915 std::vector<SDValue>&Ops,
24916 SelectionDAG &DAG) const {
24919 // Only support length 1 constraints for now.
24920 if (Constraint.length() > 1) return;
24922 char ConstraintLetter = Constraint[0];
24923 switch (ConstraintLetter) {
24926 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24927 if (C->getZExtValue() <= 31) {
24928 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24929 Op.getValueType());
24935 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24936 if (C->getZExtValue() <= 63) {
24937 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24938 Op.getValueType());
24944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24945 if (isInt<8>(C->getSExtValue())) {
24946 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24947 Op.getValueType());
24953 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24954 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24955 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24956 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24957 Op.getValueType());
24963 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24964 if (C->getZExtValue() <= 3) {
24965 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24966 Op.getValueType());
24972 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24973 if (C->getZExtValue() <= 255) {
24974 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24975 Op.getValueType());
24981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24982 if (C->getZExtValue() <= 127) {
24983 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24984 Op.getValueType());
24990 // 32-bit signed value
24991 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24992 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24993 C->getSExtValue())) {
24994 // Widen to 64 bits here to get it sign extended.
24995 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24998 // FIXME gcc accepts some relocatable values here too, but only in certain
24999 // memory models; it's complicated.
25004 // 32-bit unsigned value
25005 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25006 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25007 C->getZExtValue())) {
25008 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25009 Op.getValueType());
25013 // FIXME gcc accepts some relocatable values here too, but only in certain
25014 // memory models; it's complicated.
25018 // Literal immediates are always ok.
25019 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25020 // Widen to 64 bits here to get it sign extended.
25021 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25025 // In any sort of PIC mode addresses need to be computed at runtime by
25026 // adding in a register or some sort of table lookup. These can't
25027 // be used as immediates.
25028 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25031 // If we are in non-pic codegen mode, we allow the address of a global (with
25032 // an optional displacement) to be used with 'i'.
25033 GlobalAddressSDNode *GA = nullptr;
25034 int64_t Offset = 0;
25036 // Match either (GA), (GA+C), (GA+C1+C2), etc.
25038 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25039 Offset += GA->getOffset();
25041 } else if (Op.getOpcode() == ISD::ADD) {
25042 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25043 Offset += C->getZExtValue();
25044 Op = Op.getOperand(0);
25047 } else if (Op.getOpcode() == ISD::SUB) {
25048 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25049 Offset += -C->getZExtValue();
25050 Op = Op.getOperand(0);
25055 // Otherwise, this isn't something we can handle, reject it.
25059 const GlobalValue *GV = GA->getGlobal();
25060 // If we require an extra load to get this address, as in PIC mode, we
25061 // can't accept it.
25062 if (isGlobalStubReference(
25063 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25066 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25067 GA->getValueType(0), Offset);
25072 if (Result.getNode()) {
25073 Ops.push_back(Result);
25076 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25079 std::pair<unsigned, const TargetRegisterClass *>
25080 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25081 const std::string &Constraint,
25083 // First, see if this is a constraint that directly corresponds to an LLVM
25085 if (Constraint.size() == 1) {
25086 // GCC Constraint Letters
25087 switch (Constraint[0]) {
25089 // TODO: Slight differences here in allocation order and leaving
25090 // RIP in the class. Do they matter any more here than they do
25091 // in the normal allocation?
25092 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25093 if (Subtarget->is64Bit()) {
25094 if (VT == MVT::i32 || VT == MVT::f32)
25095 return std::make_pair(0U, &X86::GR32RegClass);
25096 if (VT == MVT::i16)
25097 return std::make_pair(0U, &X86::GR16RegClass);
25098 if (VT == MVT::i8 || VT == MVT::i1)
25099 return std::make_pair(0U, &X86::GR8RegClass);
25100 if (VT == MVT::i64 || VT == MVT::f64)
25101 return std::make_pair(0U, &X86::GR64RegClass);
25104 // 32-bit fallthrough
25105 case 'Q': // Q_REGS
25106 if (VT == MVT::i32 || VT == MVT::f32)
25107 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25108 if (VT == MVT::i16)
25109 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25110 if (VT == MVT::i8 || VT == MVT::i1)
25111 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25112 if (VT == MVT::i64)
25113 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25115 case 'r': // GENERAL_REGS
25116 case 'l': // INDEX_REGS
25117 if (VT == MVT::i8 || VT == MVT::i1)
25118 return std::make_pair(0U, &X86::GR8RegClass);
25119 if (VT == MVT::i16)
25120 return std::make_pair(0U, &X86::GR16RegClass);
25121 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25122 return std::make_pair(0U, &X86::GR32RegClass);
25123 return std::make_pair(0U, &X86::GR64RegClass);
25124 case 'R': // LEGACY_REGS
25125 if (VT == MVT::i8 || VT == MVT::i1)
25126 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25127 if (VT == MVT::i16)
25128 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25129 if (VT == MVT::i32 || !Subtarget->is64Bit())
25130 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25131 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25132 case 'f': // FP Stack registers.
25133 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25134 // value to the correct fpstack register class.
25135 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25136 return std::make_pair(0U, &X86::RFP32RegClass);
25137 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25138 return std::make_pair(0U, &X86::RFP64RegClass);
25139 return std::make_pair(0U, &X86::RFP80RegClass);
25140 case 'y': // MMX_REGS if MMX allowed.
25141 if (!Subtarget->hasMMX()) break;
25142 return std::make_pair(0U, &X86::VR64RegClass);
25143 case 'Y': // SSE_REGS if SSE2 allowed
25144 if (!Subtarget->hasSSE2()) break;
25146 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25147 if (!Subtarget->hasSSE1()) break;
25149 switch (VT.SimpleTy) {
25151 // Scalar SSE types.
25154 return std::make_pair(0U, &X86::FR32RegClass);
25157 return std::make_pair(0U, &X86::FR64RegClass);
25165 return std::make_pair(0U, &X86::VR128RegClass);
25173 return std::make_pair(0U, &X86::VR256RegClass);
25178 return std::make_pair(0U, &X86::VR512RegClass);
25184 // Use the default implementation in TargetLowering to convert the register
25185 // constraint into a member of a register class.
25186 std::pair<unsigned, const TargetRegisterClass*> Res;
25187 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25189 // Not found as a standard register?
25191 // Map st(0) -> st(7) -> ST0
25192 if (Constraint.size() == 7 && Constraint[0] == '{' &&
25193 tolower(Constraint[1]) == 's' &&
25194 tolower(Constraint[2]) == 't' &&
25195 Constraint[3] == '(' &&
25196 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25197 Constraint[5] == ')' &&
25198 Constraint[6] == '}') {
25200 Res.first = X86::FP0+Constraint[4]-'0';
25201 Res.second = &X86::RFP80RegClass;
25205 // GCC allows "st(0)" to be called just plain "st".
25206 if (StringRef("{st}").equals_lower(Constraint)) {
25207 Res.first = X86::FP0;
25208 Res.second = &X86::RFP80RegClass;
25213 if (StringRef("{flags}").equals_lower(Constraint)) {
25214 Res.first = X86::EFLAGS;
25215 Res.second = &X86::CCRRegClass;
25219 // 'A' means EAX + EDX.
25220 if (Constraint == "A") {
25221 Res.first = X86::EAX;
25222 Res.second = &X86::GR32_ADRegClass;
25228 // Otherwise, check to see if this is a register class of the wrong value
25229 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25230 // turn into {ax},{dx}.
25231 if (Res.second->hasType(VT))
25232 return Res; // Correct type already, nothing to do.
25234 // All of the single-register GCC register classes map their values onto
25235 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
25236 // really want an 8-bit or 32-bit register, map to the appropriate register
25237 // class and return the appropriate register.
25238 if (Res.second == &X86::GR16RegClass) {
25239 if (VT == MVT::i8 || VT == MVT::i1) {
25240 unsigned DestReg = 0;
25241 switch (Res.first) {
25243 case X86::AX: DestReg = X86::AL; break;
25244 case X86::DX: DestReg = X86::DL; break;
25245 case X86::CX: DestReg = X86::CL; break;
25246 case X86::BX: DestReg = X86::BL; break;
25249 Res.first = DestReg;
25250 Res.second = &X86::GR8RegClass;
25252 } else if (VT == MVT::i32 || VT == MVT::f32) {
25253 unsigned DestReg = 0;
25254 switch (Res.first) {
25256 case X86::AX: DestReg = X86::EAX; break;
25257 case X86::DX: DestReg = X86::EDX; break;
25258 case X86::CX: DestReg = X86::ECX; break;
25259 case X86::BX: DestReg = X86::EBX; break;
25260 case X86::SI: DestReg = X86::ESI; break;
25261 case X86::DI: DestReg = X86::EDI; break;
25262 case X86::BP: DestReg = X86::EBP; break;
25263 case X86::SP: DestReg = X86::ESP; break;
25266 Res.first = DestReg;
25267 Res.second = &X86::GR32RegClass;
25269 } else if (VT == MVT::i64 || VT == MVT::f64) {
25270 unsigned DestReg = 0;
25271 switch (Res.first) {
25273 case X86::AX: DestReg = X86::RAX; break;
25274 case X86::DX: DestReg = X86::RDX; break;
25275 case X86::CX: DestReg = X86::RCX; break;
25276 case X86::BX: DestReg = X86::RBX; break;
25277 case X86::SI: DestReg = X86::RSI; break;
25278 case X86::DI: DestReg = X86::RDI; break;
25279 case X86::BP: DestReg = X86::RBP; break;
25280 case X86::SP: DestReg = X86::RSP; break;
25283 Res.first = DestReg;
25284 Res.second = &X86::GR64RegClass;
25287 } else if (Res.second == &X86::FR32RegClass ||
25288 Res.second == &X86::FR64RegClass ||
25289 Res.second == &X86::VR128RegClass ||
25290 Res.second == &X86::VR256RegClass ||
25291 Res.second == &X86::FR32XRegClass ||
25292 Res.second == &X86::FR64XRegClass ||
25293 Res.second == &X86::VR128XRegClass ||
25294 Res.second == &X86::VR256XRegClass ||
25295 Res.second == &X86::VR512RegClass) {
25296 // Handle references to XMM physical registers that got mapped into the
25297 // wrong class. This can happen with constraints like {xmm0} where the
25298 // target independent register mapper will just pick the first match it can
25299 // find, ignoring the required type.
25301 if (VT == MVT::f32 || VT == MVT::i32)
25302 Res.second = &X86::FR32RegClass;
25303 else if (VT == MVT::f64 || VT == MVT::i64)
25304 Res.second = &X86::FR64RegClass;
25305 else if (X86::VR128RegClass.hasType(VT))
25306 Res.second = &X86::VR128RegClass;
25307 else if (X86::VR256RegClass.hasType(VT))
25308 Res.second = &X86::VR256RegClass;
25309 else if (X86::VR512RegClass.hasType(VT))
25310 Res.second = &X86::VR512RegClass;
25316 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25318 // Scaling factors are not free at all.
25319 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25320 // will take 2 allocations in the out of order engine instead of 1
25321 // for plain addressing mode, i.e. inst (reg1).
25323 // vaddps (%rsi,%drx), %ymm0, %ymm1
25324 // Requires two allocations (one for the load, one for the computation)
25326 // vaddps (%rsi), %ymm0, %ymm1
25327 // Requires just 1 allocation, i.e., freeing allocations for other operations
25328 // and having less micro operations to execute.
25330 // For some X86 architectures, this is even worse because for instance for
25331 // stores, the complex addressing mode forces the instruction to use the
25332 // "load" ports instead of the dedicated "store" port.
25333 // E.g., on Haswell:
25334 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25335 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25336 if (isLegalAddressingMode(AM, Ty))
25337 // Scale represents reg2 * scale, thus account for 1
25338 // as soon as we use a second register.
25339 return AM.Scale != 0;
25343 bool X86TargetLowering::isTargetFTOL() const {
25344 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();