AVX512BW: Enable packed word shift for 512bit vector. Enable lowering scalar immidiat...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
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/Analysis/EHPersonalities.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/WinEHFuncInfo.h"
37 #include "llvm/IR/CallSite.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/MC/MCAsmInfo.h"
47 #include "llvm/MC/MCContext.h"
48 #include "llvm/MC/MCExpr.h"
49 #include "llvm/MC/MCSymbol.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "X86IntrinsicsInfo.h"
56 #include <bitset>
57 #include <numeric>
58 #include <cctype>
59 using namespace llvm;
60
61 #define DEBUG_TYPE "x86-isel"
62
63 STATISTIC(NumTailCalls, "Number of tail calls");
64
65 static cl::opt<bool> ExperimentalVectorWideningLegalization(
66     "x86-experimental-vector-widening-legalization", cl::init(false),
67     cl::desc("Enable an experimental vector type legalization through widening "
68              "rather than promotion."),
69     cl::Hidden);
70
71 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
72                                      const X86Subtarget &STI)
73     : TargetLowering(TM), Subtarget(&STI) {
74   X86ScalarSSEf64 = Subtarget->hasSSE2();
75   X86ScalarSSEf32 = Subtarget->hasSSE1();
76   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77
78   // Set up the TargetLowering object.
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117   }
118
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168       // f32/f64 are legal, f80 is custom.
169       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
170     else
171       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173   } else if (!Subtarget->useSoftFloat()) {
174     // We have an algorithm for SSE2->double, and we turn this into a
175     // 64-bit FILD followed by conditional FADD for other targets.
176     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
177     // We have an algorithm for SSE2, and we turn this into a 64-bit
178     // FILD or VCVTUSI2SS/SD for other targets.
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
180   }
181
182   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
183   // this operation.
184   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
186
187   if (!Subtarget->useSoftFloat()) {
188     // SSE has no i16 to fp conversion, only i32
189     if (X86ScalarSSEf32) {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
191       // f32 and f64 cases are Legal, f80 case is not
192       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
193     } else {
194       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
196     }
197   } else {
198     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
200   }
201
202   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
203   // this operation.
204   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
206
207   if (!Subtarget->useSoftFloat()) {
208     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
209     // are Legal, f80 is custom lowered.
210     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
212
213     if (X86ScalarSSEf32) {
214       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
215       // f32 and f64 cases are Legal, f80 case is not
216       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
217     } else {
218       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
219       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
220     }
221   } else {
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
223     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Expand);
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Expand);
225   }
226
227   // Handle FP_TO_UINT by promoting the destination to a larger signed
228   // conversion.
229   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
232
233   if (Subtarget->is64Bit()) {
234     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
235       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
236       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
237       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
238     } else {
239       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
240       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
241     }
242   } else if (!Subtarget->useSoftFloat()) {
243     // Since AVX is a superset of SSE3, only check for SSE here.
244     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
245       // Expand FP_TO_UINT into a select.
246       // FIXME: We would like to use a Custom expander here eventually to do
247       // the optimal thing for SSE vs. the default expansion in the legalizer.
248       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
249     else
250       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
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);
254
255     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
256   }
257
258   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
259   if (!X86ScalarSSEf64) {
260     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
261     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
262     if (Subtarget->is64Bit()) {
263       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
264       // Without SSE, i64->f64 goes through memory.
265       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
266     }
267   }
268
269   // Scalar integer divide and remainder are lowered to use operations that
270   // produce two results, to match the available instructions. This exposes
271   // the two-result form to trivial CSE, which is able to combine x/y and x%y
272   // into a single instruction.
273   //
274   // Scalar integer multiply-high is also lowered to use two-result
275   // operations, to match the available instructions. However, plain multiply
276   // (low) operations are left as Legal, as there are single-result
277   // instructions for this in x86. Using the two-result multiply instructions
278   // when both high and low results are needed must be arranged by dagcombine.
279   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
280     setOperationAction(ISD::MULHS, VT, Expand);
281     setOperationAction(ISD::MULHU, VT, Expand);
282     setOperationAction(ISD::SDIV, VT, Expand);
283     setOperationAction(ISD::UDIV, VT, Expand);
284     setOperationAction(ISD::SREM, VT, Expand);
285     setOperationAction(ISD::UREM, VT, Expand);
286
287     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
288     setOperationAction(ISD::ADDC, VT, Custom);
289     setOperationAction(ISD::ADDE, VT, Custom);
290     setOperationAction(ISD::SUBC, VT, Custom);
291     setOperationAction(ISD::SUBE, VT, Custom);
292   }
293
294   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
295   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
296   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::f128,  Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::f128,  Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
312   if (Subtarget->is64Bit())
313     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
314   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
315   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
316   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
317   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
318
319   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
320     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
321     // is. We should promote the value to 64-bits to solve this.
322     // This is what the CRT headers do - `fmodf` is an inline header
323     // function casting to f64 and calling `fmod`.
324     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
325   } else {
326     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
327   }
328
329   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
330   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
331   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
332
333   // Promote the i8 variants and force them on up to i32 which has a shorter
334   // encoding.
335   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
336   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
337   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
338   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
339   if (Subtarget->hasBMI()) {
340     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
341     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
342     if (Subtarget->is64Bit())
343       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
344   } else {
345     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
346     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
349   }
350
351   if (Subtarget->hasLZCNT()) {
352     // When promoting the i8 variants, force them to i32 for a shorter
353     // encoding.
354     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
355     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
356     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
357     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
358     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
360     if (Subtarget->is64Bit())
361       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
362   } else {
363     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
364     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
365     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
366     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
367     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
368     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
369     if (Subtarget->is64Bit()) {
370       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
371       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
372     }
373   }
374
375   // Special handling for half-precision floating point conversions.
376   // If we don't have F16C support, then lower half float conversions
377   // into library calls.
378   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
379     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
380     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
381   }
382
383   // There's never any support for operations beyond MVT::f32.
384   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
385   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
386   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
387   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
388
389   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
390   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
391   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
392   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
393   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
394   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
395
396   if (Subtarget->hasPOPCNT()) {
397     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
398   } else {
399     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
400     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
401     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
402     if (Subtarget->is64Bit())
403       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
404   }
405
406   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
407
408   if (!Subtarget->hasMOVBE())
409     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
410
411   // These should be promoted to a larger select which is supported.
412   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
413   // X86 wants to expand cmov itself.
414   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
415   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
416   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
417   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
418   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f128 , Custom);
421   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
422   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
424   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f128 , Custom);
428   setOperationAction(ISD::SETCCE          , MVT::i8   , Custom);
429   setOperationAction(ISD::SETCCE          , MVT::i16  , Custom);
430   setOperationAction(ISD::SETCCE          , MVT::i32  , Custom);
431   if (Subtarget->is64Bit()) {
432     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
433     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
434     setOperationAction(ISD::SETCCE        , MVT::i64  , Custom);
435   }
436   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
437   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
438   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
439   // support continuation, user-level threading, and etc.. As a result, no
440   // other SjLj exception interfaces are implemented and please don't build
441   // your own exception handling based on them.
442   // LLVM/Clang supports zero-cost DWARF exception handling.
443   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
444   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
445
446   // Darwin ABI issue.
447   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
448   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
449   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
450   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
451   if (Subtarget->is64Bit())
452     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
453   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
454   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
455   if (Subtarget->is64Bit()) {
456     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
457     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
458     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
459     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
460     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
461   }
462   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
463   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
464   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
465   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
466   if (Subtarget->is64Bit()) {
467     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
468     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
469     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
470   }
471
472   if (Subtarget->hasSSE1())
473     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
474
475   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
476
477   // Expand certain atomics
478   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
479     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
480     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
481     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
482   }
483
484   if (Subtarget->hasCmpxchg16b()) {
485     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
486   }
487
488   // FIXME - use subtarget debug flags
489   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
490       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
491     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
492   }
493
494   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
495   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
496
497   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
498   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
499
500   setOperationAction(ISD::TRAP, MVT::Other, Legal);
501   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
502
503   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
504   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
505   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
506   if (Subtarget->is64Bit()) {
507     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
509   } else {
510     // TargetInfo::CharPtrBuiltinVaList
511     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
512     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
513   }
514
515   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
516   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
517
518   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
519
520   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
521   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
522   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
523
524   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
525     // f32 and f64 use SSE.
526     // Set up the FP register classes.
527     addRegisterClass(MVT::f32, &X86::FR32RegClass);
528     addRegisterClass(MVT::f64, &X86::FR64RegClass);
529
530     // Use ANDPD to simulate FABS.
531     setOperationAction(ISD::FABS , MVT::f64, Custom);
532     setOperationAction(ISD::FABS , MVT::f32, Custom);
533
534     // Use XORP to simulate FNEG.
535     setOperationAction(ISD::FNEG , MVT::f64, Custom);
536     setOperationAction(ISD::FNEG , MVT::f32, Custom);
537
538     // Use ANDPD and ORPD to simulate FCOPYSIGN.
539     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
540     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
541
542     // Lower this to FGETSIGNx86 plus an AND.
543     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
544     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
545
546     // We don't support sin/cos/fmod
547     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
548     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
549     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
550     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
551     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
552     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
553
554     // Expand FP immediates into loads from the stack, except for the special
555     // cases we handle.
556     addLegalFPImmediate(APFloat(+0.0)); // xorpd
557     addLegalFPImmediate(APFloat(+0.0f)); // xorps
558   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
559     // Use SSE for f32, x87 for f64.
560     // Set up the FP register classes.
561     addRegisterClass(MVT::f32, &X86::FR32RegClass);
562     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
563
564     // Use ANDPS to simulate FABS.
565     setOperationAction(ISD::FABS , MVT::f32, Custom);
566
567     // Use XORP to simulate FNEG.
568     setOperationAction(ISD::FNEG , MVT::f32, Custom);
569
570     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
571
572     // Use ANDPS and ORPS to simulate FCOPYSIGN.
573     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
574     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
575
576     // We don't support sin/cos/fmod
577     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
578     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
579     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
580
581     // Special cases we handle for FP constants.
582     addLegalFPImmediate(APFloat(+0.0f)); // xorps
583     addLegalFPImmediate(APFloat(+0.0)); // FLD0
584     addLegalFPImmediate(APFloat(+1.0)); // FLD1
585     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
586     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
587
588     if (!TM.Options.UnsafeFPMath) {
589       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
590       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
591       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
592     }
593   } else if (!Subtarget->useSoftFloat()) {
594     // f32 and f64 in x87.
595     // Set up the FP register classes.
596     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
597     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
598
599     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
600     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
601     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
603
604     if (!TM.Options.UnsafeFPMath) {
605       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
606       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
607       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
608       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
609       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
610       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
611     }
612     addLegalFPImmediate(APFloat(+0.0)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
616     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
617     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
618     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
619     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
620   }
621
622   // We don't support FMA.
623   setOperationAction(ISD::FMA, MVT::f64, Expand);
624   setOperationAction(ISD::FMA, MVT::f32, Expand);
625
626   // Long double always uses X87, except f128 in MMX.
627   if (!Subtarget->useSoftFloat()) {
628     if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
629       addRegisterClass(MVT::f128, &X86::FR128RegClass);
630       ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
631       setOperationAction(ISD::FABS , MVT::f128, Custom);
632       setOperationAction(ISD::FNEG , MVT::f128, Custom);
633       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
634     }
635
636     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
637     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
638     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
639     {
640       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
641       addLegalFPImmediate(TmpFlt);  // FLD0
642       TmpFlt.changeSign();
643       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
644
645       bool ignored;
646       APFloat TmpFlt2(+1.0);
647       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
648                       &ignored);
649       addLegalFPImmediate(TmpFlt2);  // FLD1
650       TmpFlt2.changeSign();
651       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
652     }
653
654     if (!TM.Options.UnsafeFPMath) {
655       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
656       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
657       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
658     }
659
660     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
661     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
662     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
663     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
664     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
665     setOperationAction(ISD::FMA, MVT::f80, Expand);
666   }
667
668   // Always use a library call for pow.
669   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
670   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
671   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
672
673   setOperationAction(ISD::FLOG, MVT::f80, Expand);
674   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
675   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
676   setOperationAction(ISD::FEXP, MVT::f80, Expand);
677   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
678   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
679   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
680
681   // First set operation action for all vector types to either promote
682   // (for widening) or expand (for scalarization). Then we will selectively
683   // turn on ones that can be effectively codegen'd.
684   for (MVT VT : MVT::vector_valuetypes()) {
685     setOperationAction(ISD::ADD , VT, Expand);
686     setOperationAction(ISD::SUB , VT, Expand);
687     setOperationAction(ISD::FADD, VT, Expand);
688     setOperationAction(ISD::FNEG, VT, Expand);
689     setOperationAction(ISD::FSUB, VT, Expand);
690     setOperationAction(ISD::MUL , VT, Expand);
691     setOperationAction(ISD::FMUL, VT, Expand);
692     setOperationAction(ISD::SDIV, VT, Expand);
693     setOperationAction(ISD::UDIV, VT, Expand);
694     setOperationAction(ISD::FDIV, VT, Expand);
695     setOperationAction(ISD::SREM, VT, Expand);
696     setOperationAction(ISD::UREM, VT, Expand);
697     setOperationAction(ISD::LOAD, VT, Expand);
698     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
699     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
700     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
701     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
702     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
703     setOperationAction(ISD::FABS, VT, Expand);
704     setOperationAction(ISD::FSIN, VT, Expand);
705     setOperationAction(ISD::FSINCOS, VT, Expand);
706     setOperationAction(ISD::FCOS, VT, Expand);
707     setOperationAction(ISD::FSINCOS, VT, Expand);
708     setOperationAction(ISD::FREM, VT, Expand);
709     setOperationAction(ISD::FMA,  VT, Expand);
710     setOperationAction(ISD::FPOWI, VT, Expand);
711     setOperationAction(ISD::FSQRT, VT, Expand);
712     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
713     setOperationAction(ISD::FFLOOR, VT, Expand);
714     setOperationAction(ISD::FCEIL, VT, Expand);
715     setOperationAction(ISD::FTRUNC, VT, Expand);
716     setOperationAction(ISD::FRINT, VT, Expand);
717     setOperationAction(ISD::FNEARBYINT, VT, Expand);
718     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
719     setOperationAction(ISD::MULHS, VT, Expand);
720     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
721     setOperationAction(ISD::MULHU, VT, Expand);
722     setOperationAction(ISD::SDIVREM, VT, Expand);
723     setOperationAction(ISD::UDIVREM, VT, Expand);
724     setOperationAction(ISD::FPOW, VT, Expand);
725     setOperationAction(ISD::CTPOP, VT, Expand);
726     setOperationAction(ISD::CTTZ, VT, Expand);
727     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
728     setOperationAction(ISD::CTLZ, VT, Expand);
729     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
730     setOperationAction(ISD::SHL, VT, Expand);
731     setOperationAction(ISD::SRA, VT, Expand);
732     setOperationAction(ISD::SRL, VT, Expand);
733     setOperationAction(ISD::ROTL, VT, Expand);
734     setOperationAction(ISD::ROTR, VT, Expand);
735     setOperationAction(ISD::BSWAP, VT, Expand);
736     setOperationAction(ISD::SETCC, VT, Expand);
737     setOperationAction(ISD::FLOG, VT, Expand);
738     setOperationAction(ISD::FLOG2, VT, Expand);
739     setOperationAction(ISD::FLOG10, VT, Expand);
740     setOperationAction(ISD::FEXP, VT, Expand);
741     setOperationAction(ISD::FEXP2, VT, Expand);
742     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
743     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
744     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
745     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
746     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
747     setOperationAction(ISD::TRUNCATE, VT, Expand);
748     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
749     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
750     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
751     setOperationAction(ISD::VSELECT, VT, Expand);
752     setOperationAction(ISD::SELECT_CC, VT, Expand);
753     for (MVT InnerVT : MVT::vector_valuetypes()) {
754       setTruncStoreAction(InnerVT, VT, Expand);
755
756       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
757       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
758
759       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
760       // types, we have to deal with them whether we ask for Expansion or not.
761       // Setting Expand causes its own optimisation problems though, so leave
762       // them legal.
763       if (VT.getVectorElementType() == MVT::i1)
764         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
765
766       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
767       // split/scalarized right now.
768       if (VT.getVectorElementType() == MVT::f16)
769         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
770     }
771   }
772
773   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
774   // with -msoft-float, disable use of MMX as well.
775   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
776     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
777     // No operations on x86mmx supported, everything uses intrinsics.
778   }
779
780   // MMX-sized vectors (other than x86mmx) are expected to be expanded
781   // into smaller operations.
782   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
783     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
784     setOperationAction(ISD::AND,                MMXTy,      Expand);
785     setOperationAction(ISD::OR,                 MMXTy,      Expand);
786     setOperationAction(ISD::XOR,                MMXTy,      Expand);
787     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
788     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
789     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
790   }
791   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
792
793   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
794     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
795
796     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
797     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
801     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
802     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
803     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
804     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
805     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
806     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
807     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
808     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
809     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
810   }
811
812   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
813     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
814
815     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
816     // registers cannot be used even for integer operations.
817     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
818     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
819     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
820     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
821
822     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
823     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
824     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
825     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
826     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
827     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
828     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
829     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
830     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
831     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
832     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
833     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
834     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
835     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
836     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
837     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
838     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
839     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
840     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
841     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
842     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
843     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
844     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
845
846     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
847     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
848     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
849     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
850
851     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
852     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
853     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
854     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
855
856     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
857     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
858     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
859     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
860     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
861
862     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
863     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
864     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
865     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
866
867     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
868     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
869     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
870     // ISD::CTTZ v2i64 - scalarization is faster.
871     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
872     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
873     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
874     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
875
876     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
877     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
878       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
879       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
880       setOperationAction(ISD::VSELECT,            VT, Custom);
881       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
882     }
883
884     // We support custom legalizing of sext and anyext loads for specific
885     // memory vector types which we can load as a scalar (or sequence of
886     // scalars) and extend in-register to a legal 128-bit vector type. For sext
887     // loads these must work with a single scalar load.
888     for (MVT VT : MVT::integer_vector_valuetypes()) {
889       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
890       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
891       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
892       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
893       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
894       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
895       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
896       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
897       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
898     }
899
900     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
901     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
902     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
903     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
904     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
905     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
906     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
907     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
908
909     if (Subtarget->is64Bit()) {
910       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
911       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
912     }
913
914     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
915     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
916       setOperationAction(ISD::AND,    VT, Promote);
917       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
918       setOperationAction(ISD::OR,     VT, Promote);
919       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
920       setOperationAction(ISD::XOR,    VT, Promote);
921       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
922       setOperationAction(ISD::LOAD,   VT, Promote);
923       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
924       setOperationAction(ISD::SELECT, VT, Promote);
925       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
926     }
927
928     // Custom lower v2i64 and v2f64 selects.
929     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
930     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
931     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
932     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
933
934     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
935     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
936
937     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
938
939     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
940     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
941     // As there is no 64-bit GPR available, we need build a special custom
942     // sequence to convert from v2i32 to v2f32.
943     if (!Subtarget->is64Bit())
944       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
945
946     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
947     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
948
949     for (MVT VT : MVT::fp_vector_valuetypes())
950       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
951
952     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
953     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
954     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
955   }
956
957   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
958     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
959       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
960       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
961       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
962       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
963       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
964     }
965
966     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
967     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
968     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
969     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
970     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
971     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
972     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
973     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
974
975     // FIXME: Do we need to handle scalar-to-vector here?
976     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
977
978     // We directly match byte blends in the backend as they match the VSELECT
979     // condition form.
980     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
981
982     // SSE41 brings specific instructions for doing vector sign extend even in
983     // cases where we don't have SRA.
984     for (MVT VT : MVT::integer_vector_valuetypes()) {
985       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
986       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
988     }
989
990     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
991     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
997
998     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1004
1005     // i8 and i16 vectors are custom because the source register and source
1006     // source memory operand types are not the same width.  f32 vectors are
1007     // custom since the immediate controlling the insert encodes additional
1008     // information.
1009     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1010     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1013
1014     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1015     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1018
1019     // FIXME: these should be Legal, but that's only for the case where
1020     // the index is constant.  For now custom expand to deal with that.
1021     if (Subtarget->is64Bit()) {
1022       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1023       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1024     }
1025   }
1026
1027   if (Subtarget->hasSSE2()) {
1028     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1029     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1031
1032     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1033     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1034
1035     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1036     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1037
1038     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1039     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1040
1041     // In the customized shift lowering, the legal cases in AVX2 will be
1042     // recognized.
1043     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1044     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1045
1046     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1047     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1048
1049     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1050     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1051   }
1052
1053   if (Subtarget->hasXOP()) {
1054     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1055     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1056     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1059     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1060     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1061     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1062   }
1063
1064   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1065     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1066     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1067     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1068     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1069     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1070     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1071
1072     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1073     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1074     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1075
1076     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1077     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1078     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1080     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1081     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1082     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1083     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1084     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1085     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1086     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1087     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1088
1089     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1090     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1091     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1092     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1093     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1094     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1095     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1096     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1097     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1098     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1099     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1100     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1101
1102     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1103     // even though v8i16 is a legal type.
1104     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1105     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1106     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1107
1108     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1109     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1110     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1111
1112     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1113     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1114
1115     for (MVT VT : MVT::fp_vector_valuetypes())
1116       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1117
1118     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1119     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1120
1121     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1122     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1123
1124     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1125     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1126
1127     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1128     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1129     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1130     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1131
1132     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1133     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1134     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1135
1136     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1137     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1138     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1139     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1140     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1141     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1142     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1143     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1144     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1145     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1146     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1147     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1148
1149     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1150     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1151     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1152     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1153
1154     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1155     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1156     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1157     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1158     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1159     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1160     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1161     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1162
1163     if (Subtarget->hasAnyFMA()) {
1164       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1165       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1166       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1168       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1169       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1170     }
1171
1172     if (Subtarget->hasInt256()) {
1173       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1174       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1175       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1177
1178       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1179       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1180       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1182
1183       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1184       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1185       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1186       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1187
1188       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1189       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1190       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1191       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1192
1193       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1194       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1195       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1196       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1197       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1198       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1199       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1200       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1201       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1202       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1203       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1204       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1205
1206       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1207       // when we have a 256bit-wide blend with immediate.
1208       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1209
1210       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1211       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1212       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1214       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1215       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1216       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1217
1218       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1219       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1221       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1222       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1223       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1224     } else {
1225       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1226       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1227       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1228       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1229
1230       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1231       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1232       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1233       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1234
1235       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1236       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1237       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1238       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1239
1240       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1241       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1242       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1243       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1244       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1245       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1246       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1247       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1248       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1249       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1250       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1251       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1252     }
1253
1254     // In the customized shift lowering, the legal cases in AVX2 will be
1255     // recognized.
1256     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1257     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1258
1259     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1260     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1261
1262     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1263     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1264
1265     // Custom lower several nodes for 256-bit types.
1266     for (MVT VT : MVT::vector_valuetypes()) {
1267       if (VT.getScalarSizeInBits() >= 32) {
1268         setOperationAction(ISD::MLOAD,  VT, Legal);
1269         setOperationAction(ISD::MSTORE, VT, Legal);
1270       }
1271       // Extract subvector is special because the value type
1272       // (result) is 128-bit but the source is 256-bit wide.
1273       if (VT.is128BitVector()) {
1274         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1275       }
1276       // Do not attempt to custom lower other non-256-bit vectors
1277       if (!VT.is256BitVector())
1278         continue;
1279
1280       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1281       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1282       setOperationAction(ISD::VSELECT,            VT, Custom);
1283       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1284       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1285       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1286       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1287       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1288     }
1289
1290     if (Subtarget->hasInt256())
1291       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1292
1293     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1295       setOperationAction(ISD::AND,    VT, Promote);
1296       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1297       setOperationAction(ISD::OR,     VT, Promote);
1298       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1299       setOperationAction(ISD::XOR,    VT, Promote);
1300       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1301       setOperationAction(ISD::LOAD,   VT, Promote);
1302       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1303       setOperationAction(ISD::SELECT, VT, Promote);
1304       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1305     }
1306   }
1307
1308   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1309     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1310     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1311     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1312     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1313
1314     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1315     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1316     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1317
1318     for (MVT VT : MVT::fp_vector_valuetypes())
1319       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1320
1321     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1322     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1323     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1324     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1325     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1326     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1327     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1328     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1329     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1330     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1331     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1332     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1333
1334     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1335     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1336     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1337     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1338     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1339     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1340     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1341     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1342     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1343     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1344     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1345     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1348
1349     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1350     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1351     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1354     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1355     setOperationAction(ISD::FABS,               MVT::v16f32, Custom);
1356
1357     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1358     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1359     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1362     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1363     setOperationAction(ISD::FABS,               MVT::v8f64, Custom);
1364     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1365     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1366
1367     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1368     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1370     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1371     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1372     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1376     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1377     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1379     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1381     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1382     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1383
1384     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1385     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1386     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1387     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1388     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1389     if (Subtarget->hasVLX()){
1390       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1391       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1392       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1393       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1394       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1395
1396       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1397       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1398       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1399       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1400       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1401     } else {
1402       setOperationAction(ISD::MLOAD,    MVT::v8i32, Custom);
1403       setOperationAction(ISD::MLOAD,    MVT::v8f32, Custom);
1404       setOperationAction(ISD::MSTORE,   MVT::v8i32, Custom);
1405       setOperationAction(ISD::MSTORE,   MVT::v8f32, Custom);
1406     }
1407     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1408     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1409     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1410     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1411     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1412     if (Subtarget->hasDQI()) {
1413       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1414       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1415
1416       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1417       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1418       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1419       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1420       if (Subtarget->hasVLX()) {
1421         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1422         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1423         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1424         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1425         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1426         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1427         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1428         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1429       }
1430     }
1431     if (Subtarget->hasVLX()) {
1432       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1433       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1434       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1435       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1436       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1437       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1438       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1439       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1440     }
1441     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1442     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1443     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1444     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1445     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1446     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1447     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1448     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1449     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1450     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1451     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1452     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1453     if (Subtarget->hasDQI()) {
1454       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1455       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1456     }
1457     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1458     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1459     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1460     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1461     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1462     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1463     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1464     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1465     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1466     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1467
1468     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1470     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1471     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1,   Custom);
1473
1474     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1475     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1476
1477     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1478
1479     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1480     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1481     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v16i1, Custom);
1482     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1483     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1484     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1485     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1486     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1487     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1488     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1489     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1490     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1491
1492     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1493     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1494     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1495     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1496     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1497     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1498     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1499     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1500
1501     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1502     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1503
1504     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1505     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1506
1507     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1508
1509     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1510     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1511
1512     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1513     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1514
1515     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1516     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1517
1518     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1519     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1520     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1521     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1522     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1523     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1524
1525     if (Subtarget->hasCDI()) {
1526       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1527       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1528       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1529       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1530
1531       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1532       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1533       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1534       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1535       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1536       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1537       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1538       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1539
1540       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1541       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1542
1543       if (Subtarget->hasVLX()) {
1544         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1545         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1546         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1547         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1548         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1549         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1550         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1551         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1552
1553         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1554         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1555         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1556         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1557       } else {
1558         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1559         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1560         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1561         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1562         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1563         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1564         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1565         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1566       }
1567     } // Subtarget->hasCDI()
1568
1569     if (Subtarget->hasDQI()) {
1570       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1571       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1572       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1573     }
1574     // Custom lower several nodes.
1575     for (MVT VT : MVT::vector_valuetypes()) {
1576       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1577       if (EltSize == 1) {
1578         setOperationAction(ISD::AND, VT, Legal);
1579         setOperationAction(ISD::OR,  VT, Legal);
1580         setOperationAction(ISD::XOR,  VT, Legal);
1581       }
1582       if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1583         setOperationAction(ISD::MGATHER,  VT, Custom);
1584         setOperationAction(ISD::MSCATTER, VT, Custom);
1585       }
1586       // Extract subvector is special because the value type
1587       // (result) is 256/128-bit but the source is 512-bit wide.
1588       if (VT.is128BitVector() || VT.is256BitVector()) {
1589         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1590       }
1591       if (VT.getVectorElementType() == MVT::i1)
1592         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1593
1594       // Do not attempt to custom lower other non-512-bit vectors
1595       if (!VT.is512BitVector())
1596         continue;
1597
1598       if (EltSize >= 32) {
1599         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1600         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1601         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1602         setOperationAction(ISD::VSELECT,             VT, Legal);
1603         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1604         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1605         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1606         setOperationAction(ISD::MLOAD,               VT, Legal);
1607         setOperationAction(ISD::MSTORE,              VT, Legal);
1608         setOperationAction(ISD::MGATHER,  VT, Legal);
1609         setOperationAction(ISD::MSCATTER, VT, Custom);
1610       }
1611     }
1612     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1613       setOperationAction(ISD::SELECT, VT, Promote);
1614       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1615     }
1616   }// has  AVX-512
1617
1618   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1619     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1620     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1621
1622     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1623     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1624
1625     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1626     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1627     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1628     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1629     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1630     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1631     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1632     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1633     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1634     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1635     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1636     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1637     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1638     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1639     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1640     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1641     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1644     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1645     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1646     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1647     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1648     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1649     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1650     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1651     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1652     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1653     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1654     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1655     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1656     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1657     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1658     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1659     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1660     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1661     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1662     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1663     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1664     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1665     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1666     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1667
1668     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1669     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1670     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1671     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1672     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1673     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1674     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1675     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1676
1677     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1678     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1679     if (Subtarget->hasVLX())
1680       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1681
1682     if (Subtarget->hasCDI()) {
1683       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1684       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1685       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1686       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1687     }
1688
1689     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1690       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1691       setOperationAction(ISD::VSELECT,             VT, Legal);
1692       setOperationAction(ISD::SRL,                 VT, Custom);
1693       setOperationAction(ISD::SHL,                 VT, Custom);
1694       setOperationAction(ISD::SRA,                 VT, Custom);
1695
1696       setOperationAction(ISD::AND,    VT, Promote);
1697       AddPromotedToType (ISD::AND,    VT, MVT::v8i64);
1698       setOperationAction(ISD::OR,     VT, Promote);
1699       AddPromotedToType (ISD::OR,     VT, MVT::v8i64);
1700       setOperationAction(ISD::XOR,    VT, Promote);
1701       AddPromotedToType (ISD::XOR,    VT, MVT::v8i64);
1702     }
1703   }
1704
1705   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1706     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1707     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1708
1709     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1710     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1711     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1712     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1713     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1714     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1715     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1716     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1717     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1718     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1719     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1720     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1721
1722     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1723     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1724     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1725     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1726     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1727     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1728     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1729     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1730
1731     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1732     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1733     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1734     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1735     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1736     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1737     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1738     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1739   }
1740
1741   // We want to custom lower some of our intrinsics.
1742   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1743   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1744   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1745   if (!Subtarget->is64Bit()) {
1746     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1747     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1748   }
1749
1750   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1751   // handle type legalization for these operations here.
1752   //
1753   // FIXME: We really should do custom legalization for addition and
1754   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1755   // than generic legalization for 64-bit multiplication-with-overflow, though.
1756   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1757     if (VT == MVT::i64 && !Subtarget->is64Bit())
1758       continue;
1759     // Add/Sub/Mul with overflow operations are custom lowered.
1760     setOperationAction(ISD::SADDO, VT, Custom);
1761     setOperationAction(ISD::UADDO, VT, Custom);
1762     setOperationAction(ISD::SSUBO, VT, Custom);
1763     setOperationAction(ISD::USUBO, VT, Custom);
1764     setOperationAction(ISD::SMULO, VT, Custom);
1765     setOperationAction(ISD::UMULO, VT, Custom);
1766   }
1767
1768   if (!Subtarget->is64Bit()) {
1769     // These libcalls are not available in 32-bit.
1770     setLibcallName(RTLIB::SHL_I128, nullptr);
1771     setLibcallName(RTLIB::SRL_I128, nullptr);
1772     setLibcallName(RTLIB::SRA_I128, nullptr);
1773   }
1774
1775   // Combine sin / cos into one node or libcall if possible.
1776   if (Subtarget->hasSinCos()) {
1777     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1778     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1779     if (Subtarget->isTargetDarwin()) {
1780       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1781       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1782       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1783       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1784     }
1785   }
1786
1787   if (Subtarget->isTargetWin64()) {
1788     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1789     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1790     setOperationAction(ISD::SREM, MVT::i128, Custom);
1791     setOperationAction(ISD::UREM, MVT::i128, Custom);
1792     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1793     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1794   }
1795
1796   // We have target-specific dag combine patterns for the following nodes:
1797   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1798   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1799   setTargetDAGCombine(ISD::BITCAST);
1800   setTargetDAGCombine(ISD::VSELECT);
1801   setTargetDAGCombine(ISD::SELECT);
1802   setTargetDAGCombine(ISD::SHL);
1803   setTargetDAGCombine(ISD::SRA);
1804   setTargetDAGCombine(ISD::SRL);
1805   setTargetDAGCombine(ISD::OR);
1806   setTargetDAGCombine(ISD::AND);
1807   setTargetDAGCombine(ISD::ADD);
1808   setTargetDAGCombine(ISD::FADD);
1809   setTargetDAGCombine(ISD::FSUB);
1810   setTargetDAGCombine(ISD::FNEG);
1811   setTargetDAGCombine(ISD::FMA);
1812   setTargetDAGCombine(ISD::FMAXNUM);
1813   setTargetDAGCombine(ISD::SUB);
1814   setTargetDAGCombine(ISD::LOAD);
1815   setTargetDAGCombine(ISD::MLOAD);
1816   setTargetDAGCombine(ISD::STORE);
1817   setTargetDAGCombine(ISD::MSTORE);
1818   setTargetDAGCombine(ISD::TRUNCATE);
1819   setTargetDAGCombine(ISD::ZERO_EXTEND);
1820   setTargetDAGCombine(ISD::ANY_EXTEND);
1821   setTargetDAGCombine(ISD::SIGN_EXTEND);
1822   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1823   setTargetDAGCombine(ISD::SINT_TO_FP);
1824   setTargetDAGCombine(ISD::UINT_TO_FP);
1825   setTargetDAGCombine(ISD::SETCC);
1826   setTargetDAGCombine(ISD::BUILD_VECTOR);
1827   setTargetDAGCombine(ISD::MUL);
1828   setTargetDAGCombine(ISD::XOR);
1829   setTargetDAGCombine(ISD::MSCATTER);
1830   setTargetDAGCombine(ISD::MGATHER);
1831
1832   computeRegisterProperties(Subtarget->getRegisterInfo());
1833
1834   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1835   MaxStoresPerMemsetOptSize = 8;
1836   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1837   MaxStoresPerMemcpyOptSize = 4;
1838   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1839   MaxStoresPerMemmoveOptSize = 4;
1840   setPrefLoopAlignment(4); // 2^4 bytes.
1841
1842   // A predictable cmov does not hurt on an in-order CPU.
1843   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1844   PredictableSelectIsExpensive = !Subtarget->isAtom();
1845   EnableExtLdPromotion = true;
1846   setPrefFunctionAlignment(4); // 2^4 bytes.
1847
1848   verifyIntrinsicTables();
1849 }
1850
1851 // This has so far only been implemented for 64-bit MachO.
1852 bool X86TargetLowering::useLoadStackGuardNode() const {
1853   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1854 }
1855
1856 TargetLoweringBase::LegalizeTypeAction
1857 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1858   if (ExperimentalVectorWideningLegalization &&
1859       VT.getVectorNumElements() != 1 &&
1860       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1861     return TypeWidenVector;
1862
1863   return TargetLoweringBase::getPreferredVectorAction(VT);
1864 }
1865
1866 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1867                                           EVT VT) const {
1868   if (!VT.isVector())
1869     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1870
1871   if (VT.isSimple()) {
1872     MVT VVT = VT.getSimpleVT();
1873     const unsigned NumElts = VVT.getVectorNumElements();
1874     const MVT EltVT = VVT.getVectorElementType();
1875     if (VVT.is512BitVector()) {
1876       if (Subtarget->hasAVX512())
1877         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1878             EltVT == MVT::f32 || EltVT == MVT::f64)
1879           switch(NumElts) {
1880           case  8: return MVT::v8i1;
1881           case 16: return MVT::v16i1;
1882         }
1883       if (Subtarget->hasBWI())
1884         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1885           switch(NumElts) {
1886           case 32: return MVT::v32i1;
1887           case 64: return MVT::v64i1;
1888         }
1889     }
1890
1891     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1892       if (Subtarget->hasVLX())
1893         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1894             EltVT == MVT::f32 || EltVT == MVT::f64)
1895           switch(NumElts) {
1896           case 2: return MVT::v2i1;
1897           case 4: return MVT::v4i1;
1898           case 8: return MVT::v8i1;
1899         }
1900       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1901         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1902           switch(NumElts) {
1903           case  8: return MVT::v8i1;
1904           case 16: return MVT::v16i1;
1905           case 32: return MVT::v32i1;
1906         }
1907     }
1908   }
1909
1910   return VT.changeVectorElementTypeToInteger();
1911 }
1912
1913 /// Helper for getByValTypeAlignment to determine
1914 /// the desired ByVal argument alignment.
1915 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1916   if (MaxAlign == 16)
1917     return;
1918   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1919     if (VTy->getBitWidth() == 128)
1920       MaxAlign = 16;
1921   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1922     unsigned EltAlign = 0;
1923     getMaxByValAlign(ATy->getElementType(), EltAlign);
1924     if (EltAlign > MaxAlign)
1925       MaxAlign = EltAlign;
1926   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1927     for (auto *EltTy : STy->elements()) {
1928       unsigned EltAlign = 0;
1929       getMaxByValAlign(EltTy, EltAlign);
1930       if (EltAlign > MaxAlign)
1931         MaxAlign = EltAlign;
1932       if (MaxAlign == 16)
1933         break;
1934     }
1935   }
1936 }
1937
1938 /// Return the desired alignment for ByVal aggregate
1939 /// function arguments in the caller parameter area. For X86, aggregates
1940 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1941 /// are at 4-byte boundaries.
1942 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1943                                                   const DataLayout &DL) const {
1944   if (Subtarget->is64Bit()) {
1945     // Max of 8 and alignment of type.
1946     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1947     if (TyAlign > 8)
1948       return TyAlign;
1949     return 8;
1950   }
1951
1952   unsigned Align = 4;
1953   if (Subtarget->hasSSE1())
1954     getMaxByValAlign(Ty, Align);
1955   return Align;
1956 }
1957
1958 /// Returns the target specific optimal type for load
1959 /// and store operations as a result of memset, memcpy, and memmove
1960 /// lowering. If DstAlign is zero that means it's safe to destination
1961 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1962 /// means there isn't a need to check it against alignment requirement,
1963 /// probably because the source does not need to be loaded. If 'IsMemset' is
1964 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1965 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1966 /// source is constant so it does not need to be loaded.
1967 /// It returns EVT::Other if the type should be determined using generic
1968 /// target-independent logic.
1969 EVT
1970 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1971                                        unsigned DstAlign, unsigned SrcAlign,
1972                                        bool IsMemset, bool ZeroMemset,
1973                                        bool MemcpyStrSrc,
1974                                        MachineFunction &MF) const {
1975   const Function *F = MF.getFunction();
1976   if ((!IsMemset || ZeroMemset) &&
1977       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1978     if (Size >= 16 &&
1979         (!Subtarget->isUnalignedMem16Slow() ||
1980          ((DstAlign == 0 || DstAlign >= 16) &&
1981           (SrcAlign == 0 || SrcAlign >= 16)))) {
1982       if (Size >= 32) {
1983         // FIXME: Check if unaligned 32-byte accesses are slow.
1984         if (Subtarget->hasInt256())
1985           return MVT::v8i32;
1986         if (Subtarget->hasFp256())
1987           return MVT::v8f32;
1988       }
1989       if (Subtarget->hasSSE2())
1990         return MVT::v4i32;
1991       if (Subtarget->hasSSE1())
1992         return MVT::v4f32;
1993     } else if (!MemcpyStrSrc && Size >= 8 &&
1994                !Subtarget->is64Bit() &&
1995                Subtarget->hasSSE2()) {
1996       // Do not use f64 to lower memcpy if source is string constant. It's
1997       // better to use i32 to avoid the loads.
1998       return MVT::f64;
1999     }
2000   }
2001   // This is a compromise. If we reach here, unaligned accesses may be slow on
2002   // this target. However, creating smaller, aligned accesses could be even
2003   // slower and would certainly be a lot more code.
2004   if (Subtarget->is64Bit() && Size >= 8)
2005     return MVT::i64;
2006   return MVT::i32;
2007 }
2008
2009 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2010   if (VT == MVT::f32)
2011     return X86ScalarSSEf32;
2012   else if (VT == MVT::f64)
2013     return X86ScalarSSEf64;
2014   return true;
2015 }
2016
2017 bool
2018 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2019                                                   unsigned,
2020                                                   unsigned,
2021                                                   bool *Fast) const {
2022   if (Fast) {
2023     switch (VT.getSizeInBits()) {
2024     default:
2025       // 8-byte and under are always assumed to be fast.
2026       *Fast = true;
2027       break;
2028     case 128:
2029       *Fast = !Subtarget->isUnalignedMem16Slow();
2030       break;
2031     case 256:
2032       *Fast = !Subtarget->isUnalignedMem32Slow();
2033       break;
2034     // TODO: What about AVX-512 (512-bit) accesses?
2035     }
2036   }
2037   // Misaligned accesses of any size are always allowed.
2038   return true;
2039 }
2040
2041 /// Return the entry encoding for a jump table in the
2042 /// current function.  The returned value is a member of the
2043 /// MachineJumpTableInfo::JTEntryKind enum.
2044 unsigned X86TargetLowering::getJumpTableEncoding() const {
2045   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2046   // symbol.
2047   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2048       Subtarget->isPICStyleGOT())
2049     return MachineJumpTableInfo::EK_Custom32;
2050
2051   // Otherwise, use the normal jump table encoding heuristics.
2052   return TargetLowering::getJumpTableEncoding();
2053 }
2054
2055 bool X86TargetLowering::useSoftFloat() const {
2056   return Subtarget->useSoftFloat();
2057 }
2058
2059 const MCExpr *
2060 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2061                                              const MachineBasicBlock *MBB,
2062                                              unsigned uid,MCContext &Ctx) const{
2063   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2064          Subtarget->isPICStyleGOT());
2065   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2066   // entries.
2067   return MCSymbolRefExpr::create(MBB->getSymbol(),
2068                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2069 }
2070
2071 /// Returns relocation base for the given PIC jumptable.
2072 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2073                                                     SelectionDAG &DAG) const {
2074   if (!Subtarget->is64Bit())
2075     // This doesn't have SDLoc associated with it, but is not really the
2076     // same as a Register.
2077     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2078                        getPointerTy(DAG.getDataLayout()));
2079   return Table;
2080 }
2081
2082 /// This returns the relocation base for the given PIC jumptable,
2083 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2084 const MCExpr *X86TargetLowering::
2085 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2086                              MCContext &Ctx) const {
2087   // X86-64 uses RIP relative addressing based on the jump table label.
2088   if (Subtarget->isPICStyleRIPRel())
2089     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2090
2091   // Otherwise, the reference is relative to the PIC base.
2092   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2093 }
2094
2095 std::pair<const TargetRegisterClass *, uint8_t>
2096 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2097                                            MVT VT) const {
2098   const TargetRegisterClass *RRC = nullptr;
2099   uint8_t Cost = 1;
2100   switch (VT.SimpleTy) {
2101   default:
2102     return TargetLowering::findRepresentativeClass(TRI, VT);
2103   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2104     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2105     break;
2106   case MVT::x86mmx:
2107     RRC = &X86::VR64RegClass;
2108     break;
2109   case MVT::f32: case MVT::f64:
2110   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2111   case MVT::v4f32: case MVT::v2f64:
2112   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2113   case MVT::v4f64:
2114     RRC = &X86::VR128RegClass;
2115     break;
2116   }
2117   return std::make_pair(RRC, Cost);
2118 }
2119
2120 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2121                                                unsigned &Offset) const {
2122   if (!Subtarget->isTargetLinux())
2123     return false;
2124
2125   if (Subtarget->is64Bit()) {
2126     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2127     Offset = 0x28;
2128     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2129       AddressSpace = 256;
2130     else
2131       AddressSpace = 257;
2132   } else {
2133     // %gs:0x14 on i386
2134     Offset = 0x14;
2135     AddressSpace = 256;
2136   }
2137   return true;
2138 }
2139
2140 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2141   if (!Subtarget->isTargetAndroid())
2142     return TargetLowering::getSafeStackPointerLocation(IRB);
2143
2144   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2145   // definition of TLS_SLOT_SAFESTACK in
2146   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2147   unsigned AddressSpace, Offset;
2148   if (Subtarget->is64Bit()) {
2149     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2150     Offset = 0x48;
2151     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2152       AddressSpace = 256;
2153     else
2154       AddressSpace = 257;
2155   } else {
2156     // %gs:0x24 on i386
2157     Offset = 0x24;
2158     AddressSpace = 256;
2159   }
2160
2161   return ConstantExpr::getIntToPtr(
2162       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2163       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2164 }
2165
2166 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2167                                             unsigned DestAS) const {
2168   assert(SrcAS != DestAS && "Expected different address spaces!");
2169
2170   return SrcAS < 256 && DestAS < 256;
2171 }
2172
2173 //===----------------------------------------------------------------------===//
2174 //               Return Value Calling Convention Implementation
2175 //===----------------------------------------------------------------------===//
2176
2177 #include "X86GenCallingConv.inc"
2178
2179 bool X86TargetLowering::CanLowerReturn(
2180     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2181     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2182   SmallVector<CCValAssign, 16> RVLocs;
2183   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2184   return CCInfo.CheckReturn(Outs, RetCC_X86);
2185 }
2186
2187 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2188   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2189   return ScratchRegs;
2190 }
2191
2192 SDValue
2193 X86TargetLowering::LowerReturn(SDValue Chain,
2194                                CallingConv::ID CallConv, bool isVarArg,
2195                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2196                                const SmallVectorImpl<SDValue> &OutVals,
2197                                SDLoc dl, SelectionDAG &DAG) const {
2198   MachineFunction &MF = DAG.getMachineFunction();
2199   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2200
2201   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2202     report_fatal_error("X86 interrupts may not return any value");
2203
2204   SmallVector<CCValAssign, 16> RVLocs;
2205   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2206   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2207
2208   SDValue Flag;
2209   SmallVector<SDValue, 6> RetOps;
2210   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2211   // Operand #1 = Bytes To Pop
2212   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2213                    MVT::i16));
2214
2215   // Copy the result values into the output registers.
2216   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2217     CCValAssign &VA = RVLocs[i];
2218     assert(VA.isRegLoc() && "Can only return in registers!");
2219     SDValue ValToCopy = OutVals[i];
2220     EVT ValVT = ValToCopy.getValueType();
2221
2222     // Promote values to the appropriate types.
2223     if (VA.getLocInfo() == CCValAssign::SExt)
2224       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2225     else if (VA.getLocInfo() == CCValAssign::ZExt)
2226       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2227     else if (VA.getLocInfo() == CCValAssign::AExt) {
2228       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2229         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2230       else
2231         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2232     }
2233     else if (VA.getLocInfo() == CCValAssign::BCvt)
2234       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2235
2236     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2237            "Unexpected FP-extend for return value.");
2238
2239     // If this is x86-64, and we disabled SSE, we can't return FP values,
2240     // or SSE or MMX vectors.
2241     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2242          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2243           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2244       report_fatal_error("SSE register return with SSE disabled");
2245     }
2246     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2247     // llvm-gcc has never done it right and no one has noticed, so this
2248     // should be OK for now.
2249     if (ValVT == MVT::f64 &&
2250         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2251       report_fatal_error("SSE2 register return with SSE2 disabled");
2252
2253     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2254     // the RET instruction and handled by the FP Stackifier.
2255     if (VA.getLocReg() == X86::FP0 ||
2256         VA.getLocReg() == X86::FP1) {
2257       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2258       // change the value to the FP stack register class.
2259       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2260         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2261       RetOps.push_back(ValToCopy);
2262       // Don't emit a copytoreg.
2263       continue;
2264     }
2265
2266     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2267     // which is returned in RAX / RDX.
2268     if (Subtarget->is64Bit()) {
2269       if (ValVT == MVT::x86mmx) {
2270         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2271           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2272           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2273                                   ValToCopy);
2274           // If we don't have SSE2 available, convert to v4f32 so the generated
2275           // register is legal.
2276           if (!Subtarget->hasSSE2())
2277             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2278         }
2279       }
2280     }
2281
2282     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2283     Flag = Chain.getValue(1);
2284     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2285   }
2286
2287   // All x86 ABIs require that for returning structs by value we copy
2288   // the sret argument into %rax/%eax (depending on ABI) for the return.
2289   // We saved the argument into a virtual register in the entry block,
2290   // so now we copy the value out and into %rax/%eax.
2291   //
2292   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2293   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2294   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2295   // either case FuncInfo->setSRetReturnReg() will have been called.
2296   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2297     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2298                                      getPointerTy(MF.getDataLayout()));
2299
2300     unsigned RetValReg
2301         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2302           X86::RAX : X86::EAX;
2303     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2304     Flag = Chain.getValue(1);
2305
2306     // RAX/EAX now acts like a return value.
2307     RetOps.push_back(
2308         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2309   }
2310
2311   RetOps[0] = Chain;  // Update chain.
2312
2313   // Add the flag if we have it.
2314   if (Flag.getNode())
2315     RetOps.push_back(Flag);
2316
2317   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2318   if (CallConv == CallingConv::X86_INTR)
2319     opcode = X86ISD::IRET;
2320   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2321 }
2322
2323 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2324   if (N->getNumValues() != 1)
2325     return false;
2326   if (!N->hasNUsesOfValue(1, 0))
2327     return false;
2328
2329   SDValue TCChain = Chain;
2330   SDNode *Copy = *N->use_begin();
2331   if (Copy->getOpcode() == ISD::CopyToReg) {
2332     // If the copy has a glue operand, we conservatively assume it isn't safe to
2333     // perform a tail call.
2334     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2335       return false;
2336     TCChain = Copy->getOperand(0);
2337   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2338     return false;
2339
2340   bool HasRet = false;
2341   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2342        UI != UE; ++UI) {
2343     if (UI->getOpcode() != X86ISD::RET_FLAG)
2344       return false;
2345     // If we are returning more than one value, we can definitely
2346     // not make a tail call see PR19530
2347     if (UI->getNumOperands() > 4)
2348       return false;
2349     if (UI->getNumOperands() == 4 &&
2350         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2351       return false;
2352     HasRet = true;
2353   }
2354
2355   if (!HasRet)
2356     return false;
2357
2358   Chain = TCChain;
2359   return true;
2360 }
2361
2362 EVT
2363 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2364                                             ISD::NodeType ExtendKind) const {
2365   MVT ReturnMVT;
2366   // TODO: Is this also valid on 32-bit?
2367   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2368     ReturnMVT = MVT::i8;
2369   else
2370     ReturnMVT = MVT::i32;
2371
2372   EVT MinVT = getRegisterType(Context, ReturnMVT);
2373   return VT.bitsLT(MinVT) ? MinVT : VT;
2374 }
2375
2376 /// Lower the result values of a call into the
2377 /// appropriate copies out of appropriate physical registers.
2378 ///
2379 SDValue
2380 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2381                                    CallingConv::ID CallConv, bool isVarArg,
2382                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2383                                    SDLoc dl, SelectionDAG &DAG,
2384                                    SmallVectorImpl<SDValue> &InVals) const {
2385
2386   // Assign locations to each value returned by this call.
2387   SmallVector<CCValAssign, 16> RVLocs;
2388   bool Is64Bit = Subtarget->is64Bit();
2389   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2390                  *DAG.getContext());
2391   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2392
2393   // Copy all of the result registers out of their specified physreg.
2394   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2395     CCValAssign &VA = RVLocs[i];
2396     EVT CopyVT = VA.getLocVT();
2397
2398     // If this is x86-64, and we disabled SSE, we can't return FP values
2399     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2400         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2401       report_fatal_error("SSE register return with SSE disabled");
2402     }
2403
2404     // If we prefer to use the value in xmm registers, copy it out as f80 and
2405     // use a truncate to move it from fp stack reg to xmm reg.
2406     bool RoundAfterCopy = false;
2407     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2408         isScalarFPTypeInSSEReg(VA.getValVT())) {
2409       CopyVT = MVT::f80;
2410       RoundAfterCopy = (CopyVT != VA.getLocVT());
2411     }
2412
2413     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2414                                CopyVT, InFlag).getValue(1);
2415     SDValue Val = Chain.getValue(0);
2416
2417     if (RoundAfterCopy)
2418       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2419                         // This truncation won't change the value.
2420                         DAG.getIntPtrConstant(1, dl));
2421
2422     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2423       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2424
2425     InFlag = Chain.getValue(2);
2426     InVals.push_back(Val);
2427   }
2428
2429   return Chain;
2430 }
2431
2432 //===----------------------------------------------------------------------===//
2433 //                C & StdCall & Fast Calling Convention implementation
2434 //===----------------------------------------------------------------------===//
2435 //  StdCall calling convention seems to be standard for many Windows' API
2436 //  routines and around. It differs from C calling convention just a little:
2437 //  callee should clean up the stack, not caller. Symbols should be also
2438 //  decorated in some fancy way :) It doesn't support any vector arguments.
2439 //  For info on fast calling convention see Fast Calling Convention (tail call)
2440 //  implementation LowerX86_32FastCCCallTo.
2441
2442 /// CallIsStructReturn - Determines whether a call uses struct return
2443 /// semantics.
2444 enum StructReturnType {
2445   NotStructReturn,
2446   RegStructReturn,
2447   StackStructReturn
2448 };
2449 static StructReturnType
2450 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2451   if (Outs.empty())
2452     return NotStructReturn;
2453
2454   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2455   if (!Flags.isSRet())
2456     return NotStructReturn;
2457   if (Flags.isInReg())
2458     return RegStructReturn;
2459   return StackStructReturn;
2460 }
2461
2462 /// Determines whether a function uses struct return semantics.
2463 static StructReturnType
2464 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2465   if (Ins.empty())
2466     return NotStructReturn;
2467
2468   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2469   if (!Flags.isSRet())
2470     return NotStructReturn;
2471   if (Flags.isInReg())
2472     return RegStructReturn;
2473   return StackStructReturn;
2474 }
2475
2476 /// Make a copy of an aggregate at address specified by "Src" to address
2477 /// "Dst" with size and alignment information specified by the specific
2478 /// parameter attribute. The copy will be passed as a byval function parameter.
2479 static SDValue
2480 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2481                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2482                           SDLoc dl) {
2483   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2484
2485   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2486                        /*isVolatile*/false, /*AlwaysInline=*/true,
2487                        /*isTailCall*/false,
2488                        MachinePointerInfo(), MachinePointerInfo());
2489 }
2490
2491 /// Return true if the calling convention is one that we can guarantee TCO for.
2492 static bool canGuaranteeTCO(CallingConv::ID CC) {
2493   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2494           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2495 }
2496
2497 /// Return true if we might ever do TCO for calls with this calling convention.
2498 static bool mayTailCallThisCC(CallingConv::ID CC) {
2499   switch (CC) {
2500   // C calling conventions:
2501   case CallingConv::C:
2502   case CallingConv::X86_64_Win64:
2503   case CallingConv::X86_64_SysV:
2504   // Callee pop conventions:
2505   case CallingConv::X86_ThisCall:
2506   case CallingConv::X86_StdCall:
2507   case CallingConv::X86_VectorCall:
2508   case CallingConv::X86_FastCall:
2509     return true;
2510   default:
2511     return canGuaranteeTCO(CC);
2512   }
2513 }
2514
2515 /// Return true if the function is being made into a tailcall target by
2516 /// changing its ABI.
2517 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2518   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2519 }
2520
2521 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2522   auto Attr =
2523       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2524   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2525     return false;
2526
2527   CallSite CS(CI);
2528   CallingConv::ID CalleeCC = CS.getCallingConv();
2529   if (!mayTailCallThisCC(CalleeCC))
2530     return false;
2531
2532   return true;
2533 }
2534
2535 SDValue
2536 X86TargetLowering::LowerMemArgument(SDValue Chain,
2537                                     CallingConv::ID CallConv,
2538                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2539                                     SDLoc dl, SelectionDAG &DAG,
2540                                     const CCValAssign &VA,
2541                                     MachineFrameInfo *MFI,
2542                                     unsigned i) const {
2543   // Create the nodes corresponding to a load from this parameter slot.
2544   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2545   bool AlwaysUseMutable = shouldGuaranteeTCO(
2546       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2547   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2548   EVT ValVT;
2549
2550   // If value is passed by pointer we have address passed instead of the value
2551   // itself.
2552   bool ExtendedInMem = VA.isExtInLoc() &&
2553     VA.getValVT().getScalarType() == MVT::i1;
2554
2555   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2556     ValVT = VA.getLocVT();
2557   else
2558     ValVT = VA.getValVT();
2559
2560   // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2561   // taken by a return address.
2562   int Offset = 0;
2563   if (CallConv == CallingConv::X86_INTR) {
2564     const X86Subtarget& Subtarget =
2565         static_cast<const X86Subtarget&>(DAG.getSubtarget());
2566     // X86 interrupts may take one or two arguments.
2567     // On the stack there will be no return address as in regular call.
2568     // Offset of last argument need to be set to -4/-8 bytes.
2569     // Where offset of the first argument out of two, should be set to 0 bytes.
2570     Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2571   }
2572
2573   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2574   // changed with more analysis.
2575   // In case of tail call optimization mark all arguments mutable. Since they
2576   // could be overwritten by lowering of arguments in case of a tail call.
2577   if (Flags.isByVal()) {
2578     unsigned Bytes = Flags.getByValSize();
2579     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2580     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2581     // Adjust SP offset of interrupt parameter.
2582     if (CallConv == CallingConv::X86_INTR) {
2583       MFI->setObjectOffset(FI, Offset);
2584     }
2585     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2586   } else {
2587     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2588                                     VA.getLocMemOffset(), isImmutable);
2589     // Adjust SP offset of interrupt parameter.
2590     if (CallConv == CallingConv::X86_INTR) {
2591       MFI->setObjectOffset(FI, Offset);
2592     }
2593
2594     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2595     SDValue Val = DAG.getLoad(
2596         ValVT, dl, Chain, FIN,
2597         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2598         false, false, 0);
2599     return ExtendedInMem ?
2600       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2601   }
2602 }
2603
2604 // FIXME: Get this from tablegen.
2605 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2606                                                 const X86Subtarget *Subtarget) {
2607   assert(Subtarget->is64Bit());
2608
2609   if (Subtarget->isCallingConvWin64(CallConv)) {
2610     static const MCPhysReg GPR64ArgRegsWin64[] = {
2611       X86::RCX, X86::RDX, X86::R8,  X86::R9
2612     };
2613     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2614   }
2615
2616   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2617     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2618   };
2619   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2620 }
2621
2622 // FIXME: Get this from tablegen.
2623 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2624                                                 CallingConv::ID CallConv,
2625                                                 const X86Subtarget *Subtarget) {
2626   assert(Subtarget->is64Bit());
2627   if (Subtarget->isCallingConvWin64(CallConv)) {
2628     // The XMM registers which might contain var arg parameters are shadowed
2629     // in their paired GPR.  So we only need to save the GPR to their home
2630     // slots.
2631     // TODO: __vectorcall will change this.
2632     return None;
2633   }
2634
2635   const Function *Fn = MF.getFunction();
2636   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2637   bool isSoftFloat = Subtarget->useSoftFloat();
2638   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2639          "SSE register cannot be used when SSE is disabled!");
2640   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2641     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2642     // registers.
2643     return None;
2644
2645   static const MCPhysReg XMMArgRegs64Bit[] = {
2646     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2647     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2648   };
2649   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2650 }
2651
2652 SDValue X86TargetLowering::LowerFormalArguments(
2653     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2654     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2655     SmallVectorImpl<SDValue> &InVals) const {
2656   MachineFunction &MF = DAG.getMachineFunction();
2657   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2658   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2659
2660   const Function* Fn = MF.getFunction();
2661   if (Fn->hasExternalLinkage() &&
2662       Subtarget->isTargetCygMing() &&
2663       Fn->getName() == "main")
2664     FuncInfo->setForceFramePointer(true);
2665
2666   MachineFrameInfo *MFI = MF.getFrameInfo();
2667   bool Is64Bit = Subtarget->is64Bit();
2668   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2669
2670   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2671          "Var args not supported with calling convention fastcc, ghc or hipe");
2672
2673   if (CallConv == CallingConv::X86_INTR) {
2674     bool isLegal = Ins.size() == 1 ||
2675                    (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2676                                         (!Is64Bit && Ins[1].VT == MVT::i32)));
2677     if (!isLegal)
2678       report_fatal_error("X86 interrupts may take one or two arguments");
2679   }
2680
2681   // Assign locations to all of the incoming arguments.
2682   SmallVector<CCValAssign, 16> ArgLocs;
2683   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2684
2685   // Allocate shadow area for Win64
2686   if (IsWin64)
2687     CCInfo.AllocateStack(32, 8);
2688
2689   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2690
2691   unsigned LastVal = ~0U;
2692   SDValue ArgValue;
2693   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2694     CCValAssign &VA = ArgLocs[i];
2695     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2696     // places.
2697     assert(VA.getValNo() != LastVal &&
2698            "Don't support value assigned to multiple locs yet");
2699     (void)LastVal;
2700     LastVal = VA.getValNo();
2701
2702     if (VA.isRegLoc()) {
2703       EVT RegVT = VA.getLocVT();
2704       const TargetRegisterClass *RC;
2705       if (RegVT == MVT::i32)
2706         RC = &X86::GR32RegClass;
2707       else if (Is64Bit && RegVT == MVT::i64)
2708         RC = &X86::GR64RegClass;
2709       else if (RegVT == MVT::f32)
2710         RC = &X86::FR32RegClass;
2711       else if (RegVT == MVT::f64)
2712         RC = &X86::FR64RegClass;
2713       else if (RegVT == MVT::f128)
2714         RC = &X86::FR128RegClass;
2715       else if (RegVT.is512BitVector())
2716         RC = &X86::VR512RegClass;
2717       else if (RegVT.is256BitVector())
2718         RC = &X86::VR256RegClass;
2719       else if (RegVT.is128BitVector())
2720         RC = &X86::VR128RegClass;
2721       else if (RegVT == MVT::x86mmx)
2722         RC = &X86::VR64RegClass;
2723       else if (RegVT == MVT::i1)
2724         RC = &X86::VK1RegClass;
2725       else if (RegVT == MVT::v8i1)
2726         RC = &X86::VK8RegClass;
2727       else if (RegVT == MVT::v16i1)
2728         RC = &X86::VK16RegClass;
2729       else if (RegVT == MVT::v32i1)
2730         RC = &X86::VK32RegClass;
2731       else if (RegVT == MVT::v64i1)
2732         RC = &X86::VK64RegClass;
2733       else
2734         llvm_unreachable("Unknown argument type!");
2735
2736       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2737       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2738
2739       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2740       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2741       // right size.
2742       if (VA.getLocInfo() == CCValAssign::SExt)
2743         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2744                                DAG.getValueType(VA.getValVT()));
2745       else if (VA.getLocInfo() == CCValAssign::ZExt)
2746         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2747                                DAG.getValueType(VA.getValVT()));
2748       else if (VA.getLocInfo() == CCValAssign::BCvt)
2749         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2750
2751       if (VA.isExtInLoc()) {
2752         // Handle MMX values passed in XMM regs.
2753         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2754           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2755         else
2756           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2757       }
2758     } else {
2759       assert(VA.isMemLoc());
2760       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2761     }
2762
2763     // If value is passed via pointer - do a load.
2764     if (VA.getLocInfo() == CCValAssign::Indirect)
2765       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2766                              MachinePointerInfo(), false, false, false, 0);
2767
2768     InVals.push_back(ArgValue);
2769   }
2770
2771   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2772     // All x86 ABIs require that for returning structs by value we copy the
2773     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2774     // the argument into a virtual register so that we can access it from the
2775     // return points.
2776     if (Ins[i].Flags.isSRet()) {
2777       unsigned Reg = FuncInfo->getSRetReturnReg();
2778       if (!Reg) {
2779         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2780         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2781         FuncInfo->setSRetReturnReg(Reg);
2782       }
2783       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2784       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2785       break;
2786     }
2787   }
2788
2789   unsigned StackSize = CCInfo.getNextStackOffset();
2790   // Align stack specially for tail calls.
2791   if (shouldGuaranteeTCO(CallConv,
2792                          MF.getTarget().Options.GuaranteedTailCallOpt))
2793     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2794
2795   // If the function takes variable number of arguments, make a frame index for
2796   // the start of the first vararg value... for expansion of llvm.va_start. We
2797   // can skip this if there are no va_start calls.
2798   if (MFI->hasVAStart() &&
2799       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2800                    CallConv != CallingConv::X86_ThisCall))) {
2801     FuncInfo->setVarArgsFrameIndex(
2802         MFI->CreateFixedObject(1, StackSize, true));
2803   }
2804
2805   // Figure out if XMM registers are in use.
2806   assert(!(Subtarget->useSoftFloat() &&
2807            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2808          "SSE register cannot be used when SSE is disabled!");
2809
2810   // 64-bit calling conventions support varargs and register parameters, so we
2811   // have to do extra work to spill them in the prologue.
2812   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2813     // Find the first unallocated argument registers.
2814     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2815     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2816     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2817     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2818     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2819            "SSE register cannot be used when SSE is disabled!");
2820
2821     // Gather all the live in physical registers.
2822     SmallVector<SDValue, 6> LiveGPRs;
2823     SmallVector<SDValue, 8> LiveXMMRegs;
2824     SDValue ALVal;
2825     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2826       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2827       LiveGPRs.push_back(
2828           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2829     }
2830     if (!ArgXMMs.empty()) {
2831       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2832       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2833       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2834         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2835         LiveXMMRegs.push_back(
2836             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2837       }
2838     }
2839
2840     if (IsWin64) {
2841       // Get to the caller-allocated home save location.  Add 8 to account
2842       // for the return address.
2843       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2844       FuncInfo->setRegSaveFrameIndex(
2845           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2846       // Fixup to set vararg frame on shadow area (4 x i64).
2847       if (NumIntRegs < 4)
2848         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2849     } else {
2850       // For X86-64, if there are vararg parameters that are passed via
2851       // registers, then we must store them to their spots on the stack so
2852       // they may be loaded by deferencing the result of va_next.
2853       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2854       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2855       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2856           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2857     }
2858
2859     // Store the integer parameter registers.
2860     SmallVector<SDValue, 8> MemOps;
2861     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2862                                       getPointerTy(DAG.getDataLayout()));
2863     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2864     for (SDValue Val : LiveGPRs) {
2865       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2866                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2867       SDValue Store =
2868           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2869                        MachinePointerInfo::getFixedStack(
2870                            DAG.getMachineFunction(),
2871                            FuncInfo->getRegSaveFrameIndex(), Offset),
2872                        false, false, 0);
2873       MemOps.push_back(Store);
2874       Offset += 8;
2875     }
2876
2877     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2878       // Now store the XMM (fp + vector) parameter registers.
2879       SmallVector<SDValue, 12> SaveXMMOps;
2880       SaveXMMOps.push_back(Chain);
2881       SaveXMMOps.push_back(ALVal);
2882       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2883                              FuncInfo->getRegSaveFrameIndex(), dl));
2884       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2885                              FuncInfo->getVarArgsFPOffset(), dl));
2886       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2887                         LiveXMMRegs.end());
2888       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2889                                    MVT::Other, SaveXMMOps));
2890     }
2891
2892     if (!MemOps.empty())
2893       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2894   }
2895
2896   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2897     // Find the largest legal vector type.
2898     MVT VecVT = MVT::Other;
2899     // FIXME: Only some x86_32 calling conventions support AVX512.
2900     if (Subtarget->hasAVX512() &&
2901         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2902                      CallConv == CallingConv::Intel_OCL_BI)))
2903       VecVT = MVT::v16f32;
2904     else if (Subtarget->hasAVX())
2905       VecVT = MVT::v8f32;
2906     else if (Subtarget->hasSSE2())
2907       VecVT = MVT::v4f32;
2908
2909     // We forward some GPRs and some vector types.
2910     SmallVector<MVT, 2> RegParmTypes;
2911     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2912     RegParmTypes.push_back(IntVT);
2913     if (VecVT != MVT::Other)
2914       RegParmTypes.push_back(VecVT);
2915
2916     // Compute the set of forwarded registers. The rest are scratch.
2917     SmallVectorImpl<ForwardedRegister> &Forwards =
2918         FuncInfo->getForwardedMustTailRegParms();
2919     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2920
2921     // Conservatively forward AL on x86_64, since it might be used for varargs.
2922     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2923       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2924       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2925     }
2926
2927     // Copy all forwards from physical to virtual registers.
2928     for (ForwardedRegister &F : Forwards) {
2929       // FIXME: Can we use a less constrained schedule?
2930       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2931       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2932       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2933     }
2934   }
2935
2936   // Some CCs need callee pop.
2937   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2938                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2939     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2940   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2941     // X86 interrupts must pop the error code if present
2942     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2943   } else {
2944     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2945     // If this is an sret function, the return should pop the hidden pointer.
2946     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2947         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2948         argsAreStructReturn(Ins) == StackStructReturn)
2949       FuncInfo->setBytesToPopOnReturn(4);
2950   }
2951
2952   if (!Is64Bit) {
2953     // RegSaveFrameIndex is X86-64 only.
2954     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2955     if (CallConv == CallingConv::X86_FastCall ||
2956         CallConv == CallingConv::X86_ThisCall)
2957       // fastcc functions can't have varargs.
2958       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2959   }
2960
2961   FuncInfo->setArgumentStackSize(StackSize);
2962
2963   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2964     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2965     if (Personality == EHPersonality::CoreCLR) {
2966       assert(Is64Bit);
2967       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2968       // that we'd prefer this slot be allocated towards the bottom of the frame
2969       // (i.e. near the stack pointer after allocating the frame).  Every
2970       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2971       // offset from the bottom of this and each funclet's frame must be the
2972       // same, so the size of funclets' (mostly empty) frames is dictated by
2973       // how far this slot is from the bottom (since they allocate just enough
2974       // space to accomodate holding this slot at the correct offset).
2975       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2976       EHInfo->PSPSymFrameIdx = PSPSymFI;
2977     }
2978   }
2979
2980   return Chain;
2981 }
2982
2983 SDValue
2984 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2985                                     SDValue StackPtr, SDValue Arg,
2986                                     SDLoc dl, SelectionDAG &DAG,
2987                                     const CCValAssign &VA,
2988                                     ISD::ArgFlagsTy Flags) const {
2989   unsigned LocMemOffset = VA.getLocMemOffset();
2990   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2991   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2992                        StackPtr, PtrOff);
2993   if (Flags.isByVal())
2994     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2995
2996   return DAG.getStore(
2997       Chain, dl, Arg, PtrOff,
2998       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2999       false, false, 0);
3000 }
3001
3002 /// Emit a load of return address if tail call
3003 /// optimization is performed and it is required.
3004 SDValue
3005 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3006                                            SDValue &OutRetAddr, SDValue Chain,
3007                                            bool IsTailCall, bool Is64Bit,
3008                                            int FPDiff, SDLoc dl) const {
3009   // Adjust the Return address stack slot.
3010   EVT VT = getPointerTy(DAG.getDataLayout());
3011   OutRetAddr = getReturnAddressFrameIndex(DAG);
3012
3013   // Load the "old" Return address.
3014   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3015                            false, false, false, 0);
3016   return SDValue(OutRetAddr.getNode(), 1);
3017 }
3018
3019 /// Emit a store of the return address if tail call
3020 /// optimization is performed and it is required (FPDiff!=0).
3021 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3022                                         SDValue Chain, SDValue RetAddrFrIdx,
3023                                         EVT PtrVT, unsigned SlotSize,
3024                                         int FPDiff, SDLoc dl) {
3025   // Store the return address to the appropriate stack slot.
3026   if (!FPDiff) return Chain;
3027   // Calculate the new stack slot for the return address.
3028   int NewReturnAddrFI =
3029     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3030                                          false);
3031   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3032   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3033                        MachinePointerInfo::getFixedStack(
3034                            DAG.getMachineFunction(), NewReturnAddrFI),
3035                        false, false, 0);
3036   return Chain;
3037 }
3038
3039 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3040 /// operation of specified width.
3041 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3042                        SDValue V2) {
3043   unsigned NumElems = VT.getVectorNumElements();
3044   SmallVector<int, 8> Mask;
3045   Mask.push_back(NumElems);
3046   for (unsigned i = 1; i != NumElems; ++i)
3047     Mask.push_back(i);
3048   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3049 }
3050
3051 SDValue
3052 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3053                              SmallVectorImpl<SDValue> &InVals) const {
3054   SelectionDAG &DAG                     = CLI.DAG;
3055   SDLoc &dl                             = CLI.DL;
3056   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3057   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3058   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3059   SDValue Chain                         = CLI.Chain;
3060   SDValue Callee                        = CLI.Callee;
3061   CallingConv::ID CallConv              = CLI.CallConv;
3062   bool &isTailCall                      = CLI.IsTailCall;
3063   bool isVarArg                         = CLI.IsVarArg;
3064
3065   MachineFunction &MF = DAG.getMachineFunction();
3066   bool Is64Bit        = Subtarget->is64Bit();
3067   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3068   StructReturnType SR = callIsStructReturn(Outs);
3069   bool IsSibcall      = false;
3070   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3071   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3072
3073   if (CallConv == CallingConv::X86_INTR)
3074     report_fatal_error("X86 interrupts may not be called directly");
3075
3076   if (Attr.getValueAsString() == "true")
3077     isTailCall = false;
3078
3079   if (Subtarget->isPICStyleGOT() &&
3080       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3081     // If we are using a GOT, disable tail calls to external symbols with
3082     // default visibility. Tail calling such a symbol requires using a GOT
3083     // relocation, which forces early binding of the symbol. This breaks code
3084     // that require lazy function symbol resolution. Using musttail or
3085     // GuaranteedTailCallOpt will override this.
3086     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3087     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3088                G->getGlobal()->hasDefaultVisibility()))
3089       isTailCall = false;
3090   }
3091
3092   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3093   if (IsMustTail) {
3094     // Force this to be a tail call.  The verifier rules are enough to ensure
3095     // that we can lower this successfully without moving the return address
3096     // around.
3097     isTailCall = true;
3098   } else if (isTailCall) {
3099     // Check if it's really possible to do a tail call.
3100     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3101                     isVarArg, SR != NotStructReturn,
3102                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3103                     Outs, OutVals, Ins, DAG);
3104
3105     // Sibcalls are automatically detected tailcalls which do not require
3106     // ABI changes.
3107     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3108       IsSibcall = true;
3109
3110     if (isTailCall)
3111       ++NumTailCalls;
3112   }
3113
3114   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3115          "Var args not supported with calling convention fastcc, ghc or hipe");
3116
3117   // Analyze operands of the call, assigning locations to each operand.
3118   SmallVector<CCValAssign, 16> ArgLocs;
3119   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3120
3121   // Allocate shadow area for Win64
3122   if (IsWin64)
3123     CCInfo.AllocateStack(32, 8);
3124
3125   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3126
3127   // Get a count of how many bytes are to be pushed on the stack.
3128   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3129   if (IsSibcall)
3130     // This is a sibcall. The memory operands are available in caller's
3131     // own caller's stack.
3132     NumBytes = 0;
3133   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3134            canGuaranteeTCO(CallConv))
3135     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3136
3137   int FPDiff = 0;
3138   if (isTailCall && !IsSibcall && !IsMustTail) {
3139     // Lower arguments at fp - stackoffset + fpdiff.
3140     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3141
3142     FPDiff = NumBytesCallerPushed - NumBytes;
3143
3144     // Set the delta of movement of the returnaddr stackslot.
3145     // But only set if delta is greater than previous delta.
3146     if (FPDiff < X86Info->getTCReturnAddrDelta())
3147       X86Info->setTCReturnAddrDelta(FPDiff);
3148   }
3149
3150   unsigned NumBytesToPush = NumBytes;
3151   unsigned NumBytesToPop = NumBytes;
3152
3153   // If we have an inalloca argument, all stack space has already been allocated
3154   // for us and be right at the top of the stack.  We don't support multiple
3155   // arguments passed in memory when using inalloca.
3156   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3157     NumBytesToPush = 0;
3158     if (!ArgLocs.back().isMemLoc())
3159       report_fatal_error("cannot use inalloca attribute on a register "
3160                          "parameter");
3161     if (ArgLocs.back().getLocMemOffset() != 0)
3162       report_fatal_error("any parameter with the inalloca attribute must be "
3163                          "the only memory argument");
3164   }
3165
3166   if (!IsSibcall)
3167     Chain = DAG.getCALLSEQ_START(
3168         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3169
3170   SDValue RetAddrFrIdx;
3171   // Load return address for tail calls.
3172   if (isTailCall && FPDiff)
3173     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3174                                     Is64Bit, FPDiff, dl);
3175
3176   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3177   SmallVector<SDValue, 8> MemOpChains;
3178   SDValue StackPtr;
3179
3180   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3181   // of tail call optimization arguments are handle later.
3182   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3183   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3184     // Skip inalloca arguments, they have already been written.
3185     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3186     if (Flags.isInAlloca())
3187       continue;
3188
3189     CCValAssign &VA = ArgLocs[i];
3190     EVT RegVT = VA.getLocVT();
3191     SDValue Arg = OutVals[i];
3192     bool isByVal = Flags.isByVal();
3193
3194     // Promote the value if needed.
3195     switch (VA.getLocInfo()) {
3196     default: llvm_unreachable("Unknown loc info!");
3197     case CCValAssign::Full: break;
3198     case CCValAssign::SExt:
3199       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3200       break;
3201     case CCValAssign::ZExt:
3202       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3203       break;
3204     case CCValAssign::AExt:
3205       if (Arg.getValueType().isVector() &&
3206           Arg.getValueType().getVectorElementType() == MVT::i1)
3207         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3208       else if (RegVT.is128BitVector()) {
3209         // Special case: passing MMX values in XMM registers.
3210         Arg = DAG.getBitcast(MVT::i64, Arg);
3211         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3212         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3213       } else
3214         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3215       break;
3216     case CCValAssign::BCvt:
3217       Arg = DAG.getBitcast(RegVT, Arg);
3218       break;
3219     case CCValAssign::Indirect: {
3220       // Store the argument.
3221       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3222       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3223       Chain = DAG.getStore(
3224           Chain, dl, Arg, SpillSlot,
3225           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3226           false, false, 0);
3227       Arg = SpillSlot;
3228       break;
3229     }
3230     }
3231
3232     if (VA.isRegLoc()) {
3233       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3234       if (isVarArg && IsWin64) {
3235         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3236         // shadow reg if callee is a varargs function.
3237         unsigned ShadowReg = 0;
3238         switch (VA.getLocReg()) {
3239         case X86::XMM0: ShadowReg = X86::RCX; break;
3240         case X86::XMM1: ShadowReg = X86::RDX; break;
3241         case X86::XMM2: ShadowReg = X86::R8; break;
3242         case X86::XMM3: ShadowReg = X86::R9; break;
3243         }
3244         if (ShadowReg)
3245           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3246       }
3247     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3248       assert(VA.isMemLoc());
3249       if (!StackPtr.getNode())
3250         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3251                                       getPointerTy(DAG.getDataLayout()));
3252       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3253                                              dl, DAG, VA, Flags));
3254     }
3255   }
3256
3257   if (!MemOpChains.empty())
3258     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3259
3260   if (Subtarget->isPICStyleGOT()) {
3261     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3262     // GOT pointer.
3263     if (!isTailCall) {
3264       RegsToPass.push_back(std::make_pair(
3265           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3266                                           getPointerTy(DAG.getDataLayout()))));
3267     } else {
3268       // If we are tail calling and generating PIC/GOT style code load the
3269       // address of the callee into ECX. The value in ecx is used as target of
3270       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3271       // for tail calls on PIC/GOT architectures. Normally we would just put the
3272       // address of GOT into ebx and then call target@PLT. But for tail calls
3273       // ebx would be restored (since ebx is callee saved) before jumping to the
3274       // target@PLT.
3275
3276       // Note: The actual moving to ECX is done further down.
3277       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3278       if (G && !G->getGlobal()->hasLocalLinkage() &&
3279           G->getGlobal()->hasDefaultVisibility())
3280         Callee = LowerGlobalAddress(Callee, DAG);
3281       else if (isa<ExternalSymbolSDNode>(Callee))
3282         Callee = LowerExternalSymbol(Callee, DAG);
3283     }
3284   }
3285
3286   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3287     // From AMD64 ABI document:
3288     // For calls that may call functions that use varargs or stdargs
3289     // (prototype-less calls or calls to functions containing ellipsis (...) in
3290     // the declaration) %al is used as hidden argument to specify the number
3291     // of SSE registers used. The contents of %al do not need to match exactly
3292     // the number of registers, but must be an ubound on the number of SSE
3293     // registers used and is in the range 0 - 8 inclusive.
3294
3295     // Count the number of XMM registers allocated.
3296     static const MCPhysReg XMMArgRegs[] = {
3297       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3298       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3299     };
3300     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3301     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3302            && "SSE registers cannot be used when SSE is disabled");
3303
3304     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3305                                         DAG.getConstant(NumXMMRegs, dl,
3306                                                         MVT::i8)));
3307   }
3308
3309   if (isVarArg && IsMustTail) {
3310     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3311     for (const auto &F : Forwards) {
3312       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3313       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3314     }
3315   }
3316
3317   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3318   // don't need this because the eligibility check rejects calls that require
3319   // shuffling arguments passed in memory.
3320   if (!IsSibcall && isTailCall) {
3321     // Force all the incoming stack arguments to be loaded from the stack
3322     // before any new outgoing arguments are stored to the stack, because the
3323     // outgoing stack slots may alias the incoming argument stack slots, and
3324     // the alias isn't otherwise explicit. This is slightly more conservative
3325     // than necessary, because it means that each store effectively depends
3326     // on every argument instead of just those arguments it would clobber.
3327     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3328
3329     SmallVector<SDValue, 8> MemOpChains2;
3330     SDValue FIN;
3331     int FI = 0;
3332     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3333       CCValAssign &VA = ArgLocs[i];
3334       if (VA.isRegLoc())
3335         continue;
3336       assert(VA.isMemLoc());
3337       SDValue Arg = OutVals[i];
3338       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3339       // Skip inalloca arguments.  They don't require any work.
3340       if (Flags.isInAlloca())
3341         continue;
3342       // Create frame index.
3343       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3344       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3345       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3346       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3347
3348       if (Flags.isByVal()) {
3349         // Copy relative to framepointer.
3350         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3351         if (!StackPtr.getNode())
3352           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3353                                         getPointerTy(DAG.getDataLayout()));
3354         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3355                              StackPtr, Source);
3356
3357         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3358                                                          ArgChain,
3359                                                          Flags, DAG, dl));
3360       } else {
3361         // Store relative to framepointer.
3362         MemOpChains2.push_back(DAG.getStore(
3363             ArgChain, dl, Arg, FIN,
3364             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3365             false, false, 0));
3366       }
3367     }
3368
3369     if (!MemOpChains2.empty())
3370       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3371
3372     // Store the return address to the appropriate stack slot.
3373     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3374                                      getPointerTy(DAG.getDataLayout()),
3375                                      RegInfo->getSlotSize(), FPDiff, dl);
3376   }
3377
3378   // Build a sequence of copy-to-reg nodes chained together with token chain
3379   // and flag operands which copy the outgoing args into registers.
3380   SDValue InFlag;
3381   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3382     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3383                              RegsToPass[i].second, InFlag);
3384     InFlag = Chain.getValue(1);
3385   }
3386
3387   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3388     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3389     // In the 64-bit large code model, we have to make all calls
3390     // through a register, since the call instruction's 32-bit
3391     // pc-relative offset may not be large enough to hold the whole
3392     // address.
3393   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3394     // If the callee is a GlobalAddress node (quite common, every direct call
3395     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3396     // it.
3397     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3398
3399     // We should use extra load for direct calls to dllimported functions in
3400     // non-JIT mode.
3401     const GlobalValue *GV = G->getGlobal();
3402     if (!GV->hasDLLImportStorageClass()) {
3403       unsigned char OpFlags = 0;
3404       bool ExtraLoad = false;
3405       unsigned WrapperKind = ISD::DELETED_NODE;
3406
3407       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3408       // external symbols most go through the PLT in PIC mode.  If the symbol
3409       // has hidden or protected visibility, or if it is static or local, then
3410       // we don't need to use the PLT - we can directly call it.
3411       if (Subtarget->isTargetELF() &&
3412           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3413           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3414         OpFlags = X86II::MO_PLT;
3415       } else if (Subtarget->isPICStyleStubAny() &&
3416                  !GV->isStrongDefinitionForLinker() &&
3417                  (!Subtarget->getTargetTriple().isMacOSX() ||
3418                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3419         // PC-relative references to external symbols should go through $stub,
3420         // unless we're building with the leopard linker or later, which
3421         // automatically synthesizes these stubs.
3422         OpFlags = X86II::MO_DARWIN_STUB;
3423       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3424                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3425         // If the function is marked as non-lazy, generate an indirect call
3426         // which loads from the GOT directly. This avoids runtime overhead
3427         // at the cost of eager binding (and one extra byte of encoding).
3428         OpFlags = X86II::MO_GOTPCREL;
3429         WrapperKind = X86ISD::WrapperRIP;
3430         ExtraLoad = true;
3431       }
3432
3433       Callee = DAG.getTargetGlobalAddress(
3434           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3435
3436       // Add a wrapper if needed.
3437       if (WrapperKind != ISD::DELETED_NODE)
3438         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3439                              getPointerTy(DAG.getDataLayout()), Callee);
3440       // Add extra indirection if needed.
3441       if (ExtraLoad)
3442         Callee = DAG.getLoad(
3443             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3444             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3445             false, 0);
3446     }
3447   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3448     unsigned char OpFlags = 0;
3449
3450     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3451     // external symbols should go through the PLT.
3452     if (Subtarget->isTargetELF() &&
3453         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3454       OpFlags = X86II::MO_PLT;
3455     } else if (Subtarget->isPICStyleStubAny() &&
3456                (!Subtarget->getTargetTriple().isMacOSX() ||
3457                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3458       // PC-relative references to external symbols should go through $stub,
3459       // unless we're building with the leopard linker or later, which
3460       // automatically synthesizes these stubs.
3461       OpFlags = X86II::MO_DARWIN_STUB;
3462     }
3463
3464     Callee = DAG.getTargetExternalSymbol(
3465         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3466   } else if (Subtarget->isTarget64BitILP32() &&
3467              Callee->getValueType(0) == MVT::i32) {
3468     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3469     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3470   }
3471
3472   // Returns a chain & a flag for retval copy to use.
3473   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3474   SmallVector<SDValue, 8> Ops;
3475
3476   if (!IsSibcall && isTailCall) {
3477     Chain = DAG.getCALLSEQ_END(Chain,
3478                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3479                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3480     InFlag = Chain.getValue(1);
3481   }
3482
3483   Ops.push_back(Chain);
3484   Ops.push_back(Callee);
3485
3486   if (isTailCall)
3487     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3488
3489   // Add argument registers to the end of the list so that they are known live
3490   // into the call.
3491   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3492     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3493                                   RegsToPass[i].second.getValueType()));
3494
3495   // Add a register mask operand representing the call-preserved registers.
3496   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3497   assert(Mask && "Missing call preserved mask for calling convention");
3498
3499   // If this is an invoke in a 32-bit function using a funclet-based
3500   // personality, assume the function clobbers all registers. If an exception
3501   // is thrown, the runtime will not restore CSRs.
3502   // FIXME: Model this more precisely so that we can register allocate across
3503   // the normal edge and spill and fill across the exceptional edge.
3504   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3505     const Function *CallerFn = MF.getFunction();
3506     EHPersonality Pers =
3507         CallerFn->hasPersonalityFn()
3508             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3509             : EHPersonality::Unknown;
3510     if (isFuncletEHPersonality(Pers))
3511       Mask = RegInfo->getNoPreservedMask();
3512   }
3513
3514   Ops.push_back(DAG.getRegisterMask(Mask));
3515
3516   if (InFlag.getNode())
3517     Ops.push_back(InFlag);
3518
3519   if (isTailCall) {
3520     // We used to do:
3521     //// If this is the first return lowered for this function, add the regs
3522     //// to the liveout set for the function.
3523     // This isn't right, although it's probably harmless on x86; liveouts
3524     // should be computed from returns not tail calls.  Consider a void
3525     // function making a tail call to a function returning int.
3526     MF.getFrameInfo()->setHasTailCall();
3527     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3528   }
3529
3530   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3531   InFlag = Chain.getValue(1);
3532
3533   // Create the CALLSEQ_END node.
3534   unsigned NumBytesForCalleeToPop;
3535   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3536                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3537     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3538   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3539            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3540            SR == StackStructReturn)
3541     // If this is a call to a struct-return function, the callee
3542     // pops the hidden struct pointer, so we have to push it back.
3543     // This is common for Darwin/X86, Linux & Mingw32 targets.
3544     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3545     NumBytesForCalleeToPop = 4;
3546   else
3547     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3548
3549   // Returns a flag for retval copy to use.
3550   if (!IsSibcall) {
3551     Chain = DAG.getCALLSEQ_END(Chain,
3552                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3553                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3554                                                      true),
3555                                InFlag, dl);
3556     InFlag = Chain.getValue(1);
3557   }
3558
3559   // Handle result values, copying them out of physregs into vregs that we
3560   // return.
3561   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3562                          Ins, dl, DAG, InVals);
3563 }
3564
3565 //===----------------------------------------------------------------------===//
3566 //                Fast Calling Convention (tail call) implementation
3567 //===----------------------------------------------------------------------===//
3568
3569 //  Like std call, callee cleans arguments, convention except that ECX is
3570 //  reserved for storing the tail called function address. Only 2 registers are
3571 //  free for argument passing (inreg). Tail call optimization is performed
3572 //  provided:
3573 //                * tailcallopt is enabled
3574 //                * caller/callee are fastcc
3575 //  On X86_64 architecture with GOT-style position independent code only local
3576 //  (within module) calls are supported at the moment.
3577 //  To keep the stack aligned according to platform abi the function
3578 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3579 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3580 //  If a tail called function callee has more arguments than the caller the
3581 //  caller needs to make sure that there is room to move the RETADDR to. This is
3582 //  achieved by reserving an area the size of the argument delta right after the
3583 //  original RETADDR, but before the saved framepointer or the spilled registers
3584 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3585 //  stack layout:
3586 //    arg1
3587 //    arg2
3588 //    RETADDR
3589 //    [ new RETADDR
3590 //      move area ]
3591 //    (possible EBP)
3592 //    ESI
3593 //    EDI
3594 //    local1 ..
3595
3596 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3597 /// requirement.
3598 unsigned
3599 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3600                                                SelectionDAG& DAG) const {
3601   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3602   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3603   unsigned StackAlignment = TFI.getStackAlignment();
3604   uint64_t AlignMask = StackAlignment - 1;
3605   int64_t Offset = StackSize;
3606   unsigned SlotSize = RegInfo->getSlotSize();
3607   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3608     // Number smaller than 12 so just add the difference.
3609     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3610   } else {
3611     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3612     Offset = ((~AlignMask) & Offset) + StackAlignment +
3613       (StackAlignment-SlotSize);
3614   }
3615   return Offset;
3616 }
3617
3618 /// Return true if the given stack call argument is already available in the
3619 /// same position (relatively) of the caller's incoming argument stack.
3620 static
3621 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3622                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3623                          const X86InstrInfo *TII) {
3624   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3625   int FI = INT_MAX;
3626   if (Arg.getOpcode() == ISD::CopyFromReg) {
3627     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3628     if (!TargetRegisterInfo::isVirtualRegister(VR))
3629       return false;
3630     MachineInstr *Def = MRI->getVRegDef(VR);
3631     if (!Def)
3632       return false;
3633     if (!Flags.isByVal()) {
3634       if (!TII->isLoadFromStackSlot(Def, FI))
3635         return false;
3636     } else {
3637       unsigned Opcode = Def->getOpcode();
3638       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3639            Opcode == X86::LEA64_32r) &&
3640           Def->getOperand(1).isFI()) {
3641         FI = Def->getOperand(1).getIndex();
3642         Bytes = Flags.getByValSize();
3643       } else
3644         return false;
3645     }
3646   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3647     if (Flags.isByVal())
3648       // ByVal argument is passed in as a pointer but it's now being
3649       // dereferenced. e.g.
3650       // define @foo(%struct.X* %A) {
3651       //   tail call @bar(%struct.X* byval %A)
3652       // }
3653       return false;
3654     SDValue Ptr = Ld->getBasePtr();
3655     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3656     if (!FINode)
3657       return false;
3658     FI = FINode->getIndex();
3659   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3660     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3661     FI = FINode->getIndex();
3662     Bytes = Flags.getByValSize();
3663   } else
3664     return false;
3665
3666   assert(FI != INT_MAX);
3667   if (!MFI->isFixedObjectIndex(FI))
3668     return false;
3669   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3670 }
3671
3672 /// Check whether the call is eligible for tail call optimization. Targets
3673 /// that want to do tail call optimization should implement this function.
3674 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3675     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3676     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3677     const SmallVectorImpl<ISD::OutputArg> &Outs,
3678     const SmallVectorImpl<SDValue> &OutVals,
3679     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3680   if (!mayTailCallThisCC(CalleeCC))
3681     return false;
3682
3683   // If -tailcallopt is specified, make fastcc functions tail-callable.
3684   MachineFunction &MF = DAG.getMachineFunction();
3685   const Function *CallerF = MF.getFunction();
3686
3687   // If the function return type is x86_fp80 and the callee return type is not,
3688   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3689   // perform a tailcall optimization here.
3690   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3691     return false;
3692
3693   CallingConv::ID CallerCC = CallerF->getCallingConv();
3694   bool CCMatch = CallerCC == CalleeCC;
3695   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3696   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3697
3698   // Win64 functions have extra shadow space for argument homing. Don't do the
3699   // sibcall if the caller and callee have mismatched expectations for this
3700   // space.
3701   if (IsCalleeWin64 != IsCallerWin64)
3702     return false;
3703
3704   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3705     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3706       return true;
3707     return false;
3708   }
3709
3710   // Look for obvious safe cases to perform tail call optimization that do not
3711   // require ABI changes. This is what gcc calls sibcall.
3712
3713   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3714   // emit a special epilogue.
3715   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3716   if (RegInfo->needsStackRealignment(MF))
3717     return false;
3718
3719   // Also avoid sibcall optimization if either caller or callee uses struct
3720   // return semantics.
3721   if (isCalleeStructRet || isCallerStructRet)
3722     return false;
3723
3724   // Do not sibcall optimize vararg calls unless all arguments are passed via
3725   // registers.
3726   if (isVarArg && !Outs.empty()) {
3727     // Optimizing for varargs on Win64 is unlikely to be safe without
3728     // additional testing.
3729     if (IsCalleeWin64 || IsCallerWin64)
3730       return false;
3731
3732     SmallVector<CCValAssign, 16> ArgLocs;
3733     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3734                    *DAG.getContext());
3735
3736     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3737     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3738       if (!ArgLocs[i].isRegLoc())
3739         return false;
3740   }
3741
3742   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3743   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3744   // this into a sibcall.
3745   bool Unused = false;
3746   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3747     if (!Ins[i].Used) {
3748       Unused = true;
3749       break;
3750     }
3751   }
3752   if (Unused) {
3753     SmallVector<CCValAssign, 16> RVLocs;
3754     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3755                    *DAG.getContext());
3756     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3757     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3758       CCValAssign &VA = RVLocs[i];
3759       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3760         return false;
3761     }
3762   }
3763
3764   // If the calling conventions do not match, then we'd better make sure the
3765   // results are returned in the same way as what the caller expects.
3766   if (!CCMatch) {
3767     SmallVector<CCValAssign, 16> RVLocs1;
3768     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3769                     *DAG.getContext());
3770     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3771
3772     SmallVector<CCValAssign, 16> RVLocs2;
3773     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3774                     *DAG.getContext());
3775     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3776
3777     if (RVLocs1.size() != RVLocs2.size())
3778       return false;
3779     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3780       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3781         return false;
3782       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3783         return false;
3784       if (RVLocs1[i].isRegLoc()) {
3785         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3786           return false;
3787       } else {
3788         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3789           return false;
3790       }
3791     }
3792   }
3793
3794   unsigned StackArgsSize = 0;
3795
3796   // If the callee takes no arguments then go on to check the results of the
3797   // call.
3798   if (!Outs.empty()) {
3799     // Check if stack adjustment is needed. For now, do not do this if any
3800     // argument is passed on the stack.
3801     SmallVector<CCValAssign, 16> ArgLocs;
3802     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3803                    *DAG.getContext());
3804
3805     // Allocate shadow area for Win64
3806     if (IsCalleeWin64)
3807       CCInfo.AllocateStack(32, 8);
3808
3809     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3810     StackArgsSize = CCInfo.getNextStackOffset();
3811
3812     if (CCInfo.getNextStackOffset()) {
3813       // Check if the arguments are already laid out in the right way as
3814       // the caller's fixed stack objects.
3815       MachineFrameInfo *MFI = MF.getFrameInfo();
3816       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3817       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3818       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3819         CCValAssign &VA = ArgLocs[i];
3820         SDValue Arg = OutVals[i];
3821         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3822         if (VA.getLocInfo() == CCValAssign::Indirect)
3823           return false;
3824         if (!VA.isRegLoc()) {
3825           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3826                                    MFI, MRI, TII))
3827             return false;
3828         }
3829       }
3830     }
3831
3832     // If the tailcall address may be in a register, then make sure it's
3833     // possible to register allocate for it. In 32-bit, the call address can
3834     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3835     // callee-saved registers are restored. These happen to be the same
3836     // registers used to pass 'inreg' arguments so watch out for those.
3837     if (!Subtarget->is64Bit() &&
3838         ((!isa<GlobalAddressSDNode>(Callee) &&
3839           !isa<ExternalSymbolSDNode>(Callee)) ||
3840          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3841       unsigned NumInRegs = 0;
3842       // In PIC we need an extra register to formulate the address computation
3843       // for the callee.
3844       unsigned MaxInRegs =
3845         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3846
3847       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3848         CCValAssign &VA = ArgLocs[i];
3849         if (!VA.isRegLoc())
3850           continue;
3851         unsigned Reg = VA.getLocReg();
3852         switch (Reg) {
3853         default: break;
3854         case X86::EAX: case X86::EDX: case X86::ECX:
3855           if (++NumInRegs == MaxInRegs)
3856             return false;
3857           break;
3858         }
3859       }
3860     }
3861   }
3862
3863   bool CalleeWillPop =
3864       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3865                        MF.getTarget().Options.GuaranteedTailCallOpt);
3866
3867   if (unsigned BytesToPop =
3868           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3869     // If we have bytes to pop, the callee must pop them.
3870     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3871     if (!CalleePopMatches)
3872       return false;
3873   } else if (CalleeWillPop && StackArgsSize > 0) {
3874     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3875     return false;
3876   }
3877
3878   return true;
3879 }
3880
3881 FastISel *
3882 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3883                                   const TargetLibraryInfo *libInfo) const {
3884   return X86::createFastISel(funcInfo, libInfo);
3885 }
3886
3887 //===----------------------------------------------------------------------===//
3888 //                           Other Lowering Hooks
3889 //===----------------------------------------------------------------------===//
3890
3891 static bool MayFoldLoad(SDValue Op) {
3892   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3893 }
3894
3895 static bool MayFoldIntoStore(SDValue Op) {
3896   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3897 }
3898
3899 static bool isTargetShuffle(unsigned Opcode) {
3900   switch(Opcode) {
3901   default: return false;
3902   case X86ISD::BLENDI:
3903   case X86ISD::PSHUFB:
3904   case X86ISD::PSHUFD:
3905   case X86ISD::PSHUFHW:
3906   case X86ISD::PSHUFLW:
3907   case X86ISD::SHUFP:
3908   case X86ISD::PALIGNR:
3909   case X86ISD::MOVLHPS:
3910   case X86ISD::MOVLHPD:
3911   case X86ISD::MOVHLPS:
3912   case X86ISD::MOVLPS:
3913   case X86ISD::MOVLPD:
3914   case X86ISD::MOVSHDUP:
3915   case X86ISD::MOVSLDUP:
3916   case X86ISD::MOVDDUP:
3917   case X86ISD::MOVSS:
3918   case X86ISD::MOVSD:
3919   case X86ISD::UNPCKL:
3920   case X86ISD::UNPCKH:
3921   case X86ISD::VPERMILPI:
3922   case X86ISD::VPERM2X128:
3923   case X86ISD::VPERMI:
3924   case X86ISD::VPERMV:
3925   case X86ISD::VPERMV3:
3926     return true;
3927   }
3928 }
3929
3930 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3931                                     SDValue V1, unsigned TargetMask,
3932                                     SelectionDAG &DAG) {
3933   switch(Opc) {
3934   default: llvm_unreachable("Unknown x86 shuffle node");
3935   case X86ISD::PSHUFD:
3936   case X86ISD::PSHUFHW:
3937   case X86ISD::PSHUFLW:
3938   case X86ISD::VPERMILPI:
3939   case X86ISD::VPERMI:
3940     return DAG.getNode(Opc, dl, VT, V1,
3941                        DAG.getConstant(TargetMask, dl, MVT::i8));
3942   }
3943 }
3944
3945 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3946                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3947   switch(Opc) {
3948   default: llvm_unreachable("Unknown x86 shuffle node");
3949   case X86ISD::MOVLHPS:
3950   case X86ISD::MOVLHPD:
3951   case X86ISD::MOVHLPS:
3952   case X86ISD::MOVLPS:
3953   case X86ISD::MOVLPD:
3954   case X86ISD::MOVSS:
3955   case X86ISD::MOVSD:
3956   case X86ISD::UNPCKL:
3957   case X86ISD::UNPCKH:
3958     return DAG.getNode(Opc, dl, VT, V1, V2);
3959   }
3960 }
3961
3962 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3963   MachineFunction &MF = DAG.getMachineFunction();
3964   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3965   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3966   int ReturnAddrIndex = FuncInfo->getRAIndex();
3967
3968   if (ReturnAddrIndex == 0) {
3969     // Set up a frame object for the return address.
3970     unsigned SlotSize = RegInfo->getSlotSize();
3971     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3972                                                            -(int64_t)SlotSize,
3973                                                            false);
3974     FuncInfo->setRAIndex(ReturnAddrIndex);
3975   }
3976
3977   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3978 }
3979
3980 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3981                                        bool hasSymbolicDisplacement) {
3982   // Offset should fit into 32 bit immediate field.
3983   if (!isInt<32>(Offset))
3984     return false;
3985
3986   // If we don't have a symbolic displacement - we don't have any extra
3987   // restrictions.
3988   if (!hasSymbolicDisplacement)
3989     return true;
3990
3991   // FIXME: Some tweaks might be needed for medium code model.
3992   if (M != CodeModel::Small && M != CodeModel::Kernel)
3993     return false;
3994
3995   // For small code model we assume that latest object is 16MB before end of 31
3996   // bits boundary. We may also accept pretty large negative constants knowing
3997   // that all objects are in the positive half of address space.
3998   if (M == CodeModel::Small && Offset < 16*1024*1024)
3999     return true;
4000
4001   // For kernel code model we know that all object resist in the negative half
4002   // of 32bits address space. We may not accept negative offsets, since they may
4003   // be just off and we may accept pretty large positive ones.
4004   if (M == CodeModel::Kernel && Offset >= 0)
4005     return true;
4006
4007   return false;
4008 }
4009
4010 /// Determines whether the callee is required to pop its own arguments.
4011 /// Callee pop is necessary to support tail calls.
4012 bool X86::isCalleePop(CallingConv::ID CallingConv,
4013                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4014   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4015   // can guarantee TCO.
4016   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4017     return true;
4018
4019   switch (CallingConv) {
4020   default:
4021     return false;
4022   case CallingConv::X86_StdCall:
4023   case CallingConv::X86_FastCall:
4024   case CallingConv::X86_ThisCall:
4025   case CallingConv::X86_VectorCall:
4026     return !is64Bit;
4027   }
4028 }
4029
4030 /// \brief Return true if the condition is an unsigned comparison operation.
4031 static bool isX86CCUnsigned(unsigned X86CC) {
4032   switch (X86CC) {
4033   default: llvm_unreachable("Invalid integer condition!");
4034   case X86::COND_E:     return true;
4035   case X86::COND_G:     return false;
4036   case X86::COND_GE:    return false;
4037   case X86::COND_L:     return false;
4038   case X86::COND_LE:    return false;
4039   case X86::COND_NE:    return true;
4040   case X86::COND_B:     return true;
4041   case X86::COND_A:     return true;
4042   case X86::COND_BE:    return true;
4043   case X86::COND_AE:    return true;
4044   }
4045 }
4046
4047 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4048   switch (SetCCOpcode) {
4049   default: llvm_unreachable("Invalid integer condition!");
4050   case ISD::SETEQ:  return X86::COND_E;
4051   case ISD::SETGT:  return X86::COND_G;
4052   case ISD::SETGE:  return X86::COND_GE;
4053   case ISD::SETLT:  return X86::COND_L;
4054   case ISD::SETLE:  return X86::COND_LE;
4055   case ISD::SETNE:  return X86::COND_NE;
4056   case ISD::SETULT: return X86::COND_B;
4057   case ISD::SETUGT: return X86::COND_A;
4058   case ISD::SETULE: return X86::COND_BE;
4059   case ISD::SETUGE: return X86::COND_AE;
4060   }
4061 }
4062
4063 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4064 /// condition code, returning the condition code and the LHS/RHS of the
4065 /// comparison to make.
4066 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4067                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4068   if (!isFP) {
4069     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4070       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4071         // X > -1   -> X == 0, jump !sign.
4072         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4073         return X86::COND_NS;
4074       }
4075       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4076         // X < 0   -> X == 0, jump on sign.
4077         return X86::COND_S;
4078       }
4079       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4080         // X < 1   -> X <= 0
4081         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4082         return X86::COND_LE;
4083       }
4084     }
4085
4086     return TranslateIntegerX86CC(SetCCOpcode);
4087   }
4088
4089   // First determine if it is required or is profitable to flip the operands.
4090
4091   // If LHS is a foldable load, but RHS is not, flip the condition.
4092   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4093       !ISD::isNON_EXTLoad(RHS.getNode())) {
4094     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4095     std::swap(LHS, RHS);
4096   }
4097
4098   switch (SetCCOpcode) {
4099   default: break;
4100   case ISD::SETOLT:
4101   case ISD::SETOLE:
4102   case ISD::SETUGT:
4103   case ISD::SETUGE:
4104     std::swap(LHS, RHS);
4105     break;
4106   }
4107
4108   // On a floating point condition, the flags are set as follows:
4109   // ZF  PF  CF   op
4110   //  0 | 0 | 0 | X > Y
4111   //  0 | 0 | 1 | X < Y
4112   //  1 | 0 | 0 | X == Y
4113   //  1 | 1 | 1 | unordered
4114   switch (SetCCOpcode) {
4115   default: llvm_unreachable("Condcode should be pre-legalized away");
4116   case ISD::SETUEQ:
4117   case ISD::SETEQ:   return X86::COND_E;
4118   case ISD::SETOLT:              // flipped
4119   case ISD::SETOGT:
4120   case ISD::SETGT:   return X86::COND_A;
4121   case ISD::SETOLE:              // flipped
4122   case ISD::SETOGE:
4123   case ISD::SETGE:   return X86::COND_AE;
4124   case ISD::SETUGT:              // flipped
4125   case ISD::SETULT:
4126   case ISD::SETLT:   return X86::COND_B;
4127   case ISD::SETUGE:              // flipped
4128   case ISD::SETULE:
4129   case ISD::SETLE:   return X86::COND_BE;
4130   case ISD::SETONE:
4131   case ISD::SETNE:   return X86::COND_NE;
4132   case ISD::SETUO:   return X86::COND_P;
4133   case ISD::SETO:    return X86::COND_NP;
4134   case ISD::SETOEQ:
4135   case ISD::SETUNE:  return X86::COND_INVALID;
4136   }
4137 }
4138
4139 /// Is there a floating point cmov for the specific X86 condition code?
4140 /// Current x86 isa includes the following FP cmov instructions:
4141 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4142 static bool hasFPCMov(unsigned X86CC) {
4143   switch (X86CC) {
4144   default:
4145     return false;
4146   case X86::COND_B:
4147   case X86::COND_BE:
4148   case X86::COND_E:
4149   case X86::COND_P:
4150   case X86::COND_A:
4151   case X86::COND_AE:
4152   case X86::COND_NE:
4153   case X86::COND_NP:
4154     return true;
4155   }
4156 }
4157
4158 /// Returns true if the target can instruction select the
4159 /// specified FP immediate natively. If false, the legalizer will
4160 /// materialize the FP immediate as a load from a constant pool.
4161 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4162   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4163     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4164       return true;
4165   }
4166   return false;
4167 }
4168
4169 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4170                                               ISD::LoadExtType ExtTy,
4171                                               EVT NewVT) const {
4172   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4173   // relocation target a movq or addq instruction: don't let the load shrink.
4174   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4175   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4176     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4177       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4178   return true;
4179 }
4180
4181 /// \brief Returns true if it is beneficial to convert a load of a constant
4182 /// to just the constant itself.
4183 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4184                                                           Type *Ty) const {
4185   assert(Ty->isIntegerTy());
4186
4187   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4188   if (BitSize == 0 || BitSize > 64)
4189     return false;
4190   return true;
4191 }
4192
4193 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4194                                                 unsigned Index) const {
4195   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4196     return false;
4197
4198   return (Index == 0 || Index == ResVT.getVectorNumElements());
4199 }
4200
4201 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4202   // Speculate cttz only if we can directly use TZCNT.
4203   return Subtarget->hasBMI();
4204 }
4205
4206 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4207   // Speculate ctlz only if we can directly use LZCNT.
4208   return Subtarget->hasLZCNT();
4209 }
4210
4211 /// Return true if every element in Mask, beginning
4212 /// from position Pos and ending in Pos+Size is undef.
4213 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4214   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4215     if (0 <= Mask[i])
4216       return false;
4217   return true;
4218 }
4219
4220 /// Return true if Val is undef or if its value falls within the
4221 /// specified range (L, H].
4222 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4223   return (Val < 0) || (Val >= Low && Val < Hi);
4224 }
4225
4226 /// Val is either less than zero (undef) or equal to the specified value.
4227 static bool isUndefOrEqual(int Val, int CmpVal) {
4228   return (Val < 0 || Val == CmpVal);
4229 }
4230
4231 /// Return true if every element in Mask, beginning
4232 /// from position Pos and ending in Pos+Size, falls within the specified
4233 /// sequential range (Low, Low+Size]. or is undef.
4234 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4235                                        unsigned Pos, unsigned Size, int Low) {
4236   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4237     if (!isUndefOrEqual(Mask[i], Low))
4238       return false;
4239   return true;
4240 }
4241
4242 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4243 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4244 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4245   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4246   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4247     return false;
4248
4249   // The index should be aligned on a vecWidth-bit boundary.
4250   uint64_t Index =
4251     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4252
4253   MVT VT = N->getSimpleValueType(0);
4254   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4255   bool Result = (Index * ElSize) % vecWidth == 0;
4256
4257   return Result;
4258 }
4259
4260 /// Return true if the specified INSERT_SUBVECTOR
4261 /// operand specifies a subvector insert that is suitable for input to
4262 /// insertion of 128 or 256-bit subvectors
4263 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4264   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4265   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4266     return false;
4267   // The index should be aligned on a vecWidth-bit boundary.
4268   uint64_t Index =
4269     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4270
4271   MVT VT = N->getSimpleValueType(0);
4272   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4273   bool Result = (Index * ElSize) % vecWidth == 0;
4274
4275   return Result;
4276 }
4277
4278 bool X86::isVINSERT128Index(SDNode *N) {
4279   return isVINSERTIndex(N, 128);
4280 }
4281
4282 bool X86::isVINSERT256Index(SDNode *N) {
4283   return isVINSERTIndex(N, 256);
4284 }
4285
4286 bool X86::isVEXTRACT128Index(SDNode *N) {
4287   return isVEXTRACTIndex(N, 128);
4288 }
4289
4290 bool X86::isVEXTRACT256Index(SDNode *N) {
4291   return isVEXTRACTIndex(N, 256);
4292 }
4293
4294 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4295   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4296   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4297          "Illegal extract subvector for VEXTRACT");
4298
4299   uint64_t Index =
4300     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4301
4302   MVT VecVT = N->getOperand(0).getSimpleValueType();
4303   MVT ElVT = VecVT.getVectorElementType();
4304
4305   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4306   return Index / NumElemsPerChunk;
4307 }
4308
4309 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4310   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4311   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4312          "Illegal insert subvector for VINSERT");
4313
4314   uint64_t Index =
4315     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4316
4317   MVT VecVT = N->getSimpleValueType(0);
4318   MVT ElVT = VecVT.getVectorElementType();
4319
4320   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4321   return Index / NumElemsPerChunk;
4322 }
4323
4324 /// Return the appropriate immediate to extract the specified
4325 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4326 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4327   return getExtractVEXTRACTImmediate(N, 128);
4328 }
4329
4330 /// Return the appropriate immediate to extract the specified
4331 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4332 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4333   return getExtractVEXTRACTImmediate(N, 256);
4334 }
4335
4336 /// Return the appropriate immediate to insert at the specified
4337 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4338 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4339   return getInsertVINSERTImmediate(N, 128);
4340 }
4341
4342 /// Return the appropriate immediate to insert at the specified
4343 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4344 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4345   return getInsertVINSERTImmediate(N, 256);
4346 }
4347
4348 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4349 bool X86::isZeroNode(SDValue Elt) {
4350   return isNullConstant(Elt) || isNullFPConstant(Elt);
4351 }
4352
4353 // Build a vector of constants
4354 // Use an UNDEF node if MaskElt == -1.
4355 // Spilt 64-bit constants in the 32-bit mode.
4356 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4357                               SelectionDAG &DAG,
4358                               SDLoc dl, bool IsMask = false) {
4359
4360   SmallVector<SDValue, 32>  Ops;
4361   bool Split = false;
4362
4363   MVT ConstVecVT = VT;
4364   unsigned NumElts = VT.getVectorNumElements();
4365   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4366   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4367     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4368     Split = true;
4369   }
4370
4371   MVT EltVT = ConstVecVT.getVectorElementType();
4372   for (unsigned i = 0; i < NumElts; ++i) {
4373     bool IsUndef = Values[i] < 0 && IsMask;
4374     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4375       DAG.getConstant(Values[i], dl, EltVT);
4376     Ops.push_back(OpNode);
4377     if (Split)
4378       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4379                     DAG.getConstant(0, dl, EltVT));
4380   }
4381   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4382   if (Split)
4383     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4384   return ConstsNode;
4385 }
4386
4387 /// Returns a vector of specified type with all zero elements.
4388 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4389                              SelectionDAG &DAG, SDLoc dl) {
4390   assert(VT.isVector() && "Expected a vector type");
4391
4392   // Always build SSE zero vectors as <4 x i32> bitcasted
4393   // to their dest type. This ensures they get CSE'd.
4394   SDValue Vec;
4395   if (VT.is128BitVector()) {  // SSE
4396     if (Subtarget->hasSSE2()) {  // SSE2
4397       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4398       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4399     } else { // SSE1
4400       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4401       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4402     }
4403   } else if (VT.is256BitVector()) { // AVX
4404     if (Subtarget->hasInt256()) { // AVX2
4405       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4406       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4407       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4408     } else {
4409       // 256-bit logic and arithmetic instructions in AVX are all
4410       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4411       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4412       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4413       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4414     }
4415   } else if (VT.is512BitVector()) { // AVX-512
4416       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4417       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4418                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4419       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4420   } else if (VT.getVectorElementType() == MVT::i1) {
4421
4422     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4423             && "Unexpected vector type");
4424     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4425             && "Unexpected vector type");
4426     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4427     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4428     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4429   } else
4430     llvm_unreachable("Unexpected vector type");
4431
4432   return DAG.getBitcast(VT, Vec);
4433 }
4434
4435 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4436                                 SelectionDAG &DAG, SDLoc dl,
4437                                 unsigned vectorWidth) {
4438   assert((vectorWidth == 128 || vectorWidth == 256) &&
4439          "Unsupported vector width");
4440   EVT VT = Vec.getValueType();
4441   EVT ElVT = VT.getVectorElementType();
4442   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4443   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4444                                   VT.getVectorNumElements()/Factor);
4445
4446   // Extract from UNDEF is UNDEF.
4447   if (Vec.getOpcode() == ISD::UNDEF)
4448     return DAG.getUNDEF(ResultVT);
4449
4450   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4451   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4452   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4453
4454   // This is the index of the first element of the vectorWidth-bit chunk
4455   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4456   IdxVal &= ~(ElemsPerChunk - 1);
4457
4458   // If the input is a buildvector just emit a smaller one.
4459   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4460     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4461                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4462
4463   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4464   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4465 }
4466
4467 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4468 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4469 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4470 /// instructions or a simple subregister reference. Idx is an index in the
4471 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4472 /// lowering EXTRACT_VECTOR_ELT operations easier.
4473 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4474                                    SelectionDAG &DAG, SDLoc dl) {
4475   assert((Vec.getValueType().is256BitVector() ||
4476           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4477   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4478 }
4479
4480 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4481 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4482                                    SelectionDAG &DAG, SDLoc dl) {
4483   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4484   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4485 }
4486
4487 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4488                                unsigned IdxVal, SelectionDAG &DAG,
4489                                SDLoc dl, unsigned vectorWidth) {
4490   assert((vectorWidth == 128 || vectorWidth == 256) &&
4491          "Unsupported vector width");
4492   // Inserting UNDEF is Result
4493   if (Vec.getOpcode() == ISD::UNDEF)
4494     return Result;
4495   EVT VT = Vec.getValueType();
4496   EVT ElVT = VT.getVectorElementType();
4497   EVT ResultVT = Result.getValueType();
4498
4499   // Insert the relevant vectorWidth bits.
4500   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4501   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4502
4503   // This is the index of the first element of the vectorWidth-bit chunk
4504   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4505   IdxVal &= ~(ElemsPerChunk - 1);
4506
4507   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4508   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4509 }
4510
4511 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4512 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4513 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4514 /// simple superregister reference.  Idx is an index in the 128 bits
4515 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4516 /// lowering INSERT_VECTOR_ELT operations easier.
4517 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4518                                   SelectionDAG &DAG, SDLoc dl) {
4519   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4520
4521   // For insertion into the zero index (low half) of a 256-bit vector, it is
4522   // more efficient to generate a blend with immediate instead of an insert*128.
4523   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4524   // extend the subvector to the size of the result vector. Make sure that
4525   // we are not recursing on that node by checking for undef here.
4526   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4527       Result.getOpcode() != ISD::UNDEF) {
4528     EVT ResultVT = Result.getValueType();
4529     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4530     SDValue Undef = DAG.getUNDEF(ResultVT);
4531     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4532                                  Vec, ZeroIndex);
4533
4534     // The blend instruction, and therefore its mask, depend on the data type.
4535     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4536     if (ScalarType.isFloatingPoint()) {
4537       // Choose either vblendps (float) or vblendpd (double).
4538       unsigned ScalarSize = ScalarType.getSizeInBits();
4539       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4540       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4541       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4542       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4543     }
4544
4545     const X86Subtarget &Subtarget =
4546     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4547
4548     // AVX2 is needed for 256-bit integer blend support.
4549     // Integers must be cast to 32-bit because there is only vpblendd;
4550     // vpblendw can't be used for this because it has a handicapped mask.
4551
4552     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4553     // is still more efficient than using the wrong domain vinsertf128 that
4554     // will be created by InsertSubVector().
4555     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4556
4557     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4558     Vec256 = DAG.getBitcast(CastVT, Vec256);
4559     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4560     return DAG.getBitcast(ResultVT, Vec256);
4561   }
4562
4563   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4564 }
4565
4566 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4567                                   SelectionDAG &DAG, SDLoc dl) {
4568   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4569   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4570 }
4571
4572 /// Insert i1-subvector to i1-vector.
4573 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4574
4575   SDLoc dl(Op);
4576   SDValue Vec = Op.getOperand(0);
4577   SDValue SubVec = Op.getOperand(1);
4578   SDValue Idx = Op.getOperand(2);
4579
4580   if (!isa<ConstantSDNode>(Idx))
4581     return SDValue();
4582
4583   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4584   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4585     return Op;
4586
4587   MVT OpVT = Op.getSimpleValueType();
4588   MVT SubVecVT = SubVec.getSimpleValueType();
4589   unsigned NumElems = OpVT.getVectorNumElements();
4590   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4591
4592   assert(IdxVal + SubVecNumElems <= NumElems &&
4593          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4594          "Unexpected index value in INSERT_SUBVECTOR");
4595
4596   // There are 3 possible cases:
4597   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4598   // 2. Subvector should be inserted in the upper part
4599   //    (IdxVal + SubVecNumElems == NumElems)
4600   // 3. Subvector should be inserted in the middle (for example v2i1
4601   //    to v16i1, index 2)
4602
4603   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4604   SDValue Undef = DAG.getUNDEF(OpVT);
4605   SDValue WideSubVec =
4606     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4607   if (Vec.isUndef())
4608     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4609       DAG.getConstant(IdxVal, dl, MVT::i8));
4610
4611   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4612     unsigned ShiftLeft = NumElems - SubVecNumElems;
4613     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4614     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4615       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4616     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4617       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4618   }
4619
4620   if (IdxVal == 0) {
4621     // Zero lower bits of the Vec
4622     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4623     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4624     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4625     // Merge them together
4626     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4627   }
4628
4629   // Simple case when we put subvector in the upper part
4630   if (IdxVal + SubVecNumElems == NumElems) {
4631     // Zero upper bits of the Vec
4632     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4633                         DAG.getConstant(IdxVal, dl, MVT::i8));
4634     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4635     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4636     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4637     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4638   }
4639   // Subvector should be inserted in the middle - use shuffle
4640   SmallVector<int, 64> Mask;
4641   for (unsigned i = 0; i < NumElems; ++i)
4642     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4643                     i : i + NumElems);
4644   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4645 }
4646
4647 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4648 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4649 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4650 /// large BUILD_VECTORS.
4651 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4652                                    unsigned NumElems, SelectionDAG &DAG,
4653                                    SDLoc dl) {
4654   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4655   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4656 }
4657
4658 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4659                                    unsigned NumElems, SelectionDAG &DAG,
4660                                    SDLoc dl) {
4661   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4662   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4663 }
4664
4665 /// Returns a vector of specified type with all bits set.
4666 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4667 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4668 /// Then bitcast to their original type, ensuring they get CSE'd.
4669 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4670                              SelectionDAG &DAG, SDLoc dl) {
4671   assert(VT.isVector() && "Expected a vector type");
4672
4673   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4674   SDValue Vec;
4675   if (VT.is512BitVector()) {
4676     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4677                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4678     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4679   } else if (VT.is256BitVector()) {
4680     if (Subtarget->hasInt256()) { // AVX2
4681       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4682       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4683     } else { // AVX
4684       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4685       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4686     }
4687   } else if (VT.is128BitVector()) {
4688     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4689   } else
4690     llvm_unreachable("Unexpected vector type");
4691
4692   return DAG.getBitcast(VT, Vec);
4693 }
4694
4695 /// Returns a vector_shuffle node for an unpackl operation.
4696 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4697                           SDValue V2) {
4698   unsigned NumElems = VT.getVectorNumElements();
4699   SmallVector<int, 8> Mask;
4700   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4701     Mask.push_back(i);
4702     Mask.push_back(i + NumElems);
4703   }
4704   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4705 }
4706
4707 /// Returns a vector_shuffle node for an unpackh operation.
4708 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4709                           SDValue V2) {
4710   unsigned NumElems = VT.getVectorNumElements();
4711   SmallVector<int, 8> Mask;
4712   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4713     Mask.push_back(i + Half);
4714     Mask.push_back(i + NumElems + Half);
4715   }
4716   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4717 }
4718
4719 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4720 /// This produces a shuffle where the low element of V2 is swizzled into the
4721 /// zero/undef vector, landing at element Idx.
4722 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4723 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4724                                            bool IsZero,
4725                                            const X86Subtarget *Subtarget,
4726                                            SelectionDAG &DAG) {
4727   MVT VT = V2.getSimpleValueType();
4728   SDValue V1 = IsZero
4729     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4730   unsigned NumElems = VT.getVectorNumElements();
4731   SmallVector<int, 16> MaskVec;
4732   for (unsigned i = 0; i != NumElems; ++i)
4733     // If this is the insertion idx, put the low elt of V2 here.
4734     MaskVec.push_back(i == Idx ? NumElems : i);
4735   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4736 }
4737
4738 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4739 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4740 /// uses one source. Note that this will set IsUnary for shuffles which use a
4741 /// single input multiple times, and in those cases it will
4742 /// adjust the mask to only have indices within that single input.
4743 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4744 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4745                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4746   unsigned NumElems = VT.getVectorNumElements();
4747   SDValue ImmN;
4748
4749   IsUnary = false;
4750   bool IsFakeUnary = false;
4751   switch(N->getOpcode()) {
4752   case X86ISD::BLENDI:
4753     ImmN = N->getOperand(N->getNumOperands()-1);
4754     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4755     break;
4756   case X86ISD::SHUFP:
4757     ImmN = N->getOperand(N->getNumOperands()-1);
4758     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4759     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4760     break;
4761   case X86ISD::UNPCKH:
4762     DecodeUNPCKHMask(VT, Mask);
4763     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4764     break;
4765   case X86ISD::UNPCKL:
4766     DecodeUNPCKLMask(VT, Mask);
4767     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4768     break;
4769   case X86ISD::MOVHLPS:
4770     DecodeMOVHLPSMask(NumElems, Mask);
4771     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4772     break;
4773   case X86ISD::MOVLHPS:
4774     DecodeMOVLHPSMask(NumElems, Mask);
4775     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4776     break;
4777   case X86ISD::PALIGNR:
4778     ImmN = N->getOperand(N->getNumOperands()-1);
4779     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4780     break;
4781   case X86ISD::PSHUFD:
4782   case X86ISD::VPERMILPI:
4783     ImmN = N->getOperand(N->getNumOperands()-1);
4784     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4785     IsUnary = true;
4786     break;
4787   case X86ISD::PSHUFHW:
4788     ImmN = N->getOperand(N->getNumOperands()-1);
4789     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4790     IsUnary = true;
4791     break;
4792   case X86ISD::PSHUFLW:
4793     ImmN = N->getOperand(N->getNumOperands()-1);
4794     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4795     IsUnary = true;
4796     break;
4797   case X86ISD::PSHUFB: {
4798     IsUnary = true;
4799     SDValue MaskNode = N->getOperand(1);
4800     while (MaskNode->getOpcode() == ISD::BITCAST)
4801       MaskNode = MaskNode->getOperand(0);
4802
4803     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4804       // If we have a build-vector, then things are easy.
4805       MVT VT = MaskNode.getSimpleValueType();
4806       assert(VT.isVector() &&
4807              "Can't produce a non-vector with a build_vector!");
4808       if (!VT.isInteger())
4809         return false;
4810
4811       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4812
4813       SmallVector<uint64_t, 32> RawMask;
4814       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4815         SDValue Op = MaskNode->getOperand(i);
4816         if (Op->getOpcode() == ISD::UNDEF) {
4817           RawMask.push_back((uint64_t)SM_SentinelUndef);
4818           continue;
4819         }
4820         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4821         if (!CN)
4822           return false;
4823         APInt MaskElement = CN->getAPIntValue();
4824
4825         // We now have to decode the element which could be any integer size and
4826         // extract each byte of it.
4827         for (int j = 0; j < NumBytesPerElement; ++j) {
4828           // Note that this is x86 and so always little endian: the low byte is
4829           // the first byte of the mask.
4830           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4831           MaskElement = MaskElement.lshr(8);
4832         }
4833       }
4834       DecodePSHUFBMask(RawMask, Mask);
4835       break;
4836     }
4837
4838     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4839     if (!MaskLoad)
4840       return false;
4841
4842     SDValue Ptr = MaskLoad->getBasePtr();
4843     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4844         Ptr->getOpcode() == X86ISD::WrapperRIP)
4845       Ptr = Ptr->getOperand(0);
4846
4847     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4848     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4849       return false;
4850
4851     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4852       DecodePSHUFBMask(C, Mask);
4853       if (Mask.empty())
4854         return false;
4855       break;
4856     }
4857
4858     return false;
4859   }
4860   case X86ISD::VPERMI:
4861     ImmN = N->getOperand(N->getNumOperands()-1);
4862     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4863     IsUnary = true;
4864     break;
4865   case X86ISD::MOVSS:
4866   case X86ISD::MOVSD:
4867     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4868     break;
4869   case X86ISD::VPERM2X128:
4870     ImmN = N->getOperand(N->getNumOperands()-1);
4871     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4872     if (Mask.empty()) return false;
4873     // Mask only contains negative index if an element is zero.
4874     if (std::any_of(Mask.begin(), Mask.end(),
4875                     [](int M){ return M == SM_SentinelZero; }))
4876       return false;
4877     break;
4878   case X86ISD::MOVSLDUP:
4879     DecodeMOVSLDUPMask(VT, Mask);
4880     IsUnary = true;
4881     break;
4882   case X86ISD::MOVSHDUP:
4883     DecodeMOVSHDUPMask(VT, Mask);
4884     IsUnary = true;
4885     break;
4886   case X86ISD::MOVDDUP:
4887     DecodeMOVDDUPMask(VT, Mask);
4888     IsUnary = true;
4889     break;
4890   case X86ISD::MOVLHPD:
4891   case X86ISD::MOVLPD:
4892   case X86ISD::MOVLPS:
4893     // Not yet implemented
4894     return false;
4895   case X86ISD::VPERMV: {
4896     IsUnary = true;
4897     SDValue MaskNode = N->getOperand(0);
4898     while (MaskNode->getOpcode() == ISD::BITCAST)
4899       MaskNode = MaskNode->getOperand(0);
4900
4901     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4902     SmallVector<uint64_t, 32> RawMask;
4903     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4904       // If we have a build-vector, then things are easy.
4905       assert(MaskNode.getSimpleValueType().isInteger() &&
4906              MaskNode.getSimpleValueType().getVectorNumElements() ==
4907              VT.getVectorNumElements());
4908
4909       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4910         SDValue Op = MaskNode->getOperand(i);
4911         if (Op->getOpcode() == ISD::UNDEF)
4912           RawMask.push_back((uint64_t)SM_SentinelUndef);
4913         else if (isa<ConstantSDNode>(Op)) {
4914           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4915           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4916         } else
4917           return false;
4918       }
4919       DecodeVPERMVMask(RawMask, Mask);
4920       break;
4921     }
4922     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4923       unsigned NumEltsInMask = MaskNode->getNumOperands();
4924       MaskNode = MaskNode->getOperand(0);
4925       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4926       if (CN) {
4927         APInt MaskEltValue = CN->getAPIntValue();
4928         for (unsigned i = 0; i < NumEltsInMask; ++i)
4929           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4930         DecodeVPERMVMask(RawMask, Mask);
4931         break;
4932       }
4933       // It may be a scalar load
4934     }
4935
4936     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4937     if (!MaskLoad)
4938       return false;
4939
4940     SDValue Ptr = MaskLoad->getBasePtr();
4941     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4942         Ptr->getOpcode() == X86ISD::WrapperRIP)
4943       Ptr = Ptr->getOperand(0);
4944
4945     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4946     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4947       return false;
4948
4949     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4950     if (C) {
4951       DecodeVPERMVMask(C, VT, Mask);
4952       if (Mask.empty())
4953         return false;
4954       break;
4955     }
4956     return false;
4957   }
4958   case X86ISD::VPERMV3: {
4959     IsUnary = false;
4960     SDValue MaskNode = N->getOperand(1);
4961     while (MaskNode->getOpcode() == ISD::BITCAST)
4962       MaskNode = MaskNode->getOperand(1);
4963
4964     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4965       // If we have a build-vector, then things are easy.
4966       assert(MaskNode.getSimpleValueType().isInteger() &&
4967              MaskNode.getSimpleValueType().getVectorNumElements() ==
4968              VT.getVectorNumElements());
4969
4970       SmallVector<uint64_t, 32> RawMask;
4971       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4972
4973       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4974         SDValue Op = MaskNode->getOperand(i);
4975         if (Op->getOpcode() == ISD::UNDEF)
4976           RawMask.push_back((uint64_t)SM_SentinelUndef);
4977         else {
4978           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4979           if (!CN)
4980             return false;
4981           APInt MaskElement = CN->getAPIntValue();
4982           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4983         }
4984       }
4985       DecodeVPERMV3Mask(RawMask, Mask);
4986       break;
4987     }
4988
4989     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4990     if (!MaskLoad)
4991       return false;
4992
4993     SDValue Ptr = MaskLoad->getBasePtr();
4994     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4995         Ptr->getOpcode() == X86ISD::WrapperRIP)
4996       Ptr = Ptr->getOperand(0);
4997
4998     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4999     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5000       return false;
5001
5002     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
5003     if (C) {
5004       DecodeVPERMV3Mask(C, VT, Mask);
5005       if (Mask.empty())
5006         return false;
5007       break;
5008     }
5009     return false;
5010   }
5011   default: llvm_unreachable("unknown target shuffle node");
5012   }
5013
5014   // If we have a fake unary shuffle, the shuffle mask is spread across two
5015   // inputs that are actually the same node. Re-map the mask to always point
5016   // into the first input.
5017   if (IsFakeUnary)
5018     for (int &M : Mask)
5019       if (M >= (int)Mask.size())
5020         M -= Mask.size();
5021
5022   return true;
5023 }
5024
5025 /// Returns the scalar element that will make up the ith
5026 /// element of the result of the vector shuffle.
5027 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5028                                    unsigned Depth) {
5029   if (Depth == 6)
5030     return SDValue();  // Limit search depth.
5031
5032   SDValue V = SDValue(N, 0);
5033   EVT VT = V.getValueType();
5034   unsigned Opcode = V.getOpcode();
5035
5036   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5037   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5038     int Elt = SV->getMaskElt(Index);
5039
5040     if (Elt < 0)
5041       return DAG.getUNDEF(VT.getVectorElementType());
5042
5043     unsigned NumElems = VT.getVectorNumElements();
5044     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5045                                          : SV->getOperand(1);
5046     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5047   }
5048
5049   // Recurse into target specific vector shuffles to find scalars.
5050   if (isTargetShuffle(Opcode)) {
5051     MVT ShufVT = V.getSimpleValueType();
5052     unsigned NumElems = ShufVT.getVectorNumElements();
5053     SmallVector<int, 16> ShuffleMask;
5054     bool IsUnary;
5055
5056     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5057       return SDValue();
5058
5059     int Elt = ShuffleMask[Index];
5060     if (Elt < 0)
5061       return DAG.getUNDEF(ShufVT.getVectorElementType());
5062
5063     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5064                                          : N->getOperand(1);
5065     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5066                                Depth+1);
5067   }
5068
5069   // Actual nodes that may contain scalar elements
5070   if (Opcode == ISD::BITCAST) {
5071     V = V.getOperand(0);
5072     EVT SrcVT = V.getValueType();
5073     unsigned NumElems = VT.getVectorNumElements();
5074
5075     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5076       return SDValue();
5077   }
5078
5079   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5080     return (Index == 0) ? V.getOperand(0)
5081                         : DAG.getUNDEF(VT.getVectorElementType());
5082
5083   if (V.getOpcode() == ISD::BUILD_VECTOR)
5084     return V.getOperand(Index);
5085
5086   return SDValue();
5087 }
5088
5089 /// Custom lower build_vector of v16i8.
5090 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5091                                        unsigned NumNonZero, unsigned NumZero,
5092                                        SelectionDAG &DAG,
5093                                        const X86Subtarget* Subtarget,
5094                                        const TargetLowering &TLI) {
5095   if (NumNonZero > 8)
5096     return SDValue();
5097
5098   SDLoc dl(Op);
5099   SDValue V;
5100   bool First = true;
5101
5102   // SSE4.1 - use PINSRB to insert each byte directly.
5103   if (Subtarget->hasSSE41()) {
5104     for (unsigned i = 0; i < 16; ++i) {
5105       bool isNonZero = (NonZeros & (1 << i)) != 0;
5106       if (isNonZero) {
5107         if (First) {
5108           if (NumZero)
5109             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5110           else
5111             V = DAG.getUNDEF(MVT::v16i8);
5112           First = false;
5113         }
5114         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5115                         MVT::v16i8, V, Op.getOperand(i),
5116                         DAG.getIntPtrConstant(i, dl));
5117       }
5118     }
5119
5120     return V;
5121   }
5122
5123   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5124   for (unsigned i = 0; i < 16; ++i) {
5125     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5126     if (ThisIsNonZero && First) {
5127       if (NumZero)
5128         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5129       else
5130         V = DAG.getUNDEF(MVT::v8i16);
5131       First = false;
5132     }
5133
5134     if ((i & 1) != 0) {
5135       SDValue ThisElt, LastElt;
5136       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5137       if (LastIsNonZero) {
5138         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5139                               MVT::i16, Op.getOperand(i-1));
5140       }
5141       if (ThisIsNonZero) {
5142         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5143         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5144                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5145         if (LastIsNonZero)
5146           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5147       } else
5148         ThisElt = LastElt;
5149
5150       if (ThisElt.getNode())
5151         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5152                         DAG.getIntPtrConstant(i/2, dl));
5153     }
5154   }
5155
5156   return DAG.getBitcast(MVT::v16i8, V);
5157 }
5158
5159 /// Custom lower build_vector of v8i16.
5160 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5161                                      unsigned NumNonZero, unsigned NumZero,
5162                                      SelectionDAG &DAG,
5163                                      const X86Subtarget* Subtarget,
5164                                      const TargetLowering &TLI) {
5165   if (NumNonZero > 4)
5166     return SDValue();
5167
5168   SDLoc dl(Op);
5169   SDValue V;
5170   bool First = true;
5171   for (unsigned i = 0; i < 8; ++i) {
5172     bool isNonZero = (NonZeros & (1 << i)) != 0;
5173     if (isNonZero) {
5174       if (First) {
5175         if (NumZero)
5176           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5177         else
5178           V = DAG.getUNDEF(MVT::v8i16);
5179         First = false;
5180       }
5181       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5182                       MVT::v8i16, V, Op.getOperand(i),
5183                       DAG.getIntPtrConstant(i, dl));
5184     }
5185   }
5186
5187   return V;
5188 }
5189
5190 /// Custom lower build_vector of v4i32 or v4f32.
5191 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5192                                      const X86Subtarget *Subtarget,
5193                                      const TargetLowering &TLI) {
5194   // Find all zeroable elements.
5195   std::bitset<4> Zeroable;
5196   for (int i=0; i < 4; ++i) {
5197     SDValue Elt = Op->getOperand(i);
5198     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5199   }
5200   assert(Zeroable.size() - Zeroable.count() > 1 &&
5201          "We expect at least two non-zero elements!");
5202
5203   // We only know how to deal with build_vector nodes where elements are either
5204   // zeroable or extract_vector_elt with constant index.
5205   SDValue FirstNonZero;
5206   unsigned FirstNonZeroIdx;
5207   for (unsigned i=0; i < 4; ++i) {
5208     if (Zeroable[i])
5209       continue;
5210     SDValue Elt = Op->getOperand(i);
5211     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5212         !isa<ConstantSDNode>(Elt.getOperand(1)))
5213       return SDValue();
5214     // Make sure that this node is extracting from a 128-bit vector.
5215     MVT VT = Elt.getOperand(0).getSimpleValueType();
5216     if (!VT.is128BitVector())
5217       return SDValue();
5218     if (!FirstNonZero.getNode()) {
5219       FirstNonZero = Elt;
5220       FirstNonZeroIdx = i;
5221     }
5222   }
5223
5224   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5225   SDValue V1 = FirstNonZero.getOperand(0);
5226   MVT VT = V1.getSimpleValueType();
5227
5228   // See if this build_vector can be lowered as a blend with zero.
5229   SDValue Elt;
5230   unsigned EltMaskIdx, EltIdx;
5231   int Mask[4];
5232   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5233     if (Zeroable[EltIdx]) {
5234       // The zero vector will be on the right hand side.
5235       Mask[EltIdx] = EltIdx+4;
5236       continue;
5237     }
5238
5239     Elt = Op->getOperand(EltIdx);
5240     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5241     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5242     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5243       break;
5244     Mask[EltIdx] = EltIdx;
5245   }
5246
5247   if (EltIdx == 4) {
5248     // Let the shuffle legalizer deal with blend operations.
5249     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5250     if (V1.getSimpleValueType() != VT)
5251       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5252     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5253   }
5254
5255   // See if we can lower this build_vector to a INSERTPS.
5256   if (!Subtarget->hasSSE41())
5257     return SDValue();
5258
5259   SDValue V2 = Elt.getOperand(0);
5260   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5261     V1 = SDValue();
5262
5263   bool CanFold = true;
5264   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5265     if (Zeroable[i])
5266       continue;
5267
5268     SDValue Current = Op->getOperand(i);
5269     SDValue SrcVector = Current->getOperand(0);
5270     if (!V1.getNode())
5271       V1 = SrcVector;
5272     CanFold = SrcVector == V1 &&
5273       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5274   }
5275
5276   if (!CanFold)
5277     return SDValue();
5278
5279   assert(V1.getNode() && "Expected at least two non-zero elements!");
5280   if (V1.getSimpleValueType() != MVT::v4f32)
5281     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5282   if (V2.getSimpleValueType() != MVT::v4f32)
5283     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5284
5285   // Ok, we can emit an INSERTPS instruction.
5286   unsigned ZMask = Zeroable.to_ulong();
5287
5288   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5289   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5290   SDLoc DL(Op);
5291   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5292                                DAG.getIntPtrConstant(InsertPSMask, DL));
5293   return DAG.getBitcast(VT, Result);
5294 }
5295
5296 /// Return a vector logical shift node.
5297 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5298                          unsigned NumBits, SelectionDAG &DAG,
5299                          const TargetLowering &TLI, SDLoc dl) {
5300   assert(VT.is128BitVector() && "Unknown type for VShift");
5301   MVT ShVT = MVT::v2i64;
5302   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5303   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5304   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5305   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5306   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5307   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5308 }
5309
5310 static SDValue
5311 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5312
5313   // Check if the scalar load can be widened into a vector load. And if
5314   // the address is "base + cst" see if the cst can be "absorbed" into
5315   // the shuffle mask.
5316   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5317     SDValue Ptr = LD->getBasePtr();
5318     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5319       return SDValue();
5320     EVT PVT = LD->getValueType(0);
5321     if (PVT != MVT::i32 && PVT != MVT::f32)
5322       return SDValue();
5323
5324     int FI = -1;
5325     int64_t Offset = 0;
5326     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5327       FI = FINode->getIndex();
5328       Offset = 0;
5329     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5330                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5331       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5332       Offset = Ptr.getConstantOperandVal(1);
5333       Ptr = Ptr.getOperand(0);
5334     } else {
5335       return SDValue();
5336     }
5337
5338     // FIXME: 256-bit vector instructions don't require a strict alignment,
5339     // improve this code to support it better.
5340     unsigned RequiredAlign = VT.getSizeInBits()/8;
5341     SDValue Chain = LD->getChain();
5342     // Make sure the stack object alignment is at least 16 or 32.
5343     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5344     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5345       if (MFI->isFixedObjectIndex(FI)) {
5346         // Can't change the alignment. FIXME: It's possible to compute
5347         // the exact stack offset and reference FI + adjust offset instead.
5348         // If someone *really* cares about this. That's the way to implement it.
5349         return SDValue();
5350       } else {
5351         MFI->setObjectAlignment(FI, RequiredAlign);
5352       }
5353     }
5354
5355     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5356     // Ptr + (Offset & ~15).
5357     if (Offset < 0)
5358       return SDValue();
5359     if ((Offset % RequiredAlign) & 3)
5360       return SDValue();
5361     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5362     if (StartOffset) {
5363       SDLoc DL(Ptr);
5364       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5365                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5366     }
5367
5368     int EltNo = (Offset - StartOffset) >> 2;
5369     unsigned NumElems = VT.getVectorNumElements();
5370
5371     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5372     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5373                              LD->getPointerInfo().getWithOffset(StartOffset),
5374                              false, false, false, 0);
5375
5376     SmallVector<int, 8> Mask(NumElems, EltNo);
5377
5378     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5379   }
5380
5381   return SDValue();
5382 }
5383
5384 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5385 /// elements can be replaced by a single large load which has the same value as
5386 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5387 ///
5388 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5389 ///
5390 /// FIXME: we'd also like to handle the case where the last elements are zero
5391 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5392 /// There's even a handy isZeroNode for that purpose.
5393 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5394                                         SDLoc &DL, SelectionDAG &DAG,
5395                                         bool isAfterLegalize) {
5396   unsigned NumElems = Elts.size();
5397
5398   LoadSDNode *LDBase = nullptr;
5399   unsigned LastLoadedElt = -1U;
5400
5401   // For each element in the initializer, see if we've found a load or an undef.
5402   // If we don't find an initial load element, or later load elements are
5403   // non-consecutive, bail out.
5404   for (unsigned i = 0; i < NumElems; ++i) {
5405     SDValue Elt = Elts[i];
5406     // Look through a bitcast.
5407     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5408       Elt = Elt.getOperand(0);
5409     if (!Elt.getNode() ||
5410         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5411       return SDValue();
5412     if (!LDBase) {
5413       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5414         return SDValue();
5415       LDBase = cast<LoadSDNode>(Elt.getNode());
5416       LastLoadedElt = i;
5417       continue;
5418     }
5419     if (Elt.getOpcode() == ISD::UNDEF)
5420       continue;
5421
5422     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5423     EVT LdVT = Elt.getValueType();
5424     // Each loaded element must be the correct fractional portion of the
5425     // requested vector load.
5426     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5427       return SDValue();
5428     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5429       return SDValue();
5430     LastLoadedElt = i;
5431   }
5432
5433   // If we have found an entire vector of loads and undefs, then return a large
5434   // load of the entire vector width starting at the base pointer.  If we found
5435   // consecutive loads for the low half, generate a vzext_load node.
5436   if (LastLoadedElt == NumElems - 1) {
5437     assert(LDBase && "Did not find base load for merging consecutive loads");
5438     EVT EltVT = LDBase->getValueType(0);
5439     // Ensure that the input vector size for the merged loads matches the
5440     // cumulative size of the input elements.
5441     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5442       return SDValue();
5443
5444     if (isAfterLegalize &&
5445         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5446       return SDValue();
5447
5448     SDValue NewLd = SDValue();
5449
5450     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5451                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5452                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5453                         LDBase->getAlignment());
5454
5455     if (LDBase->hasAnyUseOfValue(1)) {
5456       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5457                                      SDValue(LDBase, 1),
5458                                      SDValue(NewLd.getNode(), 1));
5459       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5460       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5461                              SDValue(NewLd.getNode(), 1));
5462     }
5463
5464     return NewLd;
5465   }
5466
5467   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5468   //of a v4i32 / v4f32. It's probably worth generalizing.
5469   EVT EltVT = VT.getVectorElementType();
5470   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5471       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5472     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5473     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5474     SDValue ResNode =
5475         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5476                                 LDBase->getPointerInfo(),
5477                                 LDBase->getAlignment(),
5478                                 false/*isVolatile*/, true/*ReadMem*/,
5479                                 false/*WriteMem*/);
5480
5481     // Make sure the newly-created LOAD is in the same position as LDBase in
5482     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5483     // update uses of LDBase's output chain to use the TokenFactor.
5484     if (LDBase->hasAnyUseOfValue(1)) {
5485       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5486                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5487       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5488       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5489                              SDValue(ResNode.getNode(), 1));
5490     }
5491
5492     return DAG.getBitcast(VT, ResNode);
5493   }
5494   return SDValue();
5495 }
5496
5497 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5498 /// to generate a splat value for the following cases:
5499 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5500 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5501 /// a scalar load, or a constant.
5502 /// The VBROADCAST node is returned when a pattern is found,
5503 /// or SDValue() otherwise.
5504 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5505                                     SelectionDAG &DAG) {
5506   // VBROADCAST requires AVX.
5507   // TODO: Splats could be generated for non-AVX CPUs using SSE
5508   // instructions, but there's less potential gain for only 128-bit vectors.
5509   if (!Subtarget->hasAVX())
5510     return SDValue();
5511
5512   MVT VT = Op.getSimpleValueType();
5513   SDLoc dl(Op);
5514
5515   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5516          "Unsupported vector type for broadcast.");
5517
5518   SDValue Ld;
5519   bool ConstSplatVal;
5520
5521   switch (Op.getOpcode()) {
5522     default:
5523       // Unknown pattern found.
5524       return SDValue();
5525
5526     case ISD::BUILD_VECTOR: {
5527       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5528       BitVector UndefElements;
5529       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5530
5531       // We need a splat of a single value to use broadcast, and it doesn't
5532       // make any sense if the value is only in one element of the vector.
5533       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5534         return SDValue();
5535
5536       Ld = Splat;
5537       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5538                        Ld.getOpcode() == ISD::ConstantFP);
5539
5540       // Make sure that all of the users of a non-constant load are from the
5541       // BUILD_VECTOR node.
5542       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5543         return SDValue();
5544       break;
5545     }
5546
5547     case ISD::VECTOR_SHUFFLE: {
5548       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5549
5550       // Shuffles must have a splat mask where the first element is
5551       // broadcasted.
5552       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5553         return SDValue();
5554
5555       SDValue Sc = Op.getOperand(0);
5556       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5557           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5558
5559         if (!Subtarget->hasInt256())
5560           return SDValue();
5561
5562         // Use the register form of the broadcast instruction available on AVX2.
5563         if (VT.getSizeInBits() >= 256)
5564           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5565         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5566       }
5567
5568       Ld = Sc.getOperand(0);
5569       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5570                        Ld.getOpcode() == ISD::ConstantFP);
5571
5572       // The scalar_to_vector node and the suspected
5573       // load node must have exactly one user.
5574       // Constants may have multiple users.
5575
5576       // AVX-512 has register version of the broadcast
5577       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5578         Ld.getValueType().getSizeInBits() >= 32;
5579       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5580           !hasRegVer))
5581         return SDValue();
5582       break;
5583     }
5584   }
5585
5586   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5587   bool IsGE256 = (VT.getSizeInBits() >= 256);
5588
5589   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5590   // instruction to save 8 or more bytes of constant pool data.
5591   // TODO: If multiple splats are generated to load the same constant,
5592   // it may be detrimental to overall size. There needs to be a way to detect
5593   // that condition to know if this is truly a size win.
5594   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5595
5596   // Handle broadcasting a single constant scalar from the constant pool
5597   // into a vector.
5598   // On Sandybridge (no AVX2), it is still better to load a constant vector
5599   // from the constant pool and not to broadcast it from a scalar.
5600   // But override that restriction when optimizing for size.
5601   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5602   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5603     EVT CVT = Ld.getValueType();
5604     assert(!CVT.isVector() && "Must not broadcast a vector type");
5605
5606     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5607     // For size optimization, also splat v2f64 and v2i64, and for size opt
5608     // with AVX2, also splat i8 and i16.
5609     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5610     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5611         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5612       const Constant *C = nullptr;
5613       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5614         C = CI->getConstantIntValue();
5615       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5616         C = CF->getConstantFPValue();
5617
5618       assert(C && "Invalid constant type");
5619
5620       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5621       SDValue CP =
5622           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5623       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5624       Ld = DAG.getLoad(
5625           CVT, dl, DAG.getEntryNode(), CP,
5626           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5627           false, false, Alignment);
5628
5629       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5630     }
5631   }
5632
5633   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5634
5635   // Handle AVX2 in-register broadcasts.
5636   if (!IsLoad && Subtarget->hasInt256() &&
5637       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5638     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5639
5640   // The scalar source must be a normal load.
5641   if (!IsLoad)
5642     return SDValue();
5643
5644   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5645       (Subtarget->hasVLX() && ScalarSize == 64))
5646     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5647
5648   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5649   // double since there is no vbroadcastsd xmm
5650   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5651     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5652       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5653   }
5654
5655   // Unsupported broadcast.
5656   return SDValue();
5657 }
5658
5659 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5660 /// underlying vector and index.
5661 ///
5662 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5663 /// index.
5664 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5665                                          SDValue ExtIdx) {
5666   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5667   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5668     return Idx;
5669
5670   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5671   // lowered this:
5672   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5673   // to:
5674   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5675   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5676   //                           undef)
5677   //                       Constant<0>)
5678   // In this case the vector is the extract_subvector expression and the index
5679   // is 2, as specified by the shuffle.
5680   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5681   SDValue ShuffleVec = SVOp->getOperand(0);
5682   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5683   assert(ShuffleVecVT.getVectorElementType() ==
5684          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5685
5686   int ShuffleIdx = SVOp->getMaskElt(Idx);
5687   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5688     ExtractedFromVec = ShuffleVec;
5689     return ShuffleIdx;
5690   }
5691   return Idx;
5692 }
5693
5694 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5695   MVT VT = Op.getSimpleValueType();
5696
5697   // Skip if insert_vec_elt is not supported.
5698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5699   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5700     return SDValue();
5701
5702   SDLoc DL(Op);
5703   unsigned NumElems = Op.getNumOperands();
5704
5705   SDValue VecIn1;
5706   SDValue VecIn2;
5707   SmallVector<unsigned, 4> InsertIndices;
5708   SmallVector<int, 8> Mask(NumElems, -1);
5709
5710   for (unsigned i = 0; i != NumElems; ++i) {
5711     unsigned Opc = Op.getOperand(i).getOpcode();
5712
5713     if (Opc == ISD::UNDEF)
5714       continue;
5715
5716     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5717       // Quit if more than 1 elements need inserting.
5718       if (InsertIndices.size() > 1)
5719         return SDValue();
5720
5721       InsertIndices.push_back(i);
5722       continue;
5723     }
5724
5725     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5726     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5727     // Quit if non-constant index.
5728     if (!isa<ConstantSDNode>(ExtIdx))
5729       return SDValue();
5730     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5731
5732     // Quit if extracted from vector of different type.
5733     if (ExtractedFromVec.getValueType() != VT)
5734       return SDValue();
5735
5736     if (!VecIn1.getNode())
5737       VecIn1 = ExtractedFromVec;
5738     else if (VecIn1 != ExtractedFromVec) {
5739       if (!VecIn2.getNode())
5740         VecIn2 = ExtractedFromVec;
5741       else if (VecIn2 != ExtractedFromVec)
5742         // Quit if more than 2 vectors to shuffle
5743         return SDValue();
5744     }
5745
5746     if (ExtractedFromVec == VecIn1)
5747       Mask[i] = Idx;
5748     else if (ExtractedFromVec == VecIn2)
5749       Mask[i] = Idx + NumElems;
5750   }
5751
5752   if (!VecIn1.getNode())
5753     return SDValue();
5754
5755   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5756   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5757   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5758     unsigned Idx = InsertIndices[i];
5759     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5760                      DAG.getIntPtrConstant(Idx, DL));
5761   }
5762
5763   return NV;
5764 }
5765
5766 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5767   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5768          Op.getScalarValueSizeInBits() == 1 &&
5769          "Can not convert non-constant vector");
5770   uint64_t Immediate = 0;
5771   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5772     SDValue In = Op.getOperand(idx);
5773     if (In.getOpcode() != ISD::UNDEF)
5774       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5775   }
5776   SDLoc dl(Op);
5777   MVT VT =
5778    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5779   return DAG.getConstant(Immediate, dl, VT);
5780 }
5781 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5782 SDValue
5783 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5784
5785   MVT VT = Op.getSimpleValueType();
5786   assert((VT.getVectorElementType() == MVT::i1) &&
5787          "Unexpected type in LowerBUILD_VECTORvXi1!");
5788
5789   SDLoc dl(Op);
5790   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5791     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5792     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5793     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5794   }
5795
5796   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5797     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5798     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5799     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5800   }
5801
5802   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5803     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5804     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5805       return DAG.getBitcast(VT, Imm);
5806     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5807     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5808                         DAG.getIntPtrConstant(0, dl));
5809   }
5810
5811   // Vector has one or more non-const elements
5812   uint64_t Immediate = 0;
5813   SmallVector<unsigned, 16> NonConstIdx;
5814   bool IsSplat = true;
5815   bool HasConstElts = false;
5816   int SplatIdx = -1;
5817   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5818     SDValue In = Op.getOperand(idx);
5819     if (In.getOpcode() == ISD::UNDEF)
5820       continue;
5821     if (!isa<ConstantSDNode>(In))
5822       NonConstIdx.push_back(idx);
5823     else {
5824       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5825       HasConstElts = true;
5826     }
5827     if (SplatIdx == -1)
5828       SplatIdx = idx;
5829     else if (In != Op.getOperand(SplatIdx))
5830       IsSplat = false;
5831   }
5832
5833   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5834   if (IsSplat)
5835     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5836                        DAG.getConstant(1, dl, VT),
5837                        DAG.getConstant(0, dl, VT));
5838
5839   // insert elements one by one
5840   SDValue DstVec;
5841   SDValue Imm;
5842   if (Immediate) {
5843     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5844     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5845   }
5846   else if (HasConstElts)
5847     Imm = DAG.getConstant(0, dl, VT);
5848   else
5849     Imm = DAG.getUNDEF(VT);
5850   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5851     DstVec = DAG.getBitcast(VT, Imm);
5852   else {
5853     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5854     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5855                          DAG.getIntPtrConstant(0, dl));
5856   }
5857
5858   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5859     unsigned InsertIdx = NonConstIdx[i];
5860     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5861                          Op.getOperand(InsertIdx),
5862                          DAG.getIntPtrConstant(InsertIdx, dl));
5863   }
5864   return DstVec;
5865 }
5866
5867 /// \brief Return true if \p N implements a horizontal binop and return the
5868 /// operands for the horizontal binop into V0 and V1.
5869 ///
5870 /// This is a helper function of LowerToHorizontalOp().
5871 /// This function checks that the build_vector \p N in input implements a
5872 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5873 /// operation to match.
5874 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5875 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5876 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5877 /// arithmetic sub.
5878 ///
5879 /// This function only analyzes elements of \p N whose indices are
5880 /// in range [BaseIdx, LastIdx).
5881 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5882                               SelectionDAG &DAG,
5883                               unsigned BaseIdx, unsigned LastIdx,
5884                               SDValue &V0, SDValue &V1) {
5885   EVT VT = N->getValueType(0);
5886
5887   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5888   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5889          "Invalid Vector in input!");
5890
5891   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5892   bool CanFold = true;
5893   unsigned ExpectedVExtractIdx = BaseIdx;
5894   unsigned NumElts = LastIdx - BaseIdx;
5895   V0 = DAG.getUNDEF(VT);
5896   V1 = DAG.getUNDEF(VT);
5897
5898   // Check if N implements a horizontal binop.
5899   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5900     SDValue Op = N->getOperand(i + BaseIdx);
5901
5902     // Skip UNDEFs.
5903     if (Op->getOpcode() == ISD::UNDEF) {
5904       // Update the expected vector extract index.
5905       if (i * 2 == NumElts)
5906         ExpectedVExtractIdx = BaseIdx;
5907       ExpectedVExtractIdx += 2;
5908       continue;
5909     }
5910
5911     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5912
5913     if (!CanFold)
5914       break;
5915
5916     SDValue Op0 = Op.getOperand(0);
5917     SDValue Op1 = Op.getOperand(1);
5918
5919     // Try to match the following pattern:
5920     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5921     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5922         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5923         Op0.getOperand(0) == Op1.getOperand(0) &&
5924         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5925         isa<ConstantSDNode>(Op1.getOperand(1)));
5926     if (!CanFold)
5927       break;
5928
5929     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5930     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5931
5932     if (i * 2 < NumElts) {
5933       if (V0.getOpcode() == ISD::UNDEF) {
5934         V0 = Op0.getOperand(0);
5935         if (V0.getValueType() != VT)
5936           return false;
5937       }
5938     } else {
5939       if (V1.getOpcode() == ISD::UNDEF) {
5940         V1 = Op0.getOperand(0);
5941         if (V1.getValueType() != VT)
5942           return false;
5943       }
5944       if (i * 2 == NumElts)
5945         ExpectedVExtractIdx = BaseIdx;
5946     }
5947
5948     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5949     if (I0 == ExpectedVExtractIdx)
5950       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5951     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5952       // Try to match the following dag sequence:
5953       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5954       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5955     } else
5956       CanFold = false;
5957
5958     ExpectedVExtractIdx += 2;
5959   }
5960
5961   return CanFold;
5962 }
5963
5964 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5965 /// a concat_vector.
5966 ///
5967 /// This is a helper function of LowerToHorizontalOp().
5968 /// This function expects two 256-bit vectors called V0 and V1.
5969 /// At first, each vector is split into two separate 128-bit vectors.
5970 /// Then, the resulting 128-bit vectors are used to implement two
5971 /// horizontal binary operations.
5972 ///
5973 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5974 ///
5975 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5976 /// the two new horizontal binop.
5977 /// When Mode is set, the first horizontal binop dag node would take as input
5978 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5979 /// horizontal binop dag node would take as input the lower 128-bit of V1
5980 /// and the upper 128-bit of V1.
5981 ///   Example:
5982 ///     HADD V0_LO, V0_HI
5983 ///     HADD V1_LO, V1_HI
5984 ///
5985 /// Otherwise, the first horizontal binop dag node takes as input the lower
5986 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5987 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5988 ///   Example:
5989 ///     HADD V0_LO, V1_LO
5990 ///     HADD V0_HI, V1_HI
5991 ///
5992 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5993 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5994 /// the upper 128-bits of the result.
5995 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5996                                      SDLoc DL, SelectionDAG &DAG,
5997                                      unsigned X86Opcode, bool Mode,
5998                                      bool isUndefLO, bool isUndefHI) {
5999   EVT VT = V0.getValueType();
6000   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6001          "Invalid nodes in input!");
6002
6003   unsigned NumElts = VT.getVectorNumElements();
6004   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6005   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6006   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6007   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6008   EVT NewVT = V0_LO.getValueType();
6009
6010   SDValue LO = DAG.getUNDEF(NewVT);
6011   SDValue HI = DAG.getUNDEF(NewVT);
6012
6013   if (Mode) {
6014     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6015     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6016       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6017     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6018       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6019   } else {
6020     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6021     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6022                        V1_LO->getOpcode() != ISD::UNDEF))
6023       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6024
6025     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6026                        V1_HI->getOpcode() != ISD::UNDEF))
6027       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6028   }
6029
6030   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6031 }
6032
6033 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6034 /// node.
6035 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6036                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6037   MVT VT = BV->getSimpleValueType(0);
6038   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6039       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6040     return SDValue();
6041
6042   SDLoc DL(BV);
6043   unsigned NumElts = VT.getVectorNumElements();
6044   SDValue InVec0 = DAG.getUNDEF(VT);
6045   SDValue InVec1 = DAG.getUNDEF(VT);
6046
6047   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6048           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6049
6050   // Odd-numbered elements in the input build vector are obtained from
6051   // adding two integer/float elements.
6052   // Even-numbered elements in the input build vector are obtained from
6053   // subtracting two integer/float elements.
6054   unsigned ExpectedOpcode = ISD::FSUB;
6055   unsigned NextExpectedOpcode = ISD::FADD;
6056   bool AddFound = false;
6057   bool SubFound = false;
6058
6059   for (unsigned i = 0, e = NumElts; i != e; ++i) {
6060     SDValue Op = BV->getOperand(i);
6061
6062     // Skip 'undef' values.
6063     unsigned Opcode = Op.getOpcode();
6064     if (Opcode == ISD::UNDEF) {
6065       std::swap(ExpectedOpcode, NextExpectedOpcode);
6066       continue;
6067     }
6068
6069     // Early exit if we found an unexpected opcode.
6070     if (Opcode != ExpectedOpcode)
6071       return SDValue();
6072
6073     SDValue Op0 = Op.getOperand(0);
6074     SDValue Op1 = Op.getOperand(1);
6075
6076     // Try to match the following pattern:
6077     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6078     // Early exit if we cannot match that sequence.
6079     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6080         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6081         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6082         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6083         Op0.getOperand(1) != Op1.getOperand(1))
6084       return SDValue();
6085
6086     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6087     if (I0 != i)
6088       return SDValue();
6089
6090     // We found a valid add/sub node. Update the information accordingly.
6091     if (i & 1)
6092       AddFound = true;
6093     else
6094       SubFound = true;
6095
6096     // Update InVec0 and InVec1.
6097     if (InVec0.getOpcode() == ISD::UNDEF) {
6098       InVec0 = Op0.getOperand(0);
6099       if (InVec0.getSimpleValueType() != VT)
6100         return SDValue();
6101     }
6102     if (InVec1.getOpcode() == ISD::UNDEF) {
6103       InVec1 = Op1.getOperand(0);
6104       if (InVec1.getSimpleValueType() != VT)
6105         return SDValue();
6106     }
6107
6108     // Make sure that operands in input to each add/sub node always
6109     // come from a same pair of vectors.
6110     if (InVec0 != Op0.getOperand(0)) {
6111       if (ExpectedOpcode == ISD::FSUB)
6112         return SDValue();
6113
6114       // FADD is commutable. Try to commute the operands
6115       // and then test again.
6116       std::swap(Op0, Op1);
6117       if (InVec0 != Op0.getOperand(0))
6118         return SDValue();
6119     }
6120
6121     if (InVec1 != Op1.getOperand(0))
6122       return SDValue();
6123
6124     // Update the pair of expected opcodes.
6125     std::swap(ExpectedOpcode, NextExpectedOpcode);
6126   }
6127
6128   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6129   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6130       InVec1.getOpcode() != ISD::UNDEF)
6131     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6132
6133   return SDValue();
6134 }
6135
6136 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6137 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6138                                    const X86Subtarget *Subtarget,
6139                                    SelectionDAG &DAG) {
6140   MVT VT = BV->getSimpleValueType(0);
6141   unsigned NumElts = VT.getVectorNumElements();
6142   unsigned NumUndefsLO = 0;
6143   unsigned NumUndefsHI = 0;
6144   unsigned Half = NumElts/2;
6145
6146   // Count the number of UNDEF operands in the build_vector in input.
6147   for (unsigned i = 0, e = Half; i != e; ++i)
6148     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6149       NumUndefsLO++;
6150
6151   for (unsigned i = Half, e = NumElts; i != e; ++i)
6152     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6153       NumUndefsHI++;
6154
6155   // Early exit if this is either a build_vector of all UNDEFs or all the
6156   // operands but one are UNDEF.
6157   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6158     return SDValue();
6159
6160   SDLoc DL(BV);
6161   SDValue InVec0, InVec1;
6162   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6163     // Try to match an SSE3 float HADD/HSUB.
6164     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6165       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6166
6167     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6168       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6169   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6170     // Try to match an SSSE3 integer HADD/HSUB.
6171     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6172       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6173
6174     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6175       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6176   }
6177
6178   if (!Subtarget->hasAVX())
6179     return SDValue();
6180
6181   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6182     // Try to match an AVX horizontal add/sub of packed single/double
6183     // precision floating point values from 256-bit vectors.
6184     SDValue InVec2, InVec3;
6185     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6186         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6187         ((InVec0.getOpcode() == ISD::UNDEF ||
6188           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6189         ((InVec1.getOpcode() == ISD::UNDEF ||
6190           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6191       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6192
6193     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6194         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6195         ((InVec0.getOpcode() == ISD::UNDEF ||
6196           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6197         ((InVec1.getOpcode() == ISD::UNDEF ||
6198           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6199       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6200   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6201     // Try to match an AVX2 horizontal add/sub of signed integers.
6202     SDValue InVec2, InVec3;
6203     unsigned X86Opcode;
6204     bool CanFold = true;
6205
6206     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6207         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6208         ((InVec0.getOpcode() == ISD::UNDEF ||
6209           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6210         ((InVec1.getOpcode() == ISD::UNDEF ||
6211           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6212       X86Opcode = X86ISD::HADD;
6213     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6214         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6215         ((InVec0.getOpcode() == ISD::UNDEF ||
6216           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6217         ((InVec1.getOpcode() == ISD::UNDEF ||
6218           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6219       X86Opcode = X86ISD::HSUB;
6220     else
6221       CanFold = false;
6222
6223     if (CanFold) {
6224       // Fold this build_vector into a single horizontal add/sub.
6225       // Do this only if the target has AVX2.
6226       if (Subtarget->hasAVX2())
6227         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6228
6229       // Do not try to expand this build_vector into a pair of horizontal
6230       // add/sub if we can emit a pair of scalar add/sub.
6231       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6232         return SDValue();
6233
6234       // Convert this build_vector into a pair of horizontal binop followed by
6235       // a concat vector.
6236       bool isUndefLO = NumUndefsLO == Half;
6237       bool isUndefHI = NumUndefsHI == Half;
6238       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6239                                    isUndefLO, isUndefHI);
6240     }
6241   }
6242
6243   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6244        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6245     unsigned X86Opcode;
6246     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6247       X86Opcode = X86ISD::HADD;
6248     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6249       X86Opcode = X86ISD::HSUB;
6250     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6251       X86Opcode = X86ISD::FHADD;
6252     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6253       X86Opcode = X86ISD::FHSUB;
6254     else
6255       return SDValue();
6256
6257     // Don't try to expand this build_vector into a pair of horizontal add/sub
6258     // if we can simply emit a pair of scalar add/sub.
6259     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6260       return SDValue();
6261
6262     // Convert this build_vector into two horizontal add/sub followed by
6263     // a concat vector.
6264     bool isUndefLO = NumUndefsLO == Half;
6265     bool isUndefHI = NumUndefsHI == Half;
6266     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6267                                  isUndefLO, isUndefHI);
6268   }
6269
6270   return SDValue();
6271 }
6272
6273 SDValue
6274 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6275   SDLoc dl(Op);
6276
6277   MVT VT = Op.getSimpleValueType();
6278   MVT ExtVT = VT.getVectorElementType();
6279   unsigned NumElems = Op.getNumOperands();
6280
6281   // Generate vectors for predicate vectors.
6282   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6283     return LowerBUILD_VECTORvXi1(Op, DAG);
6284
6285   // Vectors containing all zeros can be matched by pxor and xorps later
6286   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6287     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6288     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6289     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6290       return Op;
6291
6292     return getZeroVector(VT, Subtarget, DAG, dl);
6293   }
6294
6295   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6296   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6297   // vpcmpeqd on 256-bit vectors.
6298   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6299     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6300       return Op;
6301
6302     if (!VT.is512BitVector())
6303       return getOnesVector(VT, Subtarget, DAG, dl);
6304   }
6305
6306   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6307   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6308     return AddSub;
6309   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6310     return HorizontalOp;
6311   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6312     return Broadcast;
6313
6314   unsigned EVTBits = ExtVT.getSizeInBits();
6315
6316   unsigned NumZero  = 0;
6317   unsigned NumNonZero = 0;
6318   uint64_t NonZeros = 0;
6319   bool IsAllConstants = true;
6320   SmallSet<SDValue, 8> Values;
6321   for (unsigned i = 0; i < NumElems; ++i) {
6322     SDValue Elt = Op.getOperand(i);
6323     if (Elt.getOpcode() == ISD::UNDEF)
6324       continue;
6325     Values.insert(Elt);
6326     if (Elt.getOpcode() != ISD::Constant &&
6327         Elt.getOpcode() != ISD::ConstantFP)
6328       IsAllConstants = false;
6329     if (X86::isZeroNode(Elt))
6330       NumZero++;
6331     else {
6332       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6333       NonZeros |= ((uint64_t)1 << i);
6334       NumNonZero++;
6335     }
6336   }
6337
6338   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6339   if (NumNonZero == 0)
6340     return DAG.getUNDEF(VT);
6341
6342   // Special case for single non-zero, non-undef, element.
6343   if (NumNonZero == 1) {
6344     unsigned Idx = countTrailingZeros(NonZeros);
6345     SDValue Item = Op.getOperand(Idx);
6346
6347     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6348     // the value are obviously zero, truncate the value to i32 and do the
6349     // insertion that way.  Only do this if the value is non-constant or if the
6350     // value is a constant being inserted into element 0.  It is cheaper to do
6351     // a constant pool load than it is to do a movd + shuffle.
6352     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6353         (!IsAllConstants || Idx == 0)) {
6354       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6355         // Handle SSE only.
6356         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6357         MVT VecVT = MVT::v4i32;
6358
6359         // Truncate the value (which may itself be a constant) to i32, and
6360         // convert it to a vector with movd (S2V+shuffle to zero extend).
6361         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6362         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6363         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6364                                       Item, Idx * 2, true, Subtarget, DAG));
6365       }
6366     }
6367
6368     // If we have a constant or non-constant insertion into the low element of
6369     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6370     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6371     // depending on what the source datatype is.
6372     if (Idx == 0) {
6373       if (NumZero == 0)
6374         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6375
6376       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6377           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6378         if (VT.is512BitVector()) {
6379           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6380           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6381                              Item, DAG.getIntPtrConstant(0, dl));
6382         }
6383         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6384                "Expected an SSE value type!");
6385         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6386         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6387         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6388       }
6389
6390       // We can't directly insert an i8 or i16 into a vector, so zero extend
6391       // it to i32 first.
6392       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6393         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6394         if (VT.is256BitVector()) {
6395           if (Subtarget->hasAVX()) {
6396             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6397             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6398           } else {
6399             // Without AVX, we need to extend to a 128-bit vector and then
6400             // insert into the 256-bit vector.
6401             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6402             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6403             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6404           }
6405         } else {
6406           assert(VT.is128BitVector() && "Expected an SSE value type!");
6407           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6408           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6409         }
6410         return DAG.getBitcast(VT, Item);
6411       }
6412     }
6413
6414     // Is it a vector logical left shift?
6415     if (NumElems == 2 && Idx == 1 &&
6416         X86::isZeroNode(Op.getOperand(0)) &&
6417         !X86::isZeroNode(Op.getOperand(1))) {
6418       unsigned NumBits = VT.getSizeInBits();
6419       return getVShift(true, VT,
6420                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6421                                    VT, Op.getOperand(1)),
6422                        NumBits/2, DAG, *this, dl);
6423     }
6424
6425     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6426       return SDValue();
6427
6428     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6429     // is a non-constant being inserted into an element other than the low one,
6430     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6431     // movd/movss) to move this into the low element, then shuffle it into
6432     // place.
6433     if (EVTBits == 32) {
6434       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6435       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6436     }
6437   }
6438
6439   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6440   if (Values.size() == 1) {
6441     if (EVTBits == 32) {
6442       // Instead of a shuffle like this:
6443       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6444       // Check if it's possible to issue this instead.
6445       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6446       unsigned Idx = countTrailingZeros(NonZeros);
6447       SDValue Item = Op.getOperand(Idx);
6448       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6449         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6450     }
6451     return SDValue();
6452   }
6453
6454   // A vector full of immediates; various special cases are already
6455   // handled, so this is best done with a single constant-pool load.
6456   if (IsAllConstants)
6457     return SDValue();
6458
6459   // For AVX-length vectors, see if we can use a vector load to get all of the
6460   // elements, otherwise build the individual 128-bit pieces and use
6461   // shuffles to put them in place.
6462   if (VT.is256BitVector() || VT.is512BitVector()) {
6463     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6464
6465     // Check for a build vector of consecutive loads.
6466     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6467       return LD;
6468
6469     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6470
6471     // Build both the lower and upper subvector.
6472     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6473                                 makeArrayRef(&V[0], NumElems/2));
6474     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6475                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6476
6477     // Recreate the wider vector with the lower and upper part.
6478     if (VT.is256BitVector())
6479       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6480     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6481   }
6482
6483   // Let legalizer expand 2-wide build_vectors.
6484   if (EVTBits == 64) {
6485     if (NumNonZero == 1) {
6486       // One half is zero or undef.
6487       unsigned Idx = countTrailingZeros(NonZeros);
6488       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6489                                Op.getOperand(Idx));
6490       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6491     }
6492     return SDValue();
6493   }
6494
6495   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6496   if (EVTBits == 8 && NumElems == 16)
6497     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6498                                           DAG, Subtarget, *this))
6499       return V;
6500
6501   if (EVTBits == 16 && NumElems == 8)
6502     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6503                                           DAG, Subtarget, *this))
6504       return V;
6505
6506   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6507   if (EVTBits == 32 && NumElems == 4)
6508     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6509       return V;
6510
6511   // If element VT is == 32 bits, turn it into a number of shuffles.
6512   SmallVector<SDValue, 8> V(NumElems);
6513   if (NumElems == 4 && NumZero > 0) {
6514     for (unsigned i = 0; i < 4; ++i) {
6515       bool isZero = !(NonZeros & (1ULL << i));
6516       if (isZero)
6517         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6518       else
6519         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6520     }
6521
6522     for (unsigned i = 0; i < 2; ++i) {
6523       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6524         default: break;
6525         case 0:
6526           V[i] = V[i*2];  // Must be a zero vector.
6527           break;
6528         case 1:
6529           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6530           break;
6531         case 2:
6532           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6533           break;
6534         case 3:
6535           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6536           break;
6537       }
6538     }
6539
6540     bool Reverse1 = (NonZeros & 0x3) == 2;
6541     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6542     int MaskVec[] = {
6543       Reverse1 ? 1 : 0,
6544       Reverse1 ? 0 : 1,
6545       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6546       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6547     };
6548     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6549   }
6550
6551   if (Values.size() > 1 && VT.is128BitVector()) {
6552     // Check for a build vector of consecutive loads.
6553     for (unsigned i = 0; i < NumElems; ++i)
6554       V[i] = Op.getOperand(i);
6555
6556     // Check for elements which are consecutive loads.
6557     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6558       return LD;
6559
6560     // Check for a build vector from mostly shuffle plus few inserting.
6561     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6562       return Sh;
6563
6564     // For SSE 4.1, use insertps to put the high elements into the low element.
6565     if (Subtarget->hasSSE41()) {
6566       SDValue Result;
6567       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6568         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6569       else
6570         Result = DAG.getUNDEF(VT);
6571
6572       for (unsigned i = 1; i < NumElems; ++i) {
6573         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6574         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6575                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6576       }
6577       return Result;
6578     }
6579
6580     // Otherwise, expand into a number of unpckl*, start by extending each of
6581     // our (non-undef) elements to the full vector width with the element in the
6582     // bottom slot of the vector (which generates no code for SSE).
6583     for (unsigned i = 0; i < NumElems; ++i) {
6584       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6585         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6586       else
6587         V[i] = DAG.getUNDEF(VT);
6588     }
6589
6590     // Next, we iteratively mix elements, e.g. for v4f32:
6591     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6592     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6593     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6594     unsigned EltStride = NumElems >> 1;
6595     while (EltStride != 0) {
6596       for (unsigned i = 0; i < EltStride; ++i) {
6597         // If V[i+EltStride] is undef and this is the first round of mixing,
6598         // then it is safe to just drop this shuffle: V[i] is already in the
6599         // right place, the one element (since it's the first round) being
6600         // inserted as undef can be dropped.  This isn't safe for successive
6601         // rounds because they will permute elements within both vectors.
6602         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6603             EltStride == NumElems/2)
6604           continue;
6605
6606         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6607       }
6608       EltStride >>= 1;
6609     }
6610     return V[0];
6611   }
6612   return SDValue();
6613 }
6614
6615 // 256-bit AVX can use the vinsertf128 instruction
6616 // to create 256-bit vectors from two other 128-bit ones.
6617 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6618   SDLoc dl(Op);
6619   MVT ResVT = Op.getSimpleValueType();
6620
6621   assert((ResVT.is256BitVector() ||
6622           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6623
6624   SDValue V1 = Op.getOperand(0);
6625   SDValue V2 = Op.getOperand(1);
6626   unsigned NumElems = ResVT.getVectorNumElements();
6627   if (ResVT.is256BitVector())
6628     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6629
6630   if (Op.getNumOperands() == 4) {
6631     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6632                                   ResVT.getVectorNumElements()/2);
6633     SDValue V3 = Op.getOperand(2);
6634     SDValue V4 = Op.getOperand(3);
6635     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6636       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6637   }
6638   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6639 }
6640
6641 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6642                                        const X86Subtarget *Subtarget,
6643                                        SelectionDAG & DAG) {
6644   SDLoc dl(Op);
6645   MVT ResVT = Op.getSimpleValueType();
6646   unsigned NumOfOperands = Op.getNumOperands();
6647
6648   assert(isPowerOf2_32(NumOfOperands) &&
6649          "Unexpected number of operands in CONCAT_VECTORS");
6650
6651   SDValue Undef = DAG.getUNDEF(ResVT);
6652   if (NumOfOperands > 2) {
6653     // Specialize the cases when all, or all but one, of the operands are undef.
6654     unsigned NumOfDefinedOps = 0;
6655     unsigned OpIdx = 0;
6656     for (unsigned i = 0; i < NumOfOperands; i++)
6657       if (!Op.getOperand(i).isUndef()) {
6658         NumOfDefinedOps++;
6659         OpIdx = i;
6660       }
6661     if (NumOfDefinedOps == 0)
6662       return Undef;
6663     if (NumOfDefinedOps == 1) {
6664       unsigned SubVecNumElts =
6665         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6666       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6667       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6668                          Op.getOperand(OpIdx), IdxVal);
6669     }
6670
6671     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6672                                   ResVT.getVectorNumElements()/2);
6673     SmallVector<SDValue, 2> Ops;
6674     for (unsigned i = 0; i < NumOfOperands/2; i++)
6675       Ops.push_back(Op.getOperand(i));
6676     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6677     Ops.clear();
6678     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6679       Ops.push_back(Op.getOperand(i));
6680     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6681     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6682   }
6683
6684   // 2 operands
6685   SDValue V1 = Op.getOperand(0);
6686   SDValue V2 = Op.getOperand(1);
6687   unsigned NumElems = ResVT.getVectorNumElements();
6688   assert(V1.getValueType() == V2.getValueType() &&
6689          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6690          "Unexpected operands in CONCAT_VECTORS");
6691
6692   if (ResVT.getSizeInBits() >= 16)
6693     return Op; // The operation is legal with KUNPCK
6694
6695   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6696   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6697   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6698   if (IsZeroV1 && IsZeroV2)
6699     return ZeroVec;
6700
6701   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6702   if (V2.isUndef())
6703     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6704   if (IsZeroV2)
6705     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6706
6707   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6708   if (V1.isUndef())
6709     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6710
6711   if (IsZeroV1)
6712     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6713
6714   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6715   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6716 }
6717
6718 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6719                                    const X86Subtarget *Subtarget,
6720                                    SelectionDAG &DAG) {
6721   MVT VT = Op.getSimpleValueType();
6722   if (VT.getVectorElementType() == MVT::i1)
6723     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6724
6725   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6726          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6727           Op.getNumOperands() == 4)));
6728
6729   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6730   // from two other 128-bit ones.
6731
6732   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6733   return LowerAVXCONCAT_VECTORS(Op, DAG);
6734 }
6735
6736 //===----------------------------------------------------------------------===//
6737 // Vector shuffle lowering
6738 //
6739 // This is an experimental code path for lowering vector shuffles on x86. It is
6740 // designed to handle arbitrary vector shuffles and blends, gracefully
6741 // degrading performance as necessary. It works hard to recognize idiomatic
6742 // shuffles and lower them to optimal instruction patterns without leaving
6743 // a framework that allows reasonably efficient handling of all vector shuffle
6744 // patterns.
6745 //===----------------------------------------------------------------------===//
6746
6747 /// \brief Tiny helper function to identify a no-op mask.
6748 ///
6749 /// This is a somewhat boring predicate function. It checks whether the mask
6750 /// array input, which is assumed to be a single-input shuffle mask of the kind
6751 /// used by the X86 shuffle instructions (not a fully general
6752 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6753 /// in-place shuffle are 'no-op's.
6754 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6755   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6756     if (Mask[i] != -1 && Mask[i] != i)
6757       return false;
6758   return true;
6759 }
6760
6761 /// \brief Helper function to classify a mask as a single-input mask.
6762 ///
6763 /// This isn't a generic single-input test because in the vector shuffle
6764 /// lowering we canonicalize single inputs to be the first input operand. This
6765 /// means we can more quickly test for a single input by only checking whether
6766 /// an input from the second operand exists. We also assume that the size of
6767 /// mask corresponds to the size of the input vectors which isn't true in the
6768 /// fully general case.
6769 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6770   for (int M : Mask)
6771     if (M >= (int)Mask.size())
6772       return false;
6773   return true;
6774 }
6775
6776 /// \brief Test whether there are elements crossing 128-bit lanes in this
6777 /// shuffle mask.
6778 ///
6779 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6780 /// and we routinely test for these.
6781 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6782   int LaneSize = 128 / VT.getScalarSizeInBits();
6783   int Size = Mask.size();
6784   for (int i = 0; i < Size; ++i)
6785     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6786       return true;
6787   return false;
6788 }
6789
6790 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6791 ///
6792 /// This checks a shuffle mask to see if it is performing the same
6793 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6794 /// that it is also not lane-crossing. It may however involve a blend from the
6795 /// same lane of a second vector.
6796 ///
6797 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6798 /// non-trivial to compute in the face of undef lanes. The representation is
6799 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6800 /// entries from both V1 and V2 inputs to the wider mask.
6801 static bool
6802 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6803                                 SmallVectorImpl<int> &RepeatedMask) {
6804   int LaneSize = 128 / VT.getScalarSizeInBits();
6805   RepeatedMask.resize(LaneSize, -1);
6806   int Size = Mask.size();
6807   for (int i = 0; i < Size; ++i) {
6808     if (Mask[i] < 0)
6809       continue;
6810     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6811       // This entry crosses lanes, so there is no way to model this shuffle.
6812       return false;
6813
6814     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6815     if (RepeatedMask[i % LaneSize] == -1)
6816       // This is the first non-undef entry in this slot of a 128-bit lane.
6817       RepeatedMask[i % LaneSize] =
6818           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6819     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6820       // Found a mismatch with the repeated mask.
6821       return false;
6822   }
6823   return true;
6824 }
6825
6826 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6827 /// arguments.
6828 ///
6829 /// This is a fast way to test a shuffle mask against a fixed pattern:
6830 ///
6831 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6832 ///
6833 /// It returns true if the mask is exactly as wide as the argument list, and
6834 /// each element of the mask is either -1 (signifying undef) or the value given
6835 /// in the argument.
6836 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6837                                 ArrayRef<int> ExpectedMask) {
6838   if (Mask.size() != ExpectedMask.size())
6839     return false;
6840
6841   int Size = Mask.size();
6842
6843   // If the values are build vectors, we can look through them to find
6844   // equivalent inputs that make the shuffles equivalent.
6845   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6846   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6847
6848   for (int i = 0; i < Size; ++i)
6849     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6850       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6851       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6852       if (!MaskBV || !ExpectedBV ||
6853           MaskBV->getOperand(Mask[i] % Size) !=
6854               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6855         return false;
6856     }
6857
6858   return true;
6859 }
6860
6861 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6862 ///
6863 /// This helper function produces an 8-bit shuffle immediate corresponding to
6864 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6865 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6866 /// example.
6867 ///
6868 /// NB: We rely heavily on "undef" masks preserving the input lane.
6869 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6870                                           SelectionDAG &DAG) {
6871   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6872   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6873   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6874   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6875   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6876
6877   unsigned Imm = 0;
6878   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6879   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6880   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6881   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6882   return DAG.getConstant(Imm, DL, MVT::i8);
6883 }
6884
6885 /// \brief Compute whether each element of a shuffle is zeroable.
6886 ///
6887 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6888 /// Either it is an undef element in the shuffle mask, the element of the input
6889 /// referenced is undef, or the element of the input referenced is known to be
6890 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6891 /// as many lanes with this technique as possible to simplify the remaining
6892 /// shuffle.
6893 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6894                                                      SDValue V1, SDValue V2) {
6895   SmallBitVector Zeroable(Mask.size(), false);
6896
6897   while (V1.getOpcode() == ISD::BITCAST)
6898     V1 = V1->getOperand(0);
6899   while (V2.getOpcode() == ISD::BITCAST)
6900     V2 = V2->getOperand(0);
6901
6902   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6903   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6904
6905   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6906     int M = Mask[i];
6907     // Handle the easy cases.
6908     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6909       Zeroable[i] = true;
6910       continue;
6911     }
6912
6913     // If this is an index into a build_vector node (which has the same number
6914     // of elements), dig out the input value and use it.
6915     SDValue V = M < Size ? V1 : V2;
6916     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6917       continue;
6918
6919     SDValue Input = V.getOperand(M % Size);
6920     // The UNDEF opcode check really should be dead code here, but not quite
6921     // worth asserting on (it isn't invalid, just unexpected).
6922     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6923       Zeroable[i] = true;
6924   }
6925
6926   return Zeroable;
6927 }
6928
6929 // X86 has dedicated unpack instructions that can handle specific blend
6930 // operations: UNPCKH and UNPCKL.
6931 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6932                                            SDValue V1, SDValue V2,
6933                                            SelectionDAG &DAG) {
6934   int NumElts = VT.getVectorNumElements();
6935   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6936   SmallVector<int, 8> Unpckl;
6937   SmallVector<int, 8> Unpckh;
6938
6939   for (int i = 0; i < NumElts; ++i) {
6940     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6941     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6942     int HiPos = LoPos + NumEltsInLane / 2;
6943     Unpckl.push_back(LoPos);
6944     Unpckh.push_back(HiPos);
6945   }
6946
6947   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6948     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6949   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6950     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6951
6952   // Commute and try again.
6953   ShuffleVectorSDNode::commuteMask(Unpckl);
6954   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6955     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6956
6957   ShuffleVectorSDNode::commuteMask(Unpckh);
6958   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6959     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6960
6961   return SDValue();
6962 }
6963
6964 /// \brief Try to emit a bitmask instruction for a shuffle.
6965 ///
6966 /// This handles cases where we can model a blend exactly as a bitmask due to
6967 /// one of the inputs being zeroable.
6968 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6969                                            SDValue V2, ArrayRef<int> Mask,
6970                                            SelectionDAG &DAG) {
6971   MVT EltVT = VT.getVectorElementType();
6972   int NumEltBits = EltVT.getSizeInBits();
6973   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6974   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6975   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6976                                     IntEltVT);
6977   if (EltVT.isFloatingPoint()) {
6978     Zero = DAG.getBitcast(EltVT, Zero);
6979     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6980   }
6981   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6982   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6983   SDValue V;
6984   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6985     if (Zeroable[i])
6986       continue;
6987     if (Mask[i] % Size != i)
6988       return SDValue(); // Not a blend.
6989     if (!V)
6990       V = Mask[i] < Size ? V1 : V2;
6991     else if (V != (Mask[i] < Size ? V1 : V2))
6992       return SDValue(); // Can only let one input through the mask.
6993
6994     VMaskOps[i] = AllOnes;
6995   }
6996   if (!V)
6997     return SDValue(); // No non-zeroable elements!
6998
6999   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7000   V = DAG.getNode(VT.isFloatingPoint()
7001                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7002                   DL, VT, V, VMask);
7003   return V;
7004 }
7005
7006 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7007 ///
7008 /// This is used as a fallback approach when first class blend instructions are
7009 /// unavailable. Currently it is only suitable for integer vectors, but could
7010 /// be generalized for floating point vectors if desirable.
7011 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7012                                             SDValue V2, ArrayRef<int> Mask,
7013                                             SelectionDAG &DAG) {
7014   assert(VT.isInteger() && "Only supports integer vector types!");
7015   MVT EltVT = VT.getVectorElementType();
7016   int NumEltBits = EltVT.getSizeInBits();
7017   SDValue Zero = DAG.getConstant(0, DL, EltVT);
7018   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7019                                     EltVT);
7020   SmallVector<SDValue, 16> MaskOps;
7021   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7022     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7023       return SDValue(); // Shuffled input!
7024     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7025   }
7026
7027   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7028   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7029   // We have to cast V2 around.
7030   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7031   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7032                                       DAG.getBitcast(MaskVT, V1Mask),
7033                                       DAG.getBitcast(MaskVT, V2)));
7034   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7035 }
7036
7037 /// \brief Try to emit a blend instruction for a shuffle.
7038 ///
7039 /// This doesn't do any checks for the availability of instructions for blending
7040 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7041 /// be matched in the backend with the type given. What it does check for is
7042 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7043 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7044                                          SDValue V2, ArrayRef<int> Original,
7045                                          const X86Subtarget *Subtarget,
7046                                          SelectionDAG &DAG) {
7047   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7048   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7049   SmallVector<int, 8> Mask(Original.begin(), Original.end());
7050   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7051   bool ForceV1Zero = false, ForceV2Zero = false;
7052
7053   // Attempt to generate the binary blend mask. If an input is zero then
7054   // we can use any lane.
7055   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7056   unsigned BlendMask = 0;
7057   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7058     int M = Mask[i];
7059     if (M < 0)
7060       continue;
7061     if (M == i)
7062       continue;
7063     if (M == i + Size) {
7064       BlendMask |= 1u << i;
7065       continue;
7066     }
7067     if (Zeroable[i]) {
7068       if (V1IsZero) {
7069         ForceV1Zero = true;
7070         Mask[i] = i;
7071         continue;
7072       }
7073       if (V2IsZero) {
7074         ForceV2Zero = true;
7075         BlendMask |= 1u << i;
7076         Mask[i] = i + Size;
7077         continue;
7078       }
7079     }
7080     return SDValue(); // Shuffled input!
7081   }
7082
7083   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7084   if (ForceV1Zero)
7085     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7086   if (ForceV2Zero)
7087     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7088
7089   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7090     unsigned ScaledMask = 0;
7091     for (int i = 0; i != Size; ++i)
7092       if (BlendMask & (1u << i))
7093         for (int j = 0; j != Scale; ++j)
7094           ScaledMask |= 1u << (i * Scale + j);
7095     return ScaledMask;
7096   };
7097
7098   switch (VT.SimpleTy) {
7099   case MVT::v2f64:
7100   case MVT::v4f32:
7101   case MVT::v4f64:
7102   case MVT::v8f32:
7103     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7104                        DAG.getConstant(BlendMask, DL, MVT::i8));
7105
7106   case MVT::v4i64:
7107   case MVT::v8i32:
7108     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7109     // FALLTHROUGH
7110   case MVT::v2i64:
7111   case MVT::v4i32:
7112     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7113     // that instruction.
7114     if (Subtarget->hasAVX2()) {
7115       // Scale the blend by the number of 32-bit dwords per element.
7116       int Scale =  VT.getScalarSizeInBits() / 32;
7117       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7118       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7119       V1 = DAG.getBitcast(BlendVT, V1);
7120       V2 = DAG.getBitcast(BlendVT, V2);
7121       return DAG.getBitcast(
7122           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7123                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7124     }
7125     // FALLTHROUGH
7126   case MVT::v8i16: {
7127     // For integer shuffles we need to expand the mask and cast the inputs to
7128     // v8i16s prior to blending.
7129     int Scale = 8 / VT.getVectorNumElements();
7130     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7131     V1 = DAG.getBitcast(MVT::v8i16, V1);
7132     V2 = DAG.getBitcast(MVT::v8i16, V2);
7133     return DAG.getBitcast(VT,
7134                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7135                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7136   }
7137
7138   case MVT::v16i16: {
7139     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7140     SmallVector<int, 8> RepeatedMask;
7141     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7142       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7143       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7144       BlendMask = 0;
7145       for (int i = 0; i < 8; ++i)
7146         if (RepeatedMask[i] >= 16)
7147           BlendMask |= 1u << i;
7148       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7149                          DAG.getConstant(BlendMask, DL, MVT::i8));
7150     }
7151   }
7152     // FALLTHROUGH
7153   case MVT::v16i8:
7154   case MVT::v32i8: {
7155     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7156            "256-bit byte-blends require AVX2 support!");
7157
7158     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7159     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7160       return Masked;
7161
7162     // Scale the blend by the number of bytes per element.
7163     int Scale = VT.getScalarSizeInBits() / 8;
7164
7165     // This form of blend is always done on bytes. Compute the byte vector
7166     // type.
7167     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7168
7169     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7170     // mix of LLVM's code generator and the x86 backend. We tell the code
7171     // generator that boolean values in the elements of an x86 vector register
7172     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7173     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7174     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7175     // of the element (the remaining are ignored) and 0 in that high bit would
7176     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7177     // the LLVM model for boolean values in vector elements gets the relevant
7178     // bit set, it is set backwards and over constrained relative to x86's
7179     // actual model.
7180     SmallVector<SDValue, 32> VSELECTMask;
7181     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7182       for (int j = 0; j < Scale; ++j)
7183         VSELECTMask.push_back(
7184             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7185                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7186                                           MVT::i8));
7187
7188     V1 = DAG.getBitcast(BlendVT, V1);
7189     V2 = DAG.getBitcast(BlendVT, V2);
7190     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7191                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7192                                                       BlendVT, VSELECTMask),
7193                                           V1, V2));
7194   }
7195
7196   default:
7197     llvm_unreachable("Not a supported integer vector type!");
7198   }
7199 }
7200
7201 /// \brief Try to lower as a blend of elements from two inputs followed by
7202 /// a single-input permutation.
7203 ///
7204 /// This matches the pattern where we can blend elements from two inputs and
7205 /// then reduce the shuffle to a single-input permutation.
7206 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7207                                                    SDValue V2,
7208                                                    ArrayRef<int> Mask,
7209                                                    SelectionDAG &DAG) {
7210   // We build up the blend mask while checking whether a blend is a viable way
7211   // to reduce the shuffle.
7212   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7213   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7214
7215   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7216     if (Mask[i] < 0)
7217       continue;
7218
7219     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7220
7221     if (BlendMask[Mask[i] % Size] == -1)
7222       BlendMask[Mask[i] % Size] = Mask[i];
7223     else if (BlendMask[Mask[i] % Size] != Mask[i])
7224       return SDValue(); // Can't blend in the needed input!
7225
7226     PermuteMask[i] = Mask[i] % Size;
7227   }
7228
7229   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7230   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7231 }
7232
7233 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7234 /// blends and permutes.
7235 ///
7236 /// This matches the extremely common pattern for handling combined
7237 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7238 /// operations. It will try to pick the best arrangement of shuffles and
7239 /// blends.
7240 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7241                                                           SDValue V1,
7242                                                           SDValue V2,
7243                                                           ArrayRef<int> Mask,
7244                                                           SelectionDAG &DAG) {
7245   // Shuffle the input elements into the desired positions in V1 and V2 and
7246   // blend them together.
7247   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7248   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7249   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7250   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7251     if (Mask[i] >= 0 && Mask[i] < Size) {
7252       V1Mask[i] = Mask[i];
7253       BlendMask[i] = i;
7254     } else if (Mask[i] >= Size) {
7255       V2Mask[i] = Mask[i] - Size;
7256       BlendMask[i] = i + Size;
7257     }
7258
7259   // Try to lower with the simpler initial blend strategy unless one of the
7260   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7261   // shuffle may be able to fold with a load or other benefit. However, when
7262   // we'll have to do 2x as many shuffles in order to achieve this, blending
7263   // first is a better strategy.
7264   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7265     if (SDValue BlendPerm =
7266             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7267       return BlendPerm;
7268
7269   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7270   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7271   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7272 }
7273
7274 /// \brief Try to lower a vector shuffle as a byte rotation.
7275 ///
7276 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7277 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7278 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7279 /// try to generically lower a vector shuffle through such an pattern. It
7280 /// does not check for the profitability of lowering either as PALIGNR or
7281 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7282 /// This matches shuffle vectors that look like:
7283 ///
7284 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7285 ///
7286 /// Essentially it concatenates V1 and V2, shifts right by some number of
7287 /// elements, and takes the low elements as the result. Note that while this is
7288 /// specified as a *right shift* because x86 is little-endian, it is a *left
7289 /// rotate* of the vector lanes.
7290 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7291                                               SDValue V2,
7292                                               ArrayRef<int> Mask,
7293                                               const X86Subtarget *Subtarget,
7294                                               SelectionDAG &DAG) {
7295   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7296
7297   int NumElts = Mask.size();
7298   int NumLanes = VT.getSizeInBits() / 128;
7299   int NumLaneElts = NumElts / NumLanes;
7300
7301   // We need to detect various ways of spelling a rotation:
7302   //   [11, 12, 13, 14, 15,  0,  1,  2]
7303   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7304   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7305   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7306   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7307   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7308   int Rotation = 0;
7309   SDValue Lo, Hi;
7310   for (int l = 0; l < NumElts; l += NumLaneElts) {
7311     for (int i = 0; i < NumLaneElts; ++i) {
7312       if (Mask[l + i] == -1)
7313         continue;
7314       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7315
7316       // Get the mod-Size index and lane correct it.
7317       int LaneIdx = (Mask[l + i] % NumElts) - l;
7318       // Make sure it was in this lane.
7319       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7320         return SDValue();
7321
7322       // Determine where a rotated vector would have started.
7323       int StartIdx = i - LaneIdx;
7324       if (StartIdx == 0)
7325         // The identity rotation isn't interesting, stop.
7326         return SDValue();
7327
7328       // If we found the tail of a vector the rotation must be the missing
7329       // front. If we found the head of a vector, it must be how much of the
7330       // head.
7331       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7332
7333       if (Rotation == 0)
7334         Rotation = CandidateRotation;
7335       else if (Rotation != CandidateRotation)
7336         // The rotations don't match, so we can't match this mask.
7337         return SDValue();
7338
7339       // Compute which value this mask is pointing at.
7340       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7341
7342       // Compute which of the two target values this index should be assigned
7343       // to. This reflects whether the high elements are remaining or the low
7344       // elements are remaining.
7345       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7346
7347       // Either set up this value if we've not encountered it before, or check
7348       // that it remains consistent.
7349       if (!TargetV)
7350         TargetV = MaskV;
7351       else if (TargetV != MaskV)
7352         // This may be a rotation, but it pulls from the inputs in some
7353         // unsupported interleaving.
7354         return SDValue();
7355     }
7356   }
7357
7358   // Check that we successfully analyzed the mask, and normalize the results.
7359   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7360   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7361   if (!Lo)
7362     Lo = Hi;
7363   else if (!Hi)
7364     Hi = Lo;
7365
7366   // The actual rotate instruction rotates bytes, so we need to scale the
7367   // rotation based on how many bytes are in the vector lane.
7368   int Scale = 16 / NumLaneElts;
7369
7370   // SSSE3 targets can use the palignr instruction.
7371   if (Subtarget->hasSSSE3()) {
7372     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7373     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7374     Lo = DAG.getBitcast(AlignVT, Lo);
7375     Hi = DAG.getBitcast(AlignVT, Hi);
7376
7377     return DAG.getBitcast(
7378         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7379                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7380   }
7381
7382   assert(VT.is128BitVector() &&
7383          "Rotate-based lowering only supports 128-bit lowering!");
7384   assert(Mask.size() <= 16 &&
7385          "Can shuffle at most 16 bytes in a 128-bit vector!");
7386
7387   // Default SSE2 implementation
7388   int LoByteShift = 16 - Rotation * Scale;
7389   int HiByteShift = Rotation * Scale;
7390
7391   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7392   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7393   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7394
7395   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7396                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7397   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7398                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7399   return DAG.getBitcast(VT,
7400                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7401 }
7402
7403 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7404 ///
7405 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7406 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7407 /// matches elements from one of the input vectors shuffled to the left or
7408 /// right with zeroable elements 'shifted in'. It handles both the strictly
7409 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7410 /// quad word lane.
7411 ///
7412 /// PSHL : (little-endian) left bit shift.
7413 /// [ zz, 0, zz,  2 ]
7414 /// [ -1, 4, zz, -1 ]
7415 /// PSRL : (little-endian) right bit shift.
7416 /// [  1, zz,  3, zz]
7417 /// [ -1, -1,  7, zz]
7418 /// PSLLDQ : (little-endian) left byte shift
7419 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7420 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7421 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7422 /// PSRLDQ : (little-endian) right byte shift
7423 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7424 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7425 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7426 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7427                                          SDValue V2, ArrayRef<int> Mask,
7428                                          SelectionDAG &DAG) {
7429   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7430
7431   int Size = Mask.size();
7432   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7433
7434   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7435     for (int i = 0; i < Size; i += Scale)
7436       for (int j = 0; j < Shift; ++j)
7437         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7438           return false;
7439
7440     return true;
7441   };
7442
7443   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7444     for (int i = 0; i != Size; i += Scale) {
7445       unsigned Pos = Left ? i + Shift : i;
7446       unsigned Low = Left ? i : i + Shift;
7447       unsigned Len = Scale - Shift;
7448       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7449                                       Low + (V == V1 ? 0 : Size)))
7450         return SDValue();
7451     }
7452
7453     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7454     bool ByteShift = ShiftEltBits > 64;
7455     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7456                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7457     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7458
7459     // Normalize the scale for byte shifts to still produce an i64 element
7460     // type.
7461     Scale = ByteShift ? Scale / 2 : Scale;
7462
7463     // We need to round trip through the appropriate type for the shift.
7464     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7465     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7466     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7467            "Illegal integer vector type");
7468     V = DAG.getBitcast(ShiftVT, V);
7469
7470     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7471                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7472     return DAG.getBitcast(VT, V);
7473   };
7474
7475   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7476   // keep doubling the size of the integer elements up to that. We can
7477   // then shift the elements of the integer vector by whole multiples of
7478   // their width within the elements of the larger integer vector. Test each
7479   // multiple to see if we can find a match with the moved element indices
7480   // and that the shifted in elements are all zeroable.
7481   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7482     for (int Shift = 1; Shift != Scale; ++Shift)
7483       for (bool Left : {true, false})
7484         if (CheckZeros(Shift, Scale, Left))
7485           for (SDValue V : {V1, V2})
7486             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7487               return Match;
7488
7489   // no match
7490   return SDValue();
7491 }
7492
7493 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7494 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7495                                            SDValue V2, ArrayRef<int> Mask,
7496                                            SelectionDAG &DAG) {
7497   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7498   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7499
7500   int Size = Mask.size();
7501   int HalfSize = Size / 2;
7502   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7503
7504   // Upper half must be undefined.
7505   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7506     return SDValue();
7507
7508   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7509   // Remainder of lower half result is zero and upper half is all undef.
7510   auto LowerAsEXTRQ = [&]() {
7511     // Determine the extraction length from the part of the
7512     // lower half that isn't zeroable.
7513     int Len = HalfSize;
7514     for (; Len > 0; --Len)
7515       if (!Zeroable[Len - 1])
7516         break;
7517     assert(Len > 0 && "Zeroable shuffle mask");
7518
7519     // Attempt to match first Len sequential elements from the lower half.
7520     SDValue Src;
7521     int Idx = -1;
7522     for (int i = 0; i != Len; ++i) {
7523       int M = Mask[i];
7524       if (M < 0)
7525         continue;
7526       SDValue &V = (M < Size ? V1 : V2);
7527       M = M % Size;
7528
7529       // The extracted elements must start at a valid index and all mask
7530       // elements must be in the lower half.
7531       if (i > M || M >= HalfSize)
7532         return SDValue();
7533
7534       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7535         Src = V;
7536         Idx = M - i;
7537         continue;
7538       }
7539       return SDValue();
7540     }
7541
7542     if (Idx < 0)
7543       return SDValue();
7544
7545     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7546     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7547     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7548     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7549                        DAG.getConstant(BitLen, DL, MVT::i8),
7550                        DAG.getConstant(BitIdx, DL, MVT::i8));
7551   };
7552
7553   if (SDValue ExtrQ = LowerAsEXTRQ())
7554     return ExtrQ;
7555
7556   // INSERTQ: Extract lowest Len elements from lower half of second source and
7557   // insert over first source, starting at Idx.
7558   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7559   auto LowerAsInsertQ = [&]() {
7560     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7561       SDValue Base;
7562
7563       // Attempt to match first source from mask before insertion point.
7564       if (isUndefInRange(Mask, 0, Idx)) {
7565         /* EMPTY */
7566       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7567         Base = V1;
7568       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7569         Base = V2;
7570       } else {
7571         continue;
7572       }
7573
7574       // Extend the extraction length looking to match both the insertion of
7575       // the second source and the remaining elements of the first.
7576       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7577         SDValue Insert;
7578         int Len = Hi - Idx;
7579
7580         // Match insertion.
7581         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7582           Insert = V1;
7583         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7584           Insert = V2;
7585         } else {
7586           continue;
7587         }
7588
7589         // Match the remaining elements of the lower half.
7590         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7591           /* EMPTY */
7592         } else if ((!Base || (Base == V1)) &&
7593                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7594           Base = V1;
7595         } else if ((!Base || (Base == V2)) &&
7596                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7597                                               Size + Hi)) {
7598           Base = V2;
7599         } else {
7600           continue;
7601         }
7602
7603         // We may not have a base (first source) - this can safely be undefined.
7604         if (!Base)
7605           Base = DAG.getUNDEF(VT);
7606
7607         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7608         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7609         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7610                            DAG.getConstant(BitLen, DL, MVT::i8),
7611                            DAG.getConstant(BitIdx, DL, MVT::i8));
7612       }
7613     }
7614
7615     return SDValue();
7616   };
7617
7618   if (SDValue InsertQ = LowerAsInsertQ())
7619     return InsertQ;
7620
7621   return SDValue();
7622 }
7623
7624 /// \brief Lower a vector shuffle as a zero or any extension.
7625 ///
7626 /// Given a specific number of elements, element bit width, and extension
7627 /// stride, produce either a zero or any extension based on the available
7628 /// features of the subtarget. The extended elements are consecutive and
7629 /// begin and can start from an offseted element index in the input; to
7630 /// avoid excess shuffling the offset must either being in the bottom lane
7631 /// or at the start of a higher lane. All extended elements must be from
7632 /// the same lane.
7633 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7634     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7635     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7636   assert(Scale > 1 && "Need a scale to extend.");
7637   int EltBits = VT.getScalarSizeInBits();
7638   int NumElements = VT.getVectorNumElements();
7639   int NumEltsPerLane = 128 / EltBits;
7640   int OffsetLane = Offset / NumEltsPerLane;
7641   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7642          "Only 8, 16, and 32 bit elements can be extended.");
7643   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7644   assert(0 <= Offset && "Extension offset must be positive.");
7645   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7646          "Extension offset must be in the first lane or start an upper lane.");
7647
7648   // Check that an index is in same lane as the base offset.
7649   auto SafeOffset = [&](int Idx) {
7650     return OffsetLane == (Idx / NumEltsPerLane);
7651   };
7652
7653   // Shift along an input so that the offset base moves to the first element.
7654   auto ShuffleOffset = [&](SDValue V) {
7655     if (!Offset)
7656       return V;
7657
7658     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7659     for (int i = 0; i * Scale < NumElements; ++i) {
7660       int SrcIdx = i + Offset;
7661       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7662     }
7663     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7664   };
7665
7666   // Found a valid zext mask! Try various lowering strategies based on the
7667   // input type and available ISA extensions.
7668   if (Subtarget->hasSSE41()) {
7669     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7670     // PUNPCK will catch this in a later shuffle match.
7671     if (Offset && Scale == 2 && VT.is128BitVector())
7672       return SDValue();
7673     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7674                                  NumElements / Scale);
7675     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7676     return DAG.getBitcast(VT, InputV);
7677   }
7678
7679   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7680
7681   // For any extends we can cheat for larger element sizes and use shuffle
7682   // instructions that can fold with a load and/or copy.
7683   if (AnyExt && EltBits == 32) {
7684     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7685                          -1};
7686     return DAG.getBitcast(
7687         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7688                         DAG.getBitcast(MVT::v4i32, InputV),
7689                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7690   }
7691   if (AnyExt && EltBits == 16 && Scale > 2) {
7692     int PSHUFDMask[4] = {Offset / 2, -1,
7693                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7694     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7695                          DAG.getBitcast(MVT::v4i32, InputV),
7696                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7697     int PSHUFWMask[4] = {1, -1, -1, -1};
7698     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7699     return DAG.getBitcast(
7700         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7701                         DAG.getBitcast(MVT::v8i16, InputV),
7702                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7703   }
7704
7705   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7706   // to 64-bits.
7707   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7708     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7709     assert(VT.is128BitVector() && "Unexpected vector width!");
7710
7711     int LoIdx = Offset * EltBits;
7712     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7713                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7714                                          DAG.getConstant(EltBits, DL, MVT::i8),
7715                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7716
7717     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7718         !SafeOffset(Offset + 1))
7719       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7720
7721     int HiIdx = (Offset + 1) * EltBits;
7722     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7723                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7724                                          DAG.getConstant(EltBits, DL, MVT::i8),
7725                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7726     return DAG.getNode(ISD::BITCAST, DL, VT,
7727                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7728   }
7729
7730   // If this would require more than 2 unpack instructions to expand, use
7731   // pshufb when available. We can only use more than 2 unpack instructions
7732   // when zero extending i8 elements which also makes it easier to use pshufb.
7733   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7734     assert(NumElements == 16 && "Unexpected byte vector width!");
7735     SDValue PSHUFBMask[16];
7736     for (int i = 0; i < 16; ++i) {
7737       int Idx = Offset + (i / Scale);
7738       PSHUFBMask[i] = DAG.getConstant(
7739           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7740     }
7741     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7742     return DAG.getBitcast(VT,
7743                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7744                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7745                                                   MVT::v16i8, PSHUFBMask)));
7746   }
7747
7748   // If we are extending from an offset, ensure we start on a boundary that
7749   // we can unpack from.
7750   int AlignToUnpack = Offset % (NumElements / Scale);
7751   if (AlignToUnpack) {
7752     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7753     for (int i = AlignToUnpack; i < NumElements; ++i)
7754       ShMask[i - AlignToUnpack] = i;
7755     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7756     Offset -= AlignToUnpack;
7757   }
7758
7759   // Otherwise emit a sequence of unpacks.
7760   do {
7761     unsigned UnpackLoHi = X86ISD::UNPCKL;
7762     if (Offset >= (NumElements / 2)) {
7763       UnpackLoHi = X86ISD::UNPCKH;
7764       Offset -= (NumElements / 2);
7765     }
7766
7767     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7768     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7769                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7770     InputV = DAG.getBitcast(InputVT, InputV);
7771     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7772     Scale /= 2;
7773     EltBits *= 2;
7774     NumElements /= 2;
7775   } while (Scale > 1);
7776   return DAG.getBitcast(VT, InputV);
7777 }
7778
7779 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7780 ///
7781 /// This routine will try to do everything in its power to cleverly lower
7782 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7783 /// check for the profitability of this lowering,  it tries to aggressively
7784 /// match this pattern. It will use all of the micro-architectural details it
7785 /// can to emit an efficient lowering. It handles both blends with all-zero
7786 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7787 /// masking out later).
7788 ///
7789 /// The reason we have dedicated lowering for zext-style shuffles is that they
7790 /// are both incredibly common and often quite performance sensitive.
7791 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7792     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7793     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7794   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7795
7796   int Bits = VT.getSizeInBits();
7797   int NumLanes = Bits / 128;
7798   int NumElements = VT.getVectorNumElements();
7799   int NumEltsPerLane = NumElements / NumLanes;
7800   assert(VT.getScalarSizeInBits() <= 32 &&
7801          "Exceeds 32-bit integer zero extension limit");
7802   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7803
7804   // Define a helper function to check a particular ext-scale and lower to it if
7805   // valid.
7806   auto Lower = [&](int Scale) -> SDValue {
7807     SDValue InputV;
7808     bool AnyExt = true;
7809     int Offset = 0;
7810     int Matches = 0;
7811     for (int i = 0; i < NumElements; ++i) {
7812       int M = Mask[i];
7813       if (M == -1)
7814         continue; // Valid anywhere but doesn't tell us anything.
7815       if (i % Scale != 0) {
7816         // Each of the extended elements need to be zeroable.
7817         if (!Zeroable[i])
7818           return SDValue();
7819
7820         // We no longer are in the anyext case.
7821         AnyExt = false;
7822         continue;
7823       }
7824
7825       // Each of the base elements needs to be consecutive indices into the
7826       // same input vector.
7827       SDValue V = M < NumElements ? V1 : V2;
7828       M = M % NumElements;
7829       if (!InputV) {
7830         InputV = V;
7831         Offset = M - (i / Scale);
7832       } else if (InputV != V)
7833         return SDValue(); // Flip-flopping inputs.
7834
7835       // Offset must start in the lowest 128-bit lane or at the start of an
7836       // upper lane.
7837       // FIXME: Is it ever worth allowing a negative base offset?
7838       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7839             (Offset % NumEltsPerLane) == 0))
7840         return SDValue();
7841
7842       // If we are offsetting, all referenced entries must come from the same
7843       // lane.
7844       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7845         return SDValue();
7846
7847       if ((M % NumElements) != (Offset + (i / Scale)))
7848         return SDValue(); // Non-consecutive strided elements.
7849       Matches++;
7850     }
7851
7852     // If we fail to find an input, we have a zero-shuffle which should always
7853     // have already been handled.
7854     // FIXME: Maybe handle this here in case during blending we end up with one?
7855     if (!InputV)
7856       return SDValue();
7857
7858     // If we are offsetting, don't extend if we only match a single input, we
7859     // can always do better by using a basic PSHUF or PUNPCK.
7860     if (Offset != 0 && Matches < 2)
7861       return SDValue();
7862
7863     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7864         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7865   };
7866
7867   // The widest scale possible for extending is to a 64-bit integer.
7868   assert(Bits % 64 == 0 &&
7869          "The number of bits in a vector must be divisible by 64 on x86!");
7870   int NumExtElements = Bits / 64;
7871
7872   // Each iteration, try extending the elements half as much, but into twice as
7873   // many elements.
7874   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7875     assert(NumElements % NumExtElements == 0 &&
7876            "The input vector size must be divisible by the extended size.");
7877     if (SDValue V = Lower(NumElements / NumExtElements))
7878       return V;
7879   }
7880
7881   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7882   if (Bits != 128)
7883     return SDValue();
7884
7885   // Returns one of the source operands if the shuffle can be reduced to a
7886   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7887   auto CanZExtLowHalf = [&]() {
7888     for (int i = NumElements / 2; i != NumElements; ++i)
7889       if (!Zeroable[i])
7890         return SDValue();
7891     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7892       return V1;
7893     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7894       return V2;
7895     return SDValue();
7896   };
7897
7898   if (SDValue V = CanZExtLowHalf()) {
7899     V = DAG.getBitcast(MVT::v2i64, V);
7900     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7901     return DAG.getBitcast(VT, V);
7902   }
7903
7904   // No viable ext lowering found.
7905   return SDValue();
7906 }
7907
7908 /// \brief Try to get a scalar value for a specific element of a vector.
7909 ///
7910 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7911 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7912                                               SelectionDAG &DAG) {
7913   MVT VT = V.getSimpleValueType();
7914   MVT EltVT = VT.getVectorElementType();
7915   while (V.getOpcode() == ISD::BITCAST)
7916     V = V.getOperand(0);
7917   // If the bitcasts shift the element size, we can't extract an equivalent
7918   // element from it.
7919   MVT NewVT = V.getSimpleValueType();
7920   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7921     return SDValue();
7922
7923   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7924       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7925     // Ensure the scalar operand is the same size as the destination.
7926     // FIXME: Add support for scalar truncation where possible.
7927     SDValue S = V.getOperand(Idx);
7928     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7929       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7930   }
7931
7932   return SDValue();
7933 }
7934
7935 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7936 ///
7937 /// This is particularly important because the set of instructions varies
7938 /// significantly based on whether the operand is a load or not.
7939 static bool isShuffleFoldableLoad(SDValue V) {
7940   while (V.getOpcode() == ISD::BITCAST)
7941     V = V.getOperand(0);
7942
7943   return ISD::isNON_EXTLoad(V.getNode());
7944 }
7945
7946 /// \brief Try to lower insertion of a single element into a zero vector.
7947 ///
7948 /// This is a common pattern that we have especially efficient patterns to lower
7949 /// across all subtarget feature sets.
7950 static SDValue lowerVectorShuffleAsElementInsertion(
7951     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7952     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7953   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7954   MVT ExtVT = VT;
7955   MVT EltVT = VT.getVectorElementType();
7956
7957   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7958                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7959                 Mask.begin();
7960   bool IsV1Zeroable = true;
7961   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7962     if (i != V2Index && !Zeroable[i]) {
7963       IsV1Zeroable = false;
7964       break;
7965     }
7966
7967   // Check for a single input from a SCALAR_TO_VECTOR node.
7968   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7969   // all the smarts here sunk into that routine. However, the current
7970   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7971   // vector shuffle lowering is dead.
7972   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7973                                                DAG);
7974   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7975     // We need to zext the scalar if it is smaller than an i32.
7976     V2S = DAG.getBitcast(EltVT, V2S);
7977     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7978       // Using zext to expand a narrow element won't work for non-zero
7979       // insertions.
7980       if (!IsV1Zeroable)
7981         return SDValue();
7982
7983       // Zero-extend directly to i32.
7984       ExtVT = MVT::v4i32;
7985       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7986     }
7987     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7988   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7989              EltVT == MVT::i16) {
7990     // Either not inserting from the low element of the input or the input
7991     // element size is too small to use VZEXT_MOVL to clear the high bits.
7992     return SDValue();
7993   }
7994
7995   if (!IsV1Zeroable) {
7996     // If V1 can't be treated as a zero vector we have fewer options to lower
7997     // this. We can't support integer vectors or non-zero targets cheaply, and
7998     // the V1 elements can't be permuted in any way.
7999     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8000     if (!VT.isFloatingPoint() || V2Index != 0)
8001       return SDValue();
8002     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8003     V1Mask[V2Index] = -1;
8004     if (!isNoopShuffleMask(V1Mask))
8005       return SDValue();
8006     // This is essentially a special case blend operation, but if we have
8007     // general purpose blend operations, they are always faster. Bail and let
8008     // the rest of the lowering handle these as blends.
8009     if (Subtarget->hasSSE41())
8010       return SDValue();
8011
8012     // Otherwise, use MOVSD or MOVSS.
8013     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8014            "Only two types of floating point element types to handle!");
8015     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8016                        ExtVT, V1, V2);
8017   }
8018
8019   // This lowering only works for the low element with floating point vectors.
8020   if (VT.isFloatingPoint() && V2Index != 0)
8021     return SDValue();
8022
8023   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8024   if (ExtVT != VT)
8025     V2 = DAG.getBitcast(VT, V2);
8026
8027   if (V2Index != 0) {
8028     // If we have 4 or fewer lanes we can cheaply shuffle the element into
8029     // the desired position. Otherwise it is more efficient to do a vector
8030     // shift left. We know that we can do a vector shift left because all
8031     // the inputs are zero.
8032     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8033       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8034       V2Shuffle[V2Index] = 0;
8035       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8036     } else {
8037       V2 = DAG.getBitcast(MVT::v2i64, V2);
8038       V2 = DAG.getNode(
8039           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8040           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8041                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8042                               DAG.getDataLayout(), VT)));
8043       V2 = DAG.getBitcast(VT, V2);
8044     }
8045   }
8046   return V2;
8047 }
8048
8049 /// \brief Try to lower broadcast of a single - truncated - integer element,
8050 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8051 ///
8052 /// This assumes we have AVX2.
8053 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8054                                                   int BroadcastIdx,
8055                                                   const X86Subtarget *Subtarget,
8056                                                   SelectionDAG &DAG) {
8057   assert(Subtarget->hasAVX2() &&
8058          "We can only lower integer broadcasts with AVX2!");
8059
8060   EVT EltVT = VT.getVectorElementType();
8061   EVT V0VT = V0.getValueType();
8062
8063   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8064   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8065
8066   EVT V0EltVT = V0VT.getVectorElementType();
8067   if (!V0EltVT.isInteger())
8068     return SDValue();
8069
8070   const unsigned EltSize = EltVT.getSizeInBits();
8071   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8072
8073   // This is only a truncation if the original element type is larger.
8074   if (V0EltSize <= EltSize)
8075     return SDValue();
8076
8077   assert(((V0EltSize % EltSize) == 0) &&
8078          "Scalar type sizes must all be powers of 2 on x86!");
8079
8080   const unsigned V0Opc = V0.getOpcode();
8081   const unsigned Scale = V0EltSize / EltSize;
8082   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8083
8084   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8085       V0Opc != ISD::BUILD_VECTOR)
8086     return SDValue();
8087
8088   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8089
8090   // If we're extracting non-least-significant bits, shift so we can truncate.
8091   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8092   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8093   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8094   if (const int OffsetIdx = BroadcastIdx % Scale)
8095     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8096             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8097
8098   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8099                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8100 }
8101
8102 /// \brief Try to lower broadcast of a single element.
8103 ///
8104 /// For convenience, this code also bundles all of the subtarget feature set
8105 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8106 /// a convenient way to factor it out.
8107 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8108 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8109                                              ArrayRef<int> Mask,
8110                                              const X86Subtarget *Subtarget,
8111                                              SelectionDAG &DAG) {
8112   if (!Subtarget->hasAVX())
8113     return SDValue();
8114   if (VT.isInteger() && !Subtarget->hasAVX2())
8115     return SDValue();
8116
8117   // Check that the mask is a broadcast.
8118   int BroadcastIdx = -1;
8119   for (int M : Mask)
8120     if (M >= 0 && BroadcastIdx == -1)
8121       BroadcastIdx = M;
8122     else if (M >= 0 && M != BroadcastIdx)
8123       return SDValue();
8124
8125   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8126                                             "a sorted mask where the broadcast "
8127                                             "comes from V1.");
8128
8129   // Go up the chain of (vector) values to find a scalar load that we can
8130   // combine with the broadcast.
8131   for (;;) {
8132     switch (V.getOpcode()) {
8133     case ISD::CONCAT_VECTORS: {
8134       int OperandSize = Mask.size() / V.getNumOperands();
8135       V = V.getOperand(BroadcastIdx / OperandSize);
8136       BroadcastIdx %= OperandSize;
8137       continue;
8138     }
8139
8140     case ISD::INSERT_SUBVECTOR: {
8141       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8142       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8143       if (!ConstantIdx)
8144         break;
8145
8146       int BeginIdx = (int)ConstantIdx->getZExtValue();
8147       int EndIdx =
8148           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8149       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8150         BroadcastIdx -= BeginIdx;
8151         V = VInner;
8152       } else {
8153         V = VOuter;
8154       }
8155       continue;
8156     }
8157     }
8158     break;
8159   }
8160
8161   // Check if this is a broadcast of a scalar. We special case lowering
8162   // for scalars so that we can more effectively fold with loads.
8163   // First, look through bitcast: if the original value has a larger element
8164   // type than the shuffle, the broadcast element is in essence truncated.
8165   // Make that explicit to ease folding.
8166   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8167     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8168             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8169       return TruncBroadcast;
8170
8171   // Also check the simpler case, where we can directly reuse the scalar.
8172   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8173       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8174     V = V.getOperand(BroadcastIdx);
8175
8176     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8177     // Only AVX2 has register broadcasts.
8178     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8179       return SDValue();
8180   } else if (MayFoldLoad(V) && !cast<LoadSDNode>(V)->isVolatile()) {
8181     // If we are broadcasting a load that is only used by the shuffle
8182     // then we can reduce the vector load to the broadcasted scalar load.
8183     LoadSDNode *Ld = cast<LoadSDNode>(V);
8184     SDValue BaseAddr = Ld->getOperand(1);
8185     EVT AddrVT = BaseAddr.getValueType();
8186     EVT SVT = VT.getScalarType();
8187     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8188     SDValue NewAddr = DAG.getNode(
8189         ISD::ADD, DL, AddrVT, BaseAddr,
8190         DAG.getConstant(Offset, DL, AddrVT));
8191     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8192                     DAG.getMachineFunction().getMachineMemOperand(
8193                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8194   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8195     // We can't broadcast from a vector register without AVX2, and we can only
8196     // broadcast from the zero-element of a vector register.
8197     return SDValue();
8198   }
8199
8200   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8201 }
8202
8203 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8204 // INSERTPS when the V1 elements are already in the correct locations
8205 // because otherwise we can just always use two SHUFPS instructions which
8206 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8207 // perform INSERTPS if a single V1 element is out of place and all V2
8208 // elements are zeroable.
8209 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8210                                             ArrayRef<int> Mask,
8211                                             SelectionDAG &DAG) {
8212   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8213   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8214   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8215   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8216
8217   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8218
8219   unsigned ZMask = 0;
8220   int V1DstIndex = -1;
8221   int V2DstIndex = -1;
8222   bool V1UsedInPlace = false;
8223
8224   for (int i = 0; i < 4; ++i) {
8225     // Synthesize a zero mask from the zeroable elements (includes undefs).
8226     if (Zeroable[i]) {
8227       ZMask |= 1 << i;
8228       continue;
8229     }
8230
8231     // Flag if we use any V1 inputs in place.
8232     if (i == Mask[i]) {
8233       V1UsedInPlace = true;
8234       continue;
8235     }
8236
8237     // We can only insert a single non-zeroable element.
8238     if (V1DstIndex != -1 || V2DstIndex != -1)
8239       return SDValue();
8240
8241     if (Mask[i] < 4) {
8242       // V1 input out of place for insertion.
8243       V1DstIndex = i;
8244     } else {
8245       // V2 input for insertion.
8246       V2DstIndex = i;
8247     }
8248   }
8249
8250   // Don't bother if we have no (non-zeroable) element for insertion.
8251   if (V1DstIndex == -1 && V2DstIndex == -1)
8252     return SDValue();
8253
8254   // Determine element insertion src/dst indices. The src index is from the
8255   // start of the inserted vector, not the start of the concatenated vector.
8256   unsigned V2SrcIndex = 0;
8257   if (V1DstIndex != -1) {
8258     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8259     // and don't use the original V2 at all.
8260     V2SrcIndex = Mask[V1DstIndex];
8261     V2DstIndex = V1DstIndex;
8262     V2 = V1;
8263   } else {
8264     V2SrcIndex = Mask[V2DstIndex] - 4;
8265   }
8266
8267   // If no V1 inputs are used in place, then the result is created only from
8268   // the zero mask and the V2 insertion - so remove V1 dependency.
8269   if (!V1UsedInPlace)
8270     V1 = DAG.getUNDEF(MVT::v4f32);
8271
8272   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8273   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8274
8275   // Insert the V2 element into the desired position.
8276   SDLoc DL(Op);
8277   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8278                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8279 }
8280
8281 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8282 /// UNPCK instruction.
8283 ///
8284 /// This specifically targets cases where we end up with alternating between
8285 /// the two inputs, and so can permute them into something that feeds a single
8286 /// UNPCK instruction. Note that this routine only targets integer vectors
8287 /// because for floating point vectors we have a generalized SHUFPS lowering
8288 /// strategy that handles everything that doesn't *exactly* match an unpack,
8289 /// making this clever lowering unnecessary.
8290 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8291                                                     SDValue V1, SDValue V2,
8292                                                     ArrayRef<int> Mask,
8293                                                     SelectionDAG &DAG) {
8294   assert(!VT.isFloatingPoint() &&
8295          "This routine only supports integer vectors.");
8296   assert(!isSingleInputShuffleMask(Mask) &&
8297          "This routine should only be used when blending two inputs.");
8298   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8299
8300   int Size = Mask.size();
8301
8302   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8303     return M >= 0 && M % Size < Size / 2;
8304   });
8305   int NumHiInputs = std::count_if(
8306       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8307
8308   bool UnpackLo = NumLoInputs >= NumHiInputs;
8309
8310   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8311     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8312     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8313
8314     for (int i = 0; i < Size; ++i) {
8315       if (Mask[i] < 0)
8316         continue;
8317
8318       // Each element of the unpack contains Scale elements from this mask.
8319       int UnpackIdx = i / Scale;
8320
8321       // We only handle the case where V1 feeds the first slots of the unpack.
8322       // We rely on canonicalization to ensure this is the case.
8323       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8324         return SDValue();
8325
8326       // Setup the mask for this input. The indexing is tricky as we have to
8327       // handle the unpack stride.
8328       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8329       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8330           Mask[i] % Size;
8331     }
8332
8333     // If we will have to shuffle both inputs to use the unpack, check whether
8334     // we can just unpack first and shuffle the result. If so, skip this unpack.
8335     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8336         !isNoopShuffleMask(V2Mask))
8337       return SDValue();
8338
8339     // Shuffle the inputs into place.
8340     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8341     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8342
8343     // Cast the inputs to the type we will use to unpack them.
8344     V1 = DAG.getBitcast(UnpackVT, V1);
8345     V2 = DAG.getBitcast(UnpackVT, V2);
8346
8347     // Unpack the inputs and cast the result back to the desired type.
8348     return DAG.getBitcast(
8349         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8350                         UnpackVT, V1, V2));
8351   };
8352
8353   // We try each unpack from the largest to the smallest to try and find one
8354   // that fits this mask.
8355   int OrigNumElements = VT.getVectorNumElements();
8356   int OrigScalarSize = VT.getScalarSizeInBits();
8357   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8358     int Scale = ScalarSize / OrigScalarSize;
8359     int NumElements = OrigNumElements / Scale;
8360     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8361     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8362       return Unpack;
8363   }
8364
8365   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8366   // initial unpack.
8367   if (NumLoInputs == 0 || NumHiInputs == 0) {
8368     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8369            "We have to have *some* inputs!");
8370     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8371
8372     // FIXME: We could consider the total complexity of the permute of each
8373     // possible unpacking. Or at the least we should consider how many
8374     // half-crossings are created.
8375     // FIXME: We could consider commuting the unpacks.
8376
8377     SmallVector<int, 32> PermMask;
8378     PermMask.assign(Size, -1);
8379     for (int i = 0; i < Size; ++i) {
8380       if (Mask[i] < 0)
8381         continue;
8382
8383       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8384
8385       PermMask[i] =
8386           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8387     }
8388     return DAG.getVectorShuffle(
8389         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8390                             DL, VT, V1, V2),
8391         DAG.getUNDEF(VT), PermMask);
8392   }
8393
8394   return SDValue();
8395 }
8396
8397 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8398 ///
8399 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8400 /// support for floating point shuffles but not integer shuffles. These
8401 /// instructions will incur a domain crossing penalty on some chips though so
8402 /// it is better to avoid lowering through this for integer vectors where
8403 /// possible.
8404 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8405                                        const X86Subtarget *Subtarget,
8406                                        SelectionDAG &DAG) {
8407   SDLoc DL(Op);
8408   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8409   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8410   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8411   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8412   ArrayRef<int> Mask = SVOp->getMask();
8413   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8414
8415   if (isSingleInputShuffleMask(Mask)) {
8416     // Use low duplicate instructions for masks that match their pattern.
8417     if (Subtarget->hasSSE3())
8418       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8419         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8420
8421     // Straight shuffle of a single input vector. Simulate this by using the
8422     // single input as both of the "inputs" to this instruction..
8423     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8424
8425     if (Subtarget->hasAVX()) {
8426       // If we have AVX, we can use VPERMILPS which will allow folding a load
8427       // into the shuffle.
8428       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8429                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8430     }
8431
8432     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8433                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8434   }
8435   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8436   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8437
8438   // If we have a single input, insert that into V1 if we can do so cheaply.
8439   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8440     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8441             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8442       return Insertion;
8443     // Try inverting the insertion since for v2 masks it is easy to do and we
8444     // can't reliably sort the mask one way or the other.
8445     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8446                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8447     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8448             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8449       return Insertion;
8450   }
8451
8452   // Try to use one of the special instruction patterns to handle two common
8453   // blend patterns if a zero-blend above didn't work.
8454   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8455       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8456     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8457       // We can either use a special instruction to load over the low double or
8458       // to move just the low double.
8459       return DAG.getNode(
8460           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8461           DL, MVT::v2f64, V2,
8462           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8463
8464   if (Subtarget->hasSSE41())
8465     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8466                                                   Subtarget, DAG))
8467       return Blend;
8468
8469   // Use dedicated unpack instructions for masks that match their pattern.
8470   if (SDValue V =
8471           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8472     return V;
8473
8474   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8475   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8476                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8477 }
8478
8479 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8480 ///
8481 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8482 /// the integer unit to minimize domain crossing penalties. However, for blends
8483 /// it falls back to the floating point shuffle operation with appropriate bit
8484 /// casting.
8485 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8486                                        const X86Subtarget *Subtarget,
8487                                        SelectionDAG &DAG) {
8488   SDLoc DL(Op);
8489   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8490   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8491   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8492   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8493   ArrayRef<int> Mask = SVOp->getMask();
8494   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8495
8496   if (isSingleInputShuffleMask(Mask)) {
8497     // Check for being able to broadcast a single element.
8498     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8499                                                           Mask, Subtarget, DAG))
8500       return Broadcast;
8501
8502     // Straight shuffle of a single input vector. For everything from SSE2
8503     // onward this has a single fast instruction with no scary immediates.
8504     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8505     V1 = DAG.getBitcast(MVT::v4i32, V1);
8506     int WidenedMask[4] = {
8507         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8508         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8509     return DAG.getBitcast(
8510         MVT::v2i64,
8511         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8512                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8513   }
8514   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8515   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8516   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8517   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8518
8519   // If we have a blend of two PACKUS operations an the blend aligns with the
8520   // low and half halves, we can just merge the PACKUS operations. This is
8521   // particularly important as it lets us merge shuffles that this routine itself
8522   // creates.
8523   auto GetPackNode = [](SDValue V) {
8524     while (V.getOpcode() == ISD::BITCAST)
8525       V = V.getOperand(0);
8526
8527     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8528   };
8529   if (SDValue V1Pack = GetPackNode(V1))
8530     if (SDValue V2Pack = GetPackNode(V2))
8531       return DAG.getBitcast(MVT::v2i64,
8532                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8533                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8534                                                      : V1Pack.getOperand(1),
8535                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8536                                                      : V2Pack.getOperand(1)));
8537
8538   // Try to use shift instructions.
8539   if (SDValue Shift =
8540           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8541     return Shift;
8542
8543   // When loading a scalar and then shuffling it into a vector we can often do
8544   // the insertion cheaply.
8545   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8546           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8547     return Insertion;
8548   // Try inverting the insertion since for v2 masks it is easy to do and we
8549   // can't reliably sort the mask one way or the other.
8550   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8551   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8552           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8553     return Insertion;
8554
8555   // We have different paths for blend lowering, but they all must use the
8556   // *exact* same predicate.
8557   bool IsBlendSupported = Subtarget->hasSSE41();
8558   if (IsBlendSupported)
8559     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8560                                                   Subtarget, DAG))
8561       return Blend;
8562
8563   // Use dedicated unpack instructions for masks that match their pattern.
8564   if (SDValue V =
8565           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8566     return V;
8567
8568   // Try to use byte rotation instructions.
8569   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8570   if (Subtarget->hasSSSE3())
8571     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8572             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8573       return Rotate;
8574
8575   // If we have direct support for blends, we should lower by decomposing into
8576   // a permute. That will be faster than the domain cross.
8577   if (IsBlendSupported)
8578     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8579                                                       Mask, DAG);
8580
8581   // We implement this with SHUFPD which is pretty lame because it will likely
8582   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8583   // However, all the alternatives are still more cycles and newer chips don't
8584   // have this problem. It would be really nice if x86 had better shuffles here.
8585   V1 = DAG.getBitcast(MVT::v2f64, V1);
8586   V2 = DAG.getBitcast(MVT::v2f64, V2);
8587   return DAG.getBitcast(MVT::v2i64,
8588                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8589 }
8590
8591 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8592 ///
8593 /// This is used to disable more specialized lowerings when the shufps lowering
8594 /// will happen to be efficient.
8595 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8596   // This routine only handles 128-bit shufps.
8597   assert(Mask.size() == 4 && "Unsupported mask size!");
8598
8599   // To lower with a single SHUFPS we need to have the low half and high half
8600   // each requiring a single input.
8601   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8602     return false;
8603   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8604     return false;
8605
8606   return true;
8607 }
8608
8609 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8610 ///
8611 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8612 /// It makes no assumptions about whether this is the *best* lowering, it simply
8613 /// uses it.
8614 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8615                                             ArrayRef<int> Mask, SDValue V1,
8616                                             SDValue V2, SelectionDAG &DAG) {
8617   SDValue LowV = V1, HighV = V2;
8618   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8619
8620   int NumV2Elements =
8621       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8622
8623   if (NumV2Elements == 1) {
8624     int V2Index =
8625         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8626         Mask.begin();
8627
8628     // Compute the index adjacent to V2Index and in the same half by toggling
8629     // the low bit.
8630     int V2AdjIndex = V2Index ^ 1;
8631
8632     if (Mask[V2AdjIndex] == -1) {
8633       // Handles all the cases where we have a single V2 element and an undef.
8634       // This will only ever happen in the high lanes because we commute the
8635       // vector otherwise.
8636       if (V2Index < 2)
8637         std::swap(LowV, HighV);
8638       NewMask[V2Index] -= 4;
8639     } else {
8640       // Handle the case where the V2 element ends up adjacent to a V1 element.
8641       // To make this work, blend them together as the first step.
8642       int V1Index = V2AdjIndex;
8643       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8644       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8645                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8646
8647       // Now proceed to reconstruct the final blend as we have the necessary
8648       // high or low half formed.
8649       if (V2Index < 2) {
8650         LowV = V2;
8651         HighV = V1;
8652       } else {
8653         HighV = V2;
8654       }
8655       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8656       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8657     }
8658   } else if (NumV2Elements == 2) {
8659     if (Mask[0] < 4 && Mask[1] < 4) {
8660       // Handle the easy case where we have V1 in the low lanes and V2 in the
8661       // high lanes.
8662       NewMask[2] -= 4;
8663       NewMask[3] -= 4;
8664     } else if (Mask[2] < 4 && Mask[3] < 4) {
8665       // We also handle the reversed case because this utility may get called
8666       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8667       // arrange things in the right direction.
8668       NewMask[0] -= 4;
8669       NewMask[1] -= 4;
8670       HighV = V1;
8671       LowV = V2;
8672     } else {
8673       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8674       // trying to place elements directly, just blend them and set up the final
8675       // shuffle to place them.
8676
8677       // The first two blend mask elements are for V1, the second two are for
8678       // V2.
8679       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8680                           Mask[2] < 4 ? Mask[2] : Mask[3],
8681                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8682                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8683       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8684                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8685
8686       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8687       // a blend.
8688       LowV = HighV = V1;
8689       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8690       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8691       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8692       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8693     }
8694   }
8695   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8696                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8697 }
8698
8699 /// \brief Lower 4-lane 32-bit floating point shuffles.
8700 ///
8701 /// Uses instructions exclusively from the floating point unit to minimize
8702 /// domain crossing penalties, as these are sufficient to implement all v4f32
8703 /// shuffles.
8704 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8705                                        const X86Subtarget *Subtarget,
8706                                        SelectionDAG &DAG) {
8707   SDLoc DL(Op);
8708   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8709   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8710   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8711   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8712   ArrayRef<int> Mask = SVOp->getMask();
8713   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8714
8715   int NumV2Elements =
8716       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8717
8718   if (NumV2Elements == 0) {
8719     // Check for being able to broadcast a single element.
8720     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8721                                                           Mask, Subtarget, DAG))
8722       return Broadcast;
8723
8724     // Use even/odd duplicate instructions for masks that match their pattern.
8725     if (Subtarget->hasSSE3()) {
8726       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8727         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8728       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8729         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8730     }
8731
8732     if (Subtarget->hasAVX()) {
8733       // If we have AVX, we can use VPERMILPS which will allow folding a load
8734       // into the shuffle.
8735       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8736                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8737     }
8738
8739     // Otherwise, use a straight shuffle of a single input vector. We pass the
8740     // input vector to both operands to simulate this with a SHUFPS.
8741     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8742                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8743   }
8744
8745   // There are special ways we can lower some single-element blends. However, we
8746   // have custom ways we can lower more complex single-element blends below that
8747   // we defer to if both this and BLENDPS fail to match, so restrict this to
8748   // when the V2 input is targeting element 0 of the mask -- that is the fast
8749   // case here.
8750   if (NumV2Elements == 1 && Mask[0] >= 4)
8751     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8752                                                          Mask, Subtarget, DAG))
8753       return V;
8754
8755   if (Subtarget->hasSSE41()) {
8756     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8757                                                   Subtarget, DAG))
8758       return Blend;
8759
8760     // Use INSERTPS if we can complete the shuffle efficiently.
8761     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8762       return V;
8763
8764     if (!isSingleSHUFPSMask(Mask))
8765       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8766               DL, MVT::v4f32, V1, V2, Mask, DAG))
8767         return BlendPerm;
8768   }
8769
8770   // Use dedicated unpack instructions for masks that match their pattern.
8771   if (SDValue V =
8772           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8773     return V;
8774
8775   // Otherwise fall back to a SHUFPS lowering strategy.
8776   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8777 }
8778
8779 /// \brief Lower 4-lane i32 vector shuffles.
8780 ///
8781 /// We try to handle these with integer-domain shuffles where we can, but for
8782 /// blends we use the floating point domain blend instructions.
8783 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8784                                        const X86Subtarget *Subtarget,
8785                                        SelectionDAG &DAG) {
8786   SDLoc DL(Op);
8787   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8788   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8789   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8790   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8791   ArrayRef<int> Mask = SVOp->getMask();
8792   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8793
8794   // Whenever we can lower this as a zext, that instruction is strictly faster
8795   // than any alternative. It also allows us to fold memory operands into the
8796   // shuffle in many cases.
8797   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8798                                                          Mask, Subtarget, DAG))
8799     return ZExt;
8800
8801   int NumV2Elements =
8802       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8803
8804   if (NumV2Elements == 0) {
8805     // Check for being able to broadcast a single element.
8806     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8807                                                           Mask, Subtarget, DAG))
8808       return Broadcast;
8809
8810     // Straight shuffle of a single input vector. For everything from SSE2
8811     // onward this has a single fast instruction with no scary immediates.
8812     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8813     // but we aren't actually going to use the UNPCK instruction because doing
8814     // so prevents folding a load into this instruction or making a copy.
8815     const int UnpackLoMask[] = {0, 0, 1, 1};
8816     const int UnpackHiMask[] = {2, 2, 3, 3};
8817     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8818       Mask = UnpackLoMask;
8819     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8820       Mask = UnpackHiMask;
8821
8822     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8823                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8824   }
8825
8826   // Try to use shift instructions.
8827   if (SDValue Shift =
8828           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8829     return Shift;
8830
8831   // There are special ways we can lower some single-element blends.
8832   if (NumV2Elements == 1)
8833     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8834                                                          Mask, Subtarget, DAG))
8835       return V;
8836
8837   // We have different paths for blend lowering, but they all must use the
8838   // *exact* same predicate.
8839   bool IsBlendSupported = Subtarget->hasSSE41();
8840   if (IsBlendSupported)
8841     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8842                                                   Subtarget, DAG))
8843       return Blend;
8844
8845   if (SDValue Masked =
8846           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8847     return Masked;
8848
8849   // Use dedicated unpack instructions for masks that match their pattern.
8850   if (SDValue V =
8851           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8852     return V;
8853
8854   // Try to use byte rotation instructions.
8855   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8856   if (Subtarget->hasSSSE3())
8857     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8858             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8859       return Rotate;
8860
8861   // If we have direct support for blends, we should lower by decomposing into
8862   // a permute. That will be faster than the domain cross.
8863   if (IsBlendSupported)
8864     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8865                                                       Mask, DAG);
8866
8867   // Try to lower by permuting the inputs into an unpack instruction.
8868   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8869                                                             V2, Mask, DAG))
8870     return Unpack;
8871
8872   // We implement this with SHUFPS because it can blend from two vectors.
8873   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8874   // up the inputs, bypassing domain shift penalties that we would encur if we
8875   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8876   // relevant.
8877   return DAG.getBitcast(
8878       MVT::v4i32,
8879       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8880                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8881 }
8882
8883 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8884 /// shuffle lowering, and the most complex part.
8885 ///
8886 /// The lowering strategy is to try to form pairs of input lanes which are
8887 /// targeted at the same half of the final vector, and then use a dword shuffle
8888 /// to place them onto the right half, and finally unpack the paired lanes into
8889 /// their final position.
8890 ///
8891 /// The exact breakdown of how to form these dword pairs and align them on the
8892 /// correct sides is really tricky. See the comments within the function for
8893 /// more of the details.
8894 ///
8895 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8896 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8897 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8898 /// vector, form the analogous 128-bit 8-element Mask.
8899 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8900     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8901     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8902   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8903   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8904
8905   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8906   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8907   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8908
8909   SmallVector<int, 4> LoInputs;
8910   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8911                [](int M) { return M >= 0; });
8912   std::sort(LoInputs.begin(), LoInputs.end());
8913   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8914   SmallVector<int, 4> HiInputs;
8915   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8916                [](int M) { return M >= 0; });
8917   std::sort(HiInputs.begin(), HiInputs.end());
8918   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8919   int NumLToL =
8920       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8921   int NumHToL = LoInputs.size() - NumLToL;
8922   int NumLToH =
8923       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8924   int NumHToH = HiInputs.size() - NumLToH;
8925   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8926   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8927   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8928   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8929
8930   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8931   // such inputs we can swap two of the dwords across the half mark and end up
8932   // with <=2 inputs to each half in each half. Once there, we can fall through
8933   // to the generic code below. For example:
8934   //
8935   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8936   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8937   //
8938   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8939   // and an existing 2-into-2 on the other half. In this case we may have to
8940   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8941   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8942   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8943   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8944   // half than the one we target for fixing) will be fixed when we re-enter this
8945   // path. We will also combine away any sequence of PSHUFD instructions that
8946   // result into a single instruction. Here is an example of the tricky case:
8947   //
8948   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8949   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8950   //
8951   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8952   //
8953   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8954   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8955   //
8956   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8957   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8958   //
8959   // The result is fine to be handled by the generic logic.
8960   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8961                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8962                           int AOffset, int BOffset) {
8963     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8964            "Must call this with A having 3 or 1 inputs from the A half.");
8965     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8966            "Must call this with B having 1 or 3 inputs from the B half.");
8967     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8968            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8969
8970     bool ThreeAInputs = AToAInputs.size() == 3;
8971
8972     // Compute the index of dword with only one word among the three inputs in
8973     // a half by taking the sum of the half with three inputs and subtracting
8974     // the sum of the actual three inputs. The difference is the remaining
8975     // slot.
8976     int ADWord, BDWord;
8977     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8978     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8979     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8980     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8981     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8982     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8983     int TripleNonInputIdx =
8984         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8985     TripleDWord = TripleNonInputIdx / 2;
8986
8987     // We use xor with one to compute the adjacent DWord to whichever one the
8988     // OneInput is in.
8989     OneInputDWord = (OneInput / 2) ^ 1;
8990
8991     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8992     // and BToA inputs. If there is also such a problem with the BToB and AToB
8993     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8994     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8995     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8996     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8997       // Compute how many inputs will be flipped by swapping these DWords. We
8998       // need
8999       // to balance this to ensure we don't form a 3-1 shuffle in the other
9000       // half.
9001       int NumFlippedAToBInputs =
9002           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9003           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9004       int NumFlippedBToBInputs =
9005           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9006           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9007       if ((NumFlippedAToBInputs == 1 &&
9008            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9009           (NumFlippedBToBInputs == 1 &&
9010            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9011         // We choose whether to fix the A half or B half based on whether that
9012         // half has zero flipped inputs. At zero, we may not be able to fix it
9013         // with that half. We also bias towards fixing the B half because that
9014         // will more commonly be the high half, and we have to bias one way.
9015         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9016                                                        ArrayRef<int> Inputs) {
9017           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9018           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9019                                          PinnedIdx ^ 1) != Inputs.end();
9020           // Determine whether the free index is in the flipped dword or the
9021           // unflipped dword based on where the pinned index is. We use this bit
9022           // in an xor to conditionally select the adjacent dword.
9023           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9024           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9025                                              FixFreeIdx) != Inputs.end();
9026           if (IsFixIdxInput == IsFixFreeIdxInput)
9027             FixFreeIdx += 1;
9028           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9029                                         FixFreeIdx) != Inputs.end();
9030           assert(IsFixIdxInput != IsFixFreeIdxInput &&
9031                  "We need to be changing the number of flipped inputs!");
9032           int PSHUFHalfMask[] = {0, 1, 2, 3};
9033           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9034           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9035                           MVT::v8i16, V,
9036                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9037
9038           for (int &M : Mask)
9039             if (M != -1 && M == FixIdx)
9040               M = FixFreeIdx;
9041             else if (M != -1 && M == FixFreeIdx)
9042               M = FixIdx;
9043         };
9044         if (NumFlippedBToBInputs != 0) {
9045           int BPinnedIdx =
9046               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9047           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9048         } else {
9049           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9050           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9051           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9052         }
9053       }
9054     }
9055
9056     int PSHUFDMask[] = {0, 1, 2, 3};
9057     PSHUFDMask[ADWord] = BDWord;
9058     PSHUFDMask[BDWord] = ADWord;
9059     V = DAG.getBitcast(
9060         VT,
9061         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9062                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9063
9064     // Adjust the mask to match the new locations of A and B.
9065     for (int &M : Mask)
9066       if (M != -1 && M/2 == ADWord)
9067         M = 2 * BDWord + M % 2;
9068       else if (M != -1 && M/2 == BDWord)
9069         M = 2 * ADWord + M % 2;
9070
9071     // Recurse back into this routine to re-compute state now that this isn't
9072     // a 3 and 1 problem.
9073     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9074                                                      DAG);
9075   };
9076   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9077     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9078   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9079     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9080
9081   // At this point there are at most two inputs to the low and high halves from
9082   // each half. That means the inputs can always be grouped into dwords and
9083   // those dwords can then be moved to the correct half with a dword shuffle.
9084   // We use at most one low and one high word shuffle to collect these paired
9085   // inputs into dwords, and finally a dword shuffle to place them.
9086   int PSHUFLMask[4] = {-1, -1, -1, -1};
9087   int PSHUFHMask[4] = {-1, -1, -1, -1};
9088   int PSHUFDMask[4] = {-1, -1, -1, -1};
9089
9090   // First fix the masks for all the inputs that are staying in their
9091   // original halves. This will then dictate the targets of the cross-half
9092   // shuffles.
9093   auto fixInPlaceInputs =
9094       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9095                     MutableArrayRef<int> SourceHalfMask,
9096                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9097     if (InPlaceInputs.empty())
9098       return;
9099     if (InPlaceInputs.size() == 1) {
9100       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9101           InPlaceInputs[0] - HalfOffset;
9102       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9103       return;
9104     }
9105     if (IncomingInputs.empty()) {
9106       // Just fix all of the in place inputs.
9107       for (int Input : InPlaceInputs) {
9108         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9109         PSHUFDMask[Input / 2] = Input / 2;
9110       }
9111       return;
9112     }
9113
9114     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9115     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9116         InPlaceInputs[0] - HalfOffset;
9117     // Put the second input next to the first so that they are packed into
9118     // a dword. We find the adjacent index by toggling the low bit.
9119     int AdjIndex = InPlaceInputs[0] ^ 1;
9120     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9121     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9122     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9123   };
9124   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9125   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9126
9127   // Now gather the cross-half inputs and place them into a free dword of
9128   // their target half.
9129   // FIXME: This operation could almost certainly be simplified dramatically to
9130   // look more like the 3-1 fixing operation.
9131   auto moveInputsToRightHalf = [&PSHUFDMask](
9132       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9133       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9134       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9135       int DestOffset) {
9136     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9137       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9138     };
9139     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9140                                                int Word) {
9141       int LowWord = Word & ~1;
9142       int HighWord = Word | 1;
9143       return isWordClobbered(SourceHalfMask, LowWord) ||
9144              isWordClobbered(SourceHalfMask, HighWord);
9145     };
9146
9147     if (IncomingInputs.empty())
9148       return;
9149
9150     if (ExistingInputs.empty()) {
9151       // Map any dwords with inputs from them into the right half.
9152       for (int Input : IncomingInputs) {
9153         // If the source half mask maps over the inputs, turn those into
9154         // swaps and use the swapped lane.
9155         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9156           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9157             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9158                 Input - SourceOffset;
9159             // We have to swap the uses in our half mask in one sweep.
9160             for (int &M : HalfMask)
9161               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9162                 M = Input;
9163               else if (M == Input)
9164                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9165           } else {
9166             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9167                        Input - SourceOffset &&
9168                    "Previous placement doesn't match!");
9169           }
9170           // Note that this correctly re-maps both when we do a swap and when
9171           // we observe the other side of the swap above. We rely on that to
9172           // avoid swapping the members of the input list directly.
9173           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9174         }
9175
9176         // Map the input's dword into the correct half.
9177         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9178           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9179         else
9180           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9181                      Input / 2 &&
9182                  "Previous placement doesn't match!");
9183       }
9184
9185       // And just directly shift any other-half mask elements to be same-half
9186       // as we will have mirrored the dword containing the element into the
9187       // same position within that half.
9188       for (int &M : HalfMask)
9189         if (M >= SourceOffset && M < SourceOffset + 4) {
9190           M = M - SourceOffset + DestOffset;
9191           assert(M >= 0 && "This should never wrap below zero!");
9192         }
9193       return;
9194     }
9195
9196     // Ensure we have the input in a viable dword of its current half. This
9197     // is particularly tricky because the original position may be clobbered
9198     // by inputs being moved and *staying* in that half.
9199     if (IncomingInputs.size() == 1) {
9200       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9201         int InputFixed = std::find(std::begin(SourceHalfMask),
9202                                    std::end(SourceHalfMask), -1) -
9203                          std::begin(SourceHalfMask) + SourceOffset;
9204         SourceHalfMask[InputFixed - SourceOffset] =
9205             IncomingInputs[0] - SourceOffset;
9206         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9207                      InputFixed);
9208         IncomingInputs[0] = InputFixed;
9209       }
9210     } else if (IncomingInputs.size() == 2) {
9211       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9212           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9213         // We have two non-adjacent or clobbered inputs we need to extract from
9214         // the source half. To do this, we need to map them into some adjacent
9215         // dword slot in the source mask.
9216         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9217                               IncomingInputs[1] - SourceOffset};
9218
9219         // If there is a free slot in the source half mask adjacent to one of
9220         // the inputs, place the other input in it. We use (Index XOR 1) to
9221         // compute an adjacent index.
9222         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9223             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9224           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9225           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9226           InputsFixed[1] = InputsFixed[0] ^ 1;
9227         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9228                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9229           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9230           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9231           InputsFixed[0] = InputsFixed[1] ^ 1;
9232         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9233                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9234           // The two inputs are in the same DWord but it is clobbered and the
9235           // adjacent DWord isn't used at all. Move both inputs to the free
9236           // slot.
9237           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9238           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9239           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9240           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9241         } else {
9242           // The only way we hit this point is if there is no clobbering
9243           // (because there are no off-half inputs to this half) and there is no
9244           // free slot adjacent to one of the inputs. In this case, we have to
9245           // swap an input with a non-input.
9246           for (int i = 0; i < 4; ++i)
9247             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9248                    "We can't handle any clobbers here!");
9249           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9250                  "Cannot have adjacent inputs here!");
9251
9252           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9253           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9254
9255           // We also have to update the final source mask in this case because
9256           // it may need to undo the above swap.
9257           for (int &M : FinalSourceHalfMask)
9258             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9259               M = InputsFixed[1] + SourceOffset;
9260             else if (M == InputsFixed[1] + SourceOffset)
9261               M = (InputsFixed[0] ^ 1) + SourceOffset;
9262
9263           InputsFixed[1] = InputsFixed[0] ^ 1;
9264         }
9265
9266         // Point everything at the fixed inputs.
9267         for (int &M : HalfMask)
9268           if (M == IncomingInputs[0])
9269             M = InputsFixed[0] + SourceOffset;
9270           else if (M == IncomingInputs[1])
9271             M = InputsFixed[1] + SourceOffset;
9272
9273         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9274         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9275       }
9276     } else {
9277       llvm_unreachable("Unhandled input size!");
9278     }
9279
9280     // Now hoist the DWord down to the right half.
9281     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9282     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9283     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9284     for (int &M : HalfMask)
9285       for (int Input : IncomingInputs)
9286         if (M == Input)
9287           M = FreeDWord * 2 + Input % 2;
9288   };
9289   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9290                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9291   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9292                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9293
9294   // Now enact all the shuffles we've computed to move the inputs into their
9295   // target half.
9296   if (!isNoopShuffleMask(PSHUFLMask))
9297     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9298                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9299   if (!isNoopShuffleMask(PSHUFHMask))
9300     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9301                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9302   if (!isNoopShuffleMask(PSHUFDMask))
9303     V = DAG.getBitcast(
9304         VT,
9305         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9306                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9307
9308   // At this point, each half should contain all its inputs, and we can then
9309   // just shuffle them into their final position.
9310   assert(std::count_if(LoMask.begin(), LoMask.end(),
9311                        [](int M) { return M >= 4; }) == 0 &&
9312          "Failed to lift all the high half inputs to the low mask!");
9313   assert(std::count_if(HiMask.begin(), HiMask.end(),
9314                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9315          "Failed to lift all the low half inputs to the high mask!");
9316
9317   // Do a half shuffle for the low mask.
9318   if (!isNoopShuffleMask(LoMask))
9319     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9320                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9321
9322   // Do a half shuffle with the high mask after shifting its values down.
9323   for (int &M : HiMask)
9324     if (M >= 0)
9325       M -= 4;
9326   if (!isNoopShuffleMask(HiMask))
9327     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9328                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9329
9330   return V;
9331 }
9332
9333 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9334 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9335                                           SDValue V2, ArrayRef<int> Mask,
9336                                           SelectionDAG &DAG, bool &V1InUse,
9337                                           bool &V2InUse) {
9338   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9339   SDValue V1Mask[16];
9340   SDValue V2Mask[16];
9341   V1InUse = false;
9342   V2InUse = false;
9343
9344   int Size = Mask.size();
9345   int Scale = 16 / Size;
9346   for (int i = 0; i < 16; ++i) {
9347     if (Mask[i / Scale] == -1) {
9348       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9349     } else {
9350       const int ZeroMask = 0x80;
9351       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9352                                           : ZeroMask;
9353       int V2Idx = Mask[i / Scale] < Size
9354                       ? ZeroMask
9355                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9356       if (Zeroable[i / Scale])
9357         V1Idx = V2Idx = ZeroMask;
9358       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9359       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9360       V1InUse |= (ZeroMask != V1Idx);
9361       V2InUse |= (ZeroMask != V2Idx);
9362     }
9363   }
9364
9365   if (V1InUse)
9366     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9367                      DAG.getBitcast(MVT::v16i8, V1),
9368                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9369   if (V2InUse)
9370     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9371                      DAG.getBitcast(MVT::v16i8, V2),
9372                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9373
9374   // If we need shuffled inputs from both, blend the two.
9375   SDValue V;
9376   if (V1InUse && V2InUse)
9377     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9378   else
9379     V = V1InUse ? V1 : V2;
9380
9381   // Cast the result back to the correct type.
9382   return DAG.getBitcast(VT, V);
9383 }
9384
9385 /// \brief Generic lowering of 8-lane i16 shuffles.
9386 ///
9387 /// This handles both single-input shuffles and combined shuffle/blends with
9388 /// two inputs. The single input shuffles are immediately delegated to
9389 /// a dedicated lowering routine.
9390 ///
9391 /// The blends are lowered in one of three fundamental ways. If there are few
9392 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9393 /// of the input is significantly cheaper when lowered as an interleaving of
9394 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9395 /// halves of the inputs separately (making them have relatively few inputs)
9396 /// and then concatenate them.
9397 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9398                                        const X86Subtarget *Subtarget,
9399                                        SelectionDAG &DAG) {
9400   SDLoc DL(Op);
9401   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9402   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9403   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9404   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9405   ArrayRef<int> OrigMask = SVOp->getMask();
9406   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9407                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9408   MutableArrayRef<int> Mask(MaskStorage);
9409
9410   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9411
9412   // Whenever we can lower this as a zext, that instruction is strictly faster
9413   // than any alternative.
9414   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9415           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9416     return ZExt;
9417
9418   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9419   (void)isV1;
9420   auto isV2 = [](int M) { return M >= 8; };
9421
9422   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9423
9424   if (NumV2Inputs == 0) {
9425     // Check for being able to broadcast a single element.
9426     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9427                                                           Mask, Subtarget, DAG))
9428       return Broadcast;
9429
9430     // Try to use shift instructions.
9431     if (SDValue Shift =
9432             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9433       return Shift;
9434
9435     // Use dedicated unpack instructions for masks that match their pattern.
9436     if (SDValue V =
9437             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9438       return V;
9439
9440     // Try to use byte rotation instructions.
9441     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9442                                                         Mask, Subtarget, DAG))
9443       return Rotate;
9444
9445     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9446                                                      Subtarget, DAG);
9447   }
9448
9449   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9450          "All single-input shuffles should be canonicalized to be V1-input "
9451          "shuffles.");
9452
9453   // Try to use shift instructions.
9454   if (SDValue Shift =
9455           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9456     return Shift;
9457
9458   // See if we can use SSE4A Extraction / Insertion.
9459   if (Subtarget->hasSSE4A())
9460     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9461       return V;
9462
9463   // There are special ways we can lower some single-element blends.
9464   if (NumV2Inputs == 1)
9465     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9466                                                          Mask, Subtarget, DAG))
9467       return V;
9468
9469   // We have different paths for blend lowering, but they all must use the
9470   // *exact* same predicate.
9471   bool IsBlendSupported = Subtarget->hasSSE41();
9472   if (IsBlendSupported)
9473     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9474                                                   Subtarget, DAG))
9475       return Blend;
9476
9477   if (SDValue Masked =
9478           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9479     return Masked;
9480
9481   // Use dedicated unpack instructions for masks that match their pattern.
9482   if (SDValue V =
9483           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9484     return V;
9485
9486   // Try to use byte rotation instructions.
9487   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9488           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9489     return Rotate;
9490
9491   if (SDValue BitBlend =
9492           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9493     return BitBlend;
9494
9495   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9496                                                             V2, Mask, DAG))
9497     return Unpack;
9498
9499   // If we can't directly blend but can use PSHUFB, that will be better as it
9500   // can both shuffle and set up the inefficient blend.
9501   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9502     bool V1InUse, V2InUse;
9503     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9504                                       V1InUse, V2InUse);
9505   }
9506
9507   // We can always bit-blend if we have to so the fallback strategy is to
9508   // decompose into single-input permutes and blends.
9509   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9510                                                       Mask, DAG);
9511 }
9512
9513 /// \brief Check whether a compaction lowering can be done by dropping even
9514 /// elements and compute how many times even elements must be dropped.
9515 ///
9516 /// This handles shuffles which take every Nth element where N is a power of
9517 /// two. Example shuffle masks:
9518 ///
9519 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9520 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9521 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9522 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9523 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9524 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9525 ///
9526 /// Any of these lanes can of course be undef.
9527 ///
9528 /// This routine only supports N <= 3.
9529 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9530 /// for larger N.
9531 ///
9532 /// \returns N above, or the number of times even elements must be dropped if
9533 /// there is such a number. Otherwise returns zero.
9534 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9535   // Figure out whether we're looping over two inputs or just one.
9536   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9537
9538   // The modulus for the shuffle vector entries is based on whether this is
9539   // a single input or not.
9540   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9541   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9542          "We should only be called with masks with a power-of-2 size!");
9543
9544   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9545
9546   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9547   // and 2^3 simultaneously. This is because we may have ambiguity with
9548   // partially undef inputs.
9549   bool ViableForN[3] = {true, true, true};
9550
9551   for (int i = 0, e = Mask.size(); i < e; ++i) {
9552     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9553     // want.
9554     if (Mask[i] == -1)
9555       continue;
9556
9557     bool IsAnyViable = false;
9558     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9559       if (ViableForN[j]) {
9560         uint64_t N = j + 1;
9561
9562         // The shuffle mask must be equal to (i * 2^N) % M.
9563         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9564           IsAnyViable = true;
9565         else
9566           ViableForN[j] = false;
9567       }
9568     // Early exit if we exhaust the possible powers of two.
9569     if (!IsAnyViable)
9570       break;
9571   }
9572
9573   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9574     if (ViableForN[j])
9575       return j + 1;
9576
9577   // Return 0 as there is no viable power of two.
9578   return 0;
9579 }
9580
9581 /// \brief Generic lowering of v16i8 shuffles.
9582 ///
9583 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9584 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9585 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9586 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9587 /// back together.
9588 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9589                                        const X86Subtarget *Subtarget,
9590                                        SelectionDAG &DAG) {
9591   SDLoc DL(Op);
9592   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9593   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9594   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9595   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9596   ArrayRef<int> Mask = SVOp->getMask();
9597   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9598
9599   // Try to use shift instructions.
9600   if (SDValue Shift =
9601           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9602     return Shift;
9603
9604   // Try to use byte rotation instructions.
9605   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9606           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9607     return Rotate;
9608
9609   // Try to use a zext lowering.
9610   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9611           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9612     return ZExt;
9613
9614   // See if we can use SSE4A Extraction / Insertion.
9615   if (Subtarget->hasSSE4A())
9616     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9617       return V;
9618
9619   int NumV2Elements =
9620       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9621
9622   // For single-input shuffles, there are some nicer lowering tricks we can use.
9623   if (NumV2Elements == 0) {
9624     // Check for being able to broadcast a single element.
9625     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9626                                                           Mask, Subtarget, DAG))
9627       return Broadcast;
9628
9629     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9630     // Notably, this handles splat and partial-splat shuffles more efficiently.
9631     // However, it only makes sense if the pre-duplication shuffle simplifies
9632     // things significantly. Currently, this means we need to be able to
9633     // express the pre-duplication shuffle as an i16 shuffle.
9634     //
9635     // FIXME: We should check for other patterns which can be widened into an
9636     // i16 shuffle as well.
9637     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9638       for (int i = 0; i < 16; i += 2)
9639         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9640           return false;
9641
9642       return true;
9643     };
9644     auto tryToWidenViaDuplication = [&]() -> SDValue {
9645       if (!canWidenViaDuplication(Mask))
9646         return SDValue();
9647       SmallVector<int, 4> LoInputs;
9648       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9649                    [](int M) { return M >= 0 && M < 8; });
9650       std::sort(LoInputs.begin(), LoInputs.end());
9651       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9652                      LoInputs.end());
9653       SmallVector<int, 4> HiInputs;
9654       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9655                    [](int M) { return M >= 8; });
9656       std::sort(HiInputs.begin(), HiInputs.end());
9657       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9658                      HiInputs.end());
9659
9660       bool TargetLo = LoInputs.size() >= HiInputs.size();
9661       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9662       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9663
9664       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9665       SmallDenseMap<int, int, 8> LaneMap;
9666       for (int I : InPlaceInputs) {
9667         PreDupI16Shuffle[I/2] = I/2;
9668         LaneMap[I] = I;
9669       }
9670       int j = TargetLo ? 0 : 4, je = j + 4;
9671       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9672         // Check if j is already a shuffle of this input. This happens when
9673         // there are two adjacent bytes after we move the low one.
9674         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9675           // If we haven't yet mapped the input, search for a slot into which
9676           // we can map it.
9677           while (j < je && PreDupI16Shuffle[j] != -1)
9678             ++j;
9679
9680           if (j == je)
9681             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9682             return SDValue();
9683
9684           // Map this input with the i16 shuffle.
9685           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9686         }
9687
9688         // Update the lane map based on the mapping we ended up with.
9689         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9690       }
9691       V1 = DAG.getBitcast(
9692           MVT::v16i8,
9693           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9694                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9695
9696       // Unpack the bytes to form the i16s that will be shuffled into place.
9697       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9698                        MVT::v16i8, V1, V1);
9699
9700       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9701       for (int i = 0; i < 16; ++i)
9702         if (Mask[i] != -1) {
9703           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9704           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9705           if (PostDupI16Shuffle[i / 2] == -1)
9706             PostDupI16Shuffle[i / 2] = MappedMask;
9707           else
9708             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9709                    "Conflicting entrties in the original shuffle!");
9710         }
9711       return DAG.getBitcast(
9712           MVT::v16i8,
9713           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9714                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9715     };
9716     if (SDValue V = tryToWidenViaDuplication())
9717       return V;
9718   }
9719
9720   if (SDValue Masked =
9721           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9722     return Masked;
9723
9724   // Use dedicated unpack instructions for masks that match their pattern.
9725   if (SDValue V =
9726           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9727     return V;
9728
9729   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9730   // with PSHUFB. It is important to do this before we attempt to generate any
9731   // blends but after all of the single-input lowerings. If the single input
9732   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9733   // want to preserve that and we can DAG combine any longer sequences into
9734   // a PSHUFB in the end. But once we start blending from multiple inputs,
9735   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9736   // and there are *very* few patterns that would actually be faster than the
9737   // PSHUFB approach because of its ability to zero lanes.
9738   //
9739   // FIXME: The only exceptions to the above are blends which are exact
9740   // interleavings with direct instructions supporting them. We currently don't
9741   // handle those well here.
9742   if (Subtarget->hasSSSE3()) {
9743     bool V1InUse = false;
9744     bool V2InUse = false;
9745
9746     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9747                                                 DAG, V1InUse, V2InUse);
9748
9749     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9750     // do so. This avoids using them to handle blends-with-zero which is
9751     // important as a single pshufb is significantly faster for that.
9752     if (V1InUse && V2InUse) {
9753       if (Subtarget->hasSSE41())
9754         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9755                                                       Mask, Subtarget, DAG))
9756           return Blend;
9757
9758       // We can use an unpack to do the blending rather than an or in some
9759       // cases. Even though the or may be (very minorly) more efficient, we
9760       // preference this lowering because there are common cases where part of
9761       // the complexity of the shuffles goes away when we do the final blend as
9762       // an unpack.
9763       // FIXME: It might be worth trying to detect if the unpack-feeding
9764       // shuffles will both be pshufb, in which case we shouldn't bother with
9765       // this.
9766       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9767               DL, MVT::v16i8, V1, V2, Mask, DAG))
9768         return Unpack;
9769     }
9770
9771     return PSHUFB;
9772   }
9773
9774   // There are special ways we can lower some single-element blends.
9775   if (NumV2Elements == 1)
9776     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9777                                                          Mask, Subtarget, DAG))
9778       return V;
9779
9780   if (SDValue BitBlend =
9781           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9782     return BitBlend;
9783
9784   // Check whether a compaction lowering can be done. This handles shuffles
9785   // which take every Nth element for some even N. See the helper function for
9786   // details.
9787   //
9788   // We special case these as they can be particularly efficiently handled with
9789   // the PACKUSB instruction on x86 and they show up in common patterns of
9790   // rearranging bytes to truncate wide elements.
9791   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9792     // NumEvenDrops is the power of two stride of the elements. Another way of
9793     // thinking about it is that we need to drop the even elements this many
9794     // times to get the original input.
9795     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9796
9797     // First we need to zero all the dropped bytes.
9798     assert(NumEvenDrops <= 3 &&
9799            "No support for dropping even elements more than 3 times.");
9800     // We use the mask type to pick which bytes are preserved based on how many
9801     // elements are dropped.
9802     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9803     SDValue ByteClearMask = DAG.getBitcast(
9804         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9805     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9806     if (!IsSingleInput)
9807       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9808
9809     // Now pack things back together.
9810     V1 = DAG.getBitcast(MVT::v8i16, V1);
9811     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9812     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9813     for (int i = 1; i < NumEvenDrops; ++i) {
9814       Result = DAG.getBitcast(MVT::v8i16, Result);
9815       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9816     }
9817
9818     return Result;
9819   }
9820
9821   // Handle multi-input cases by blending single-input shuffles.
9822   if (NumV2Elements > 0)
9823     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9824                                                       Mask, DAG);
9825
9826   // The fallback path for single-input shuffles widens this into two v8i16
9827   // vectors with unpacks, shuffles those, and then pulls them back together
9828   // with a pack.
9829   SDValue V = V1;
9830
9831   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9832   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9833   for (int i = 0; i < 16; ++i)
9834     if (Mask[i] >= 0)
9835       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9836
9837   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9838
9839   SDValue VLoHalf, VHiHalf;
9840   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9841   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9842   // i16s.
9843   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9844                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9845       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9846                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9847     // Use a mask to drop the high bytes.
9848     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9849     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9850                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9851
9852     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9853     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9854
9855     // Squash the masks to point directly into VLoHalf.
9856     for (int &M : LoBlendMask)
9857       if (M >= 0)
9858         M /= 2;
9859     for (int &M : HiBlendMask)
9860       if (M >= 0)
9861         M /= 2;
9862   } else {
9863     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9864     // VHiHalf so that we can blend them as i16s.
9865     VLoHalf = DAG.getBitcast(
9866         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9867     VHiHalf = DAG.getBitcast(
9868         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9869   }
9870
9871   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9872   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9873
9874   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9875 }
9876
9877 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9878 ///
9879 /// This routine breaks down the specific type of 128-bit shuffle and
9880 /// dispatches to the lowering routines accordingly.
9881 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9882                                         MVT VT, const X86Subtarget *Subtarget,
9883                                         SelectionDAG &DAG) {
9884   switch (VT.SimpleTy) {
9885   case MVT::v2i64:
9886     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9887   case MVT::v2f64:
9888     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9889   case MVT::v4i32:
9890     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9891   case MVT::v4f32:
9892     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9893   case MVT::v8i16:
9894     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9895   case MVT::v16i8:
9896     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9897
9898   default:
9899     llvm_unreachable("Unimplemented!");
9900   }
9901 }
9902
9903 /// \brief Helper function to test whether a shuffle mask could be
9904 /// simplified by widening the elements being shuffled.
9905 ///
9906 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9907 /// leaves it in an unspecified state.
9908 ///
9909 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9910 /// shuffle masks. The latter have the special property of a '-2' representing
9911 /// a zero-ed lane of a vector.
9912 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9913                                     SmallVectorImpl<int> &WidenedMask) {
9914   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9915     // If both elements are undef, its trivial.
9916     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9917       WidenedMask.push_back(SM_SentinelUndef);
9918       continue;
9919     }
9920
9921     // Check for an undef mask and a mask value properly aligned to fit with
9922     // a pair of values. If we find such a case, use the non-undef mask's value.
9923     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9924       WidenedMask.push_back(Mask[i + 1] / 2);
9925       continue;
9926     }
9927     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9928       WidenedMask.push_back(Mask[i] / 2);
9929       continue;
9930     }
9931
9932     // When zeroing, we need to spread the zeroing across both lanes to widen.
9933     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9934       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9935           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9936         WidenedMask.push_back(SM_SentinelZero);
9937         continue;
9938       }
9939       return false;
9940     }
9941
9942     // Finally check if the two mask values are adjacent and aligned with
9943     // a pair.
9944     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9945       WidenedMask.push_back(Mask[i] / 2);
9946       continue;
9947     }
9948
9949     // Otherwise we can't safely widen the elements used in this shuffle.
9950     return false;
9951   }
9952   assert(WidenedMask.size() == Mask.size() / 2 &&
9953          "Incorrect size of mask after widening the elements!");
9954
9955   return true;
9956 }
9957
9958 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9959 ///
9960 /// This routine just extracts two subvectors, shuffles them independently, and
9961 /// then concatenates them back together. This should work effectively with all
9962 /// AVX vector shuffle types.
9963 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9964                                           SDValue V2, ArrayRef<int> Mask,
9965                                           SelectionDAG &DAG) {
9966   assert(VT.getSizeInBits() >= 256 &&
9967          "Only for 256-bit or wider vector shuffles!");
9968   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9969   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9970
9971   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9972   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9973
9974   int NumElements = VT.getVectorNumElements();
9975   int SplitNumElements = NumElements / 2;
9976   MVT ScalarVT = VT.getVectorElementType();
9977   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9978
9979   // Rather than splitting build-vectors, just build two narrower build
9980   // vectors. This helps shuffling with splats and zeros.
9981   auto SplitVector = [&](SDValue V) {
9982     while (V.getOpcode() == ISD::BITCAST)
9983       V = V->getOperand(0);
9984
9985     MVT OrigVT = V.getSimpleValueType();
9986     int OrigNumElements = OrigVT.getVectorNumElements();
9987     int OrigSplitNumElements = OrigNumElements / 2;
9988     MVT OrigScalarVT = OrigVT.getVectorElementType();
9989     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9990
9991     SDValue LoV, HiV;
9992
9993     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9994     if (!BV) {
9995       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9996                         DAG.getIntPtrConstant(0, DL));
9997       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9998                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9999     } else {
10000
10001       SmallVector<SDValue, 16> LoOps, HiOps;
10002       for (int i = 0; i < OrigSplitNumElements; ++i) {
10003         LoOps.push_back(BV->getOperand(i));
10004         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10005       }
10006       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10007       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10008     }
10009     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10010                           DAG.getBitcast(SplitVT, HiV));
10011   };
10012
10013   SDValue LoV1, HiV1, LoV2, HiV2;
10014   std::tie(LoV1, HiV1) = SplitVector(V1);
10015   std::tie(LoV2, HiV2) = SplitVector(V2);
10016
10017   // Now create two 4-way blends of these half-width vectors.
10018   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10019     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10020     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10021     for (int i = 0; i < SplitNumElements; ++i) {
10022       int M = HalfMask[i];
10023       if (M >= NumElements) {
10024         if (M >= NumElements + SplitNumElements)
10025           UseHiV2 = true;
10026         else
10027           UseLoV2 = true;
10028         V2BlendMask.push_back(M - NumElements);
10029         V1BlendMask.push_back(-1);
10030         BlendMask.push_back(SplitNumElements + i);
10031       } else if (M >= 0) {
10032         if (M >= SplitNumElements)
10033           UseHiV1 = true;
10034         else
10035           UseLoV1 = true;
10036         V2BlendMask.push_back(-1);
10037         V1BlendMask.push_back(M);
10038         BlendMask.push_back(i);
10039       } else {
10040         V2BlendMask.push_back(-1);
10041         V1BlendMask.push_back(-1);
10042         BlendMask.push_back(-1);
10043       }
10044     }
10045
10046     // Because the lowering happens after all combining takes place, we need to
10047     // manually combine these blend masks as much as possible so that we create
10048     // a minimal number of high-level vector shuffle nodes.
10049
10050     // First try just blending the halves of V1 or V2.
10051     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10052       return DAG.getUNDEF(SplitVT);
10053     if (!UseLoV2 && !UseHiV2)
10054       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10055     if (!UseLoV1 && !UseHiV1)
10056       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10057
10058     SDValue V1Blend, V2Blend;
10059     if (UseLoV1 && UseHiV1) {
10060       V1Blend =
10061         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10062     } else {
10063       // We only use half of V1 so map the usage down into the final blend mask.
10064       V1Blend = UseLoV1 ? LoV1 : HiV1;
10065       for (int i = 0; i < SplitNumElements; ++i)
10066         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10067           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10068     }
10069     if (UseLoV2 && UseHiV2) {
10070       V2Blend =
10071         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10072     } else {
10073       // We only use half of V2 so map the usage down into the final blend mask.
10074       V2Blend = UseLoV2 ? LoV2 : HiV2;
10075       for (int i = 0; i < SplitNumElements; ++i)
10076         if (BlendMask[i] >= SplitNumElements)
10077           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10078     }
10079     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10080   };
10081   SDValue Lo = HalfBlend(LoMask);
10082   SDValue Hi = HalfBlend(HiMask);
10083   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10084 }
10085
10086 /// \brief Either split a vector in halves or decompose the shuffles and the
10087 /// blend.
10088 ///
10089 /// This is provided as a good fallback for many lowerings of non-single-input
10090 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10091 /// between splitting the shuffle into 128-bit components and stitching those
10092 /// back together vs. extracting the single-input shuffles and blending those
10093 /// results.
10094 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10095                                                 SDValue V2, ArrayRef<int> Mask,
10096                                                 SelectionDAG &DAG) {
10097   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10098                                             "lower single-input shuffles as it "
10099                                             "could then recurse on itself.");
10100   int Size = Mask.size();
10101
10102   // If this can be modeled as a broadcast of two elements followed by a blend,
10103   // prefer that lowering. This is especially important because broadcasts can
10104   // often fold with memory operands.
10105   auto DoBothBroadcast = [&] {
10106     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10107     for (int M : Mask)
10108       if (M >= Size) {
10109         if (V2BroadcastIdx == -1)
10110           V2BroadcastIdx = M - Size;
10111         else if (M - Size != V2BroadcastIdx)
10112           return false;
10113       } else if (M >= 0) {
10114         if (V1BroadcastIdx == -1)
10115           V1BroadcastIdx = M;
10116         else if (M != V1BroadcastIdx)
10117           return false;
10118       }
10119     return true;
10120   };
10121   if (DoBothBroadcast())
10122     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10123                                                       DAG);
10124
10125   // If the inputs all stem from a single 128-bit lane of each input, then we
10126   // split them rather than blending because the split will decompose to
10127   // unusually few instructions.
10128   int LaneCount = VT.getSizeInBits() / 128;
10129   int LaneSize = Size / LaneCount;
10130   SmallBitVector LaneInputs[2];
10131   LaneInputs[0].resize(LaneCount, false);
10132   LaneInputs[1].resize(LaneCount, false);
10133   for (int i = 0; i < Size; ++i)
10134     if (Mask[i] >= 0)
10135       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10136   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10137     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10138
10139   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10140   // that the decomposed single-input shuffles don't end up here.
10141   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10142 }
10143
10144 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10145 /// a permutation and blend of those lanes.
10146 ///
10147 /// This essentially blends the out-of-lane inputs to each lane into the lane
10148 /// from a permuted copy of the vector. This lowering strategy results in four
10149 /// instructions in the worst case for a single-input cross lane shuffle which
10150 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10151 /// of. Special cases for each particular shuffle pattern should be handled
10152 /// prior to trying this lowering.
10153 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10154                                                        SDValue V1, SDValue V2,
10155                                                        ArrayRef<int> Mask,
10156                                                        SelectionDAG &DAG) {
10157   // FIXME: This should probably be generalized for 512-bit vectors as well.
10158   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10159   int LaneSize = Mask.size() / 2;
10160
10161   // If there are only inputs from one 128-bit lane, splitting will in fact be
10162   // less expensive. The flags track whether the given lane contains an element
10163   // that crosses to another lane.
10164   bool LaneCrossing[2] = {false, false};
10165   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10166     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10167       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10168   if (!LaneCrossing[0] || !LaneCrossing[1])
10169     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10170
10171   if (isSingleInputShuffleMask(Mask)) {
10172     SmallVector<int, 32> FlippedBlendMask;
10173     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10174       FlippedBlendMask.push_back(
10175           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10176                                   ? Mask[i]
10177                                   : Mask[i] % LaneSize +
10178                                         (i / LaneSize) * LaneSize + Size));
10179
10180     // Flip the vector, and blend the results which should now be in-lane. The
10181     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10182     // 5 for the high source. The value 3 selects the high half of source 2 and
10183     // the value 2 selects the low half of source 2. We only use source 2 to
10184     // allow folding it into a memory operand.
10185     unsigned PERMMask = 3 | 2 << 4;
10186     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10187                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10188     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10189   }
10190
10191   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10192   // will be handled by the above logic and a blend of the results, much like
10193   // other patterns in AVX.
10194   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10195 }
10196
10197 /// \brief Handle lowering 2-lane 128-bit shuffles.
10198 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10199                                         SDValue V2, ArrayRef<int> Mask,
10200                                         const X86Subtarget *Subtarget,
10201                                         SelectionDAG &DAG) {
10202   // TODO: If minimizing size and one of the inputs is a zero vector and the
10203   // the zero vector has only one use, we could use a VPERM2X128 to save the
10204   // instruction bytes needed to explicitly generate the zero vector.
10205
10206   // Blends are faster and handle all the non-lane-crossing cases.
10207   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10208                                                 Subtarget, DAG))
10209     return Blend;
10210
10211   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10212   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10213
10214   // If either input operand is a zero vector, use VPERM2X128 because its mask
10215   // allows us to replace the zero input with an implicit zero.
10216   if (!IsV1Zero && !IsV2Zero) {
10217     // Check for patterns which can be matched with a single insert of a 128-bit
10218     // subvector.
10219     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10220     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10221       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10222                                    VT.getVectorNumElements() / 2);
10223       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10224                                 DAG.getIntPtrConstant(0, DL));
10225       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10226                                 OnlyUsesV1 ? V1 : V2,
10227                                 DAG.getIntPtrConstant(0, DL));
10228       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10229     }
10230   }
10231
10232   // Otherwise form a 128-bit permutation. After accounting for undefs,
10233   // convert the 64-bit shuffle mask selection values into 128-bit
10234   // selection bits by dividing the indexes by 2 and shifting into positions
10235   // defined by a vperm2*128 instruction's immediate control byte.
10236
10237   // The immediate permute control byte looks like this:
10238   //    [1:0] - select 128 bits from sources for low half of destination
10239   //    [2]   - ignore
10240   //    [3]   - zero low half of destination
10241   //    [5:4] - select 128 bits from sources for high half of destination
10242   //    [6]   - ignore
10243   //    [7]   - zero high half of destination
10244
10245   int MaskLO = Mask[0];
10246   if (MaskLO == SM_SentinelUndef)
10247     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10248
10249   int MaskHI = Mask[2];
10250   if (MaskHI == SM_SentinelUndef)
10251     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10252
10253   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10254
10255   // If either input is a zero vector, replace it with an undef input.
10256   // Shuffle mask values <  4 are selecting elements of V1.
10257   // Shuffle mask values >= 4 are selecting elements of V2.
10258   // Adjust each half of the permute mask by clearing the half that was
10259   // selecting the zero vector and setting the zero mask bit.
10260   if (IsV1Zero) {
10261     V1 = DAG.getUNDEF(VT);
10262     if (MaskLO < 4)
10263       PermMask = (PermMask & 0xf0) | 0x08;
10264     if (MaskHI < 4)
10265       PermMask = (PermMask & 0x0f) | 0x80;
10266   }
10267   if (IsV2Zero) {
10268     V2 = DAG.getUNDEF(VT);
10269     if (MaskLO >= 4)
10270       PermMask = (PermMask & 0xf0) | 0x08;
10271     if (MaskHI >= 4)
10272       PermMask = (PermMask & 0x0f) | 0x80;
10273   }
10274
10275   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10276                      DAG.getConstant(PermMask, DL, MVT::i8));
10277 }
10278
10279 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10280 /// shuffling each lane.
10281 ///
10282 /// This will only succeed when the result of fixing the 128-bit lanes results
10283 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10284 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10285 /// the lane crosses early and then use simpler shuffles within each lane.
10286 ///
10287 /// FIXME: It might be worthwhile at some point to support this without
10288 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10289 /// in x86 only floating point has interesting non-repeating shuffles, and even
10290 /// those are still *marginally* more expensive.
10291 static SDValue lowerVectorShuffleByMerging128BitLanes(
10292     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10293     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10294   assert(!isSingleInputShuffleMask(Mask) &&
10295          "This is only useful with multiple inputs.");
10296
10297   int Size = Mask.size();
10298   int LaneSize = 128 / VT.getScalarSizeInBits();
10299   int NumLanes = Size / LaneSize;
10300   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10301
10302   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10303   // check whether the in-128-bit lane shuffles share a repeating pattern.
10304   SmallVector<int, 4> Lanes;
10305   Lanes.resize(NumLanes, -1);
10306   SmallVector<int, 4> InLaneMask;
10307   InLaneMask.resize(LaneSize, -1);
10308   for (int i = 0; i < Size; ++i) {
10309     if (Mask[i] < 0)
10310       continue;
10311
10312     int j = i / LaneSize;
10313
10314     if (Lanes[j] < 0) {
10315       // First entry we've seen for this lane.
10316       Lanes[j] = Mask[i] / LaneSize;
10317     } else if (Lanes[j] != Mask[i] / LaneSize) {
10318       // This doesn't match the lane selected previously!
10319       return SDValue();
10320     }
10321
10322     // Check that within each lane we have a consistent shuffle mask.
10323     int k = i % LaneSize;
10324     if (InLaneMask[k] < 0) {
10325       InLaneMask[k] = Mask[i] % LaneSize;
10326     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10327       // This doesn't fit a repeating in-lane mask.
10328       return SDValue();
10329     }
10330   }
10331
10332   // First shuffle the lanes into place.
10333   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10334                                 VT.getSizeInBits() / 64);
10335   SmallVector<int, 8> LaneMask;
10336   LaneMask.resize(NumLanes * 2, -1);
10337   for (int i = 0; i < NumLanes; ++i)
10338     if (Lanes[i] >= 0) {
10339       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10340       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10341     }
10342
10343   V1 = DAG.getBitcast(LaneVT, V1);
10344   V2 = DAG.getBitcast(LaneVT, V2);
10345   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10346
10347   // Cast it back to the type we actually want.
10348   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10349
10350   // Now do a simple shuffle that isn't lane crossing.
10351   SmallVector<int, 8> NewMask;
10352   NewMask.resize(Size, -1);
10353   for (int i = 0; i < Size; ++i)
10354     if (Mask[i] >= 0)
10355       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10356   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10357          "Must not introduce lane crosses at this point!");
10358
10359   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10360 }
10361
10362 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10363 /// given mask.
10364 ///
10365 /// This returns true if the elements from a particular input are already in the
10366 /// slot required by the given mask and require no permutation.
10367 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10368   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10369   int Size = Mask.size();
10370   for (int i = 0; i < Size; ++i)
10371     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10372       return false;
10373
10374   return true;
10375 }
10376
10377 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10378                                             ArrayRef<int> Mask, SDValue V1,
10379                                             SDValue V2, SelectionDAG &DAG) {
10380
10381   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10382   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10383   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10384   int NumElts = VT.getVectorNumElements();
10385   bool ShufpdMask = true;
10386   bool CommutableMask = true;
10387   unsigned Immediate = 0;
10388   for (int i = 0; i < NumElts; ++i) {
10389     if (Mask[i] < 0)
10390       continue;
10391     int Val = (i & 6) + NumElts * (i & 1);
10392     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10393     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10394       ShufpdMask = false;
10395     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10396       CommutableMask = false;
10397     Immediate |= (Mask[i] % 2) << i;
10398   }
10399   if (ShufpdMask)
10400     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10401                        DAG.getConstant(Immediate, DL, MVT::i8));
10402   if (CommutableMask)
10403     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10404                        DAG.getConstant(Immediate, DL, MVT::i8));
10405   return SDValue();
10406 }
10407
10408 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10409 ///
10410 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10411 /// isn't available.
10412 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10413                                        const X86Subtarget *Subtarget,
10414                                        SelectionDAG &DAG) {
10415   SDLoc DL(Op);
10416   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10417   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10418   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10419   ArrayRef<int> Mask = SVOp->getMask();
10420   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10421
10422   SmallVector<int, 4> WidenedMask;
10423   if (canWidenShuffleElements(Mask, WidenedMask))
10424     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10425                                     DAG);
10426
10427   if (isSingleInputShuffleMask(Mask)) {
10428     // Check for being able to broadcast a single element.
10429     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10430                                                           Mask, Subtarget, DAG))
10431       return Broadcast;
10432
10433     // Use low duplicate instructions for masks that match their pattern.
10434     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10435       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10436
10437     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10438       // Non-half-crossing single input shuffles can be lowerid with an
10439       // interleaved permutation.
10440       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10441                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10442       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10443                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10444     }
10445
10446     // With AVX2 we have direct support for this permutation.
10447     if (Subtarget->hasAVX2())
10448       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10449                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10450
10451     // Otherwise, fall back.
10452     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10453                                                    DAG);
10454   }
10455
10456   // Use dedicated unpack instructions for masks that match their pattern.
10457   if (SDValue V =
10458           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10459     return V;
10460
10461   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10462                                                 Subtarget, DAG))
10463     return Blend;
10464
10465   // Check if the blend happens to exactly fit that of SHUFPD.
10466   if (SDValue Op =
10467       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10468     return Op;
10469
10470   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10471   // shuffle. However, if we have AVX2 and either inputs are already in place,
10472   // we will be able to shuffle even across lanes the other input in a single
10473   // instruction so skip this pattern.
10474   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10475                                  isShuffleMaskInputInPlace(1, Mask))))
10476     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10477             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10478       return Result;
10479
10480   // If we have AVX2 then we always want to lower with a blend because an v4 we
10481   // can fully permute the elements.
10482   if (Subtarget->hasAVX2())
10483     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10484                                                       Mask, DAG);
10485
10486   // Otherwise fall back on generic lowering.
10487   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10488 }
10489
10490 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10491 ///
10492 /// This routine is only called when we have AVX2 and thus a reasonable
10493 /// instruction set for v4i64 shuffling..
10494 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10495                                        const X86Subtarget *Subtarget,
10496                                        SelectionDAG &DAG) {
10497   SDLoc DL(Op);
10498   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10499   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10500   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10501   ArrayRef<int> Mask = SVOp->getMask();
10502   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10503   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10504
10505   SmallVector<int, 4> WidenedMask;
10506   if (canWidenShuffleElements(Mask, WidenedMask))
10507     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10508                                     DAG);
10509
10510   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10511                                                 Subtarget, DAG))
10512     return Blend;
10513
10514   // Check for being able to broadcast a single element.
10515   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10516                                                         Mask, Subtarget, DAG))
10517     return Broadcast;
10518
10519   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10520   // use lower latency instructions that will operate on both 128-bit lanes.
10521   SmallVector<int, 2> RepeatedMask;
10522   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10523     if (isSingleInputShuffleMask(Mask)) {
10524       int PSHUFDMask[] = {-1, -1, -1, -1};
10525       for (int i = 0; i < 2; ++i)
10526         if (RepeatedMask[i] >= 0) {
10527           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10528           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10529         }
10530       return DAG.getBitcast(
10531           MVT::v4i64,
10532           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10533                       DAG.getBitcast(MVT::v8i32, V1),
10534                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10535     }
10536   }
10537
10538   // AVX2 provides a direct instruction for permuting a single input across
10539   // lanes.
10540   if (isSingleInputShuffleMask(Mask))
10541     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10542                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10543
10544   // Try to use shift instructions.
10545   if (SDValue Shift =
10546           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10547     return Shift;
10548
10549   // Use dedicated unpack instructions for masks that match their pattern.
10550   if (SDValue V =
10551           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10552     return V;
10553
10554   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10555   // shuffle. However, if we have AVX2 and either inputs are already in place,
10556   // we will be able to shuffle even across lanes the other input in a single
10557   // instruction so skip this pattern.
10558   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10559                                  isShuffleMaskInputInPlace(1, Mask))))
10560     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10561             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10562       return Result;
10563
10564   // Otherwise fall back on generic blend lowering.
10565   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10566                                                     Mask, DAG);
10567 }
10568
10569 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10570 ///
10571 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10572 /// isn't available.
10573 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10574                                        const X86Subtarget *Subtarget,
10575                                        SelectionDAG &DAG) {
10576   SDLoc DL(Op);
10577   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10578   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10579   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10580   ArrayRef<int> Mask = SVOp->getMask();
10581   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10582
10583   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10584                                                 Subtarget, DAG))
10585     return Blend;
10586
10587   // Check for being able to broadcast a single element.
10588   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10589                                                         Mask, Subtarget, DAG))
10590     return Broadcast;
10591
10592   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10593   // options to efficiently lower the shuffle.
10594   SmallVector<int, 4> RepeatedMask;
10595   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10596     assert(RepeatedMask.size() == 4 &&
10597            "Repeated masks must be half the mask width!");
10598
10599     // Use even/odd duplicate instructions for masks that match their pattern.
10600     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10601       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10602     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10603       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10604
10605     if (isSingleInputShuffleMask(Mask))
10606       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10607                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10608
10609     // Use dedicated unpack instructions for masks that match their pattern.
10610     if (SDValue V =
10611             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10612       return V;
10613
10614     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10615     // have already handled any direct blends. We also need to squash the
10616     // repeated mask into a simulated v4f32 mask.
10617     for (int i = 0; i < 4; ++i)
10618       if (RepeatedMask[i] >= 8)
10619         RepeatedMask[i] -= 4;
10620     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10621   }
10622
10623   // If we have a single input shuffle with different shuffle patterns in the
10624   // two 128-bit lanes use the variable mask to VPERMILPS.
10625   if (isSingleInputShuffleMask(Mask)) {
10626     SDValue VPermMask[8];
10627     for (int i = 0; i < 8; ++i)
10628       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10629                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10630     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10631       return DAG.getNode(
10632           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10633           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10634
10635     if (Subtarget->hasAVX2())
10636       return DAG.getNode(
10637           X86ISD::VPERMV, DL, MVT::v8f32,
10638           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10639
10640     // Otherwise, fall back.
10641     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10642                                                    DAG);
10643   }
10644
10645   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10646   // shuffle.
10647   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10648           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10649     return Result;
10650
10651   // If we have AVX2 then we always want to lower with a blend because at v8 we
10652   // can fully permute the elements.
10653   if (Subtarget->hasAVX2())
10654     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10655                                                       Mask, DAG);
10656
10657   // Otherwise fall back on generic lowering.
10658   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10659 }
10660
10661 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10662 ///
10663 /// This routine is only called when we have AVX2 and thus a reasonable
10664 /// instruction set for v8i32 shuffling..
10665 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10666                                        const X86Subtarget *Subtarget,
10667                                        SelectionDAG &DAG) {
10668   SDLoc DL(Op);
10669   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10670   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10671   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10672   ArrayRef<int> Mask = SVOp->getMask();
10673   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10674   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10675
10676   // Whenever we can lower this as a zext, that instruction is strictly faster
10677   // than any alternative. It also allows us to fold memory operands into the
10678   // shuffle in many cases.
10679   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10680                                                          Mask, Subtarget, DAG))
10681     return ZExt;
10682
10683   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10684                                                 Subtarget, DAG))
10685     return Blend;
10686
10687   // Check for being able to broadcast a single element.
10688   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10689                                                         Mask, Subtarget, DAG))
10690     return Broadcast;
10691
10692   // If the shuffle mask is repeated in each 128-bit lane we can use more
10693   // efficient instructions that mirror the shuffles across the two 128-bit
10694   // lanes.
10695   SmallVector<int, 4> RepeatedMask;
10696   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10697     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10698     if (isSingleInputShuffleMask(Mask))
10699       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10700                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10701
10702     // Use dedicated unpack instructions for masks that match their pattern.
10703     if (SDValue V =
10704             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10705       return V;
10706   }
10707
10708   // Try to use shift instructions.
10709   if (SDValue Shift =
10710           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10711     return Shift;
10712
10713   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10714           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10715     return Rotate;
10716
10717   // If the shuffle patterns aren't repeated but it is a single input, directly
10718   // generate a cross-lane VPERMD instruction.
10719   if (isSingleInputShuffleMask(Mask)) {
10720     SDValue VPermMask[8];
10721     for (int i = 0; i < 8; ++i)
10722       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10723                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10724     return DAG.getNode(
10725         X86ISD::VPERMV, DL, MVT::v8i32,
10726         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10727   }
10728
10729   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10730   // shuffle.
10731   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10732           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10733     return Result;
10734
10735   // Otherwise fall back on generic blend lowering.
10736   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10737                                                     Mask, DAG);
10738 }
10739
10740 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10741 ///
10742 /// This routine is only called when we have AVX2 and thus a reasonable
10743 /// instruction set for v16i16 shuffling..
10744 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10745                                         const X86Subtarget *Subtarget,
10746                                         SelectionDAG &DAG) {
10747   SDLoc DL(Op);
10748   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10749   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10750   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10751   ArrayRef<int> Mask = SVOp->getMask();
10752   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10753   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10754
10755   // Whenever we can lower this as a zext, that instruction is strictly faster
10756   // than any alternative. It also allows us to fold memory operands into the
10757   // shuffle in many cases.
10758   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10759                                                          Mask, Subtarget, DAG))
10760     return ZExt;
10761
10762   // Check for being able to broadcast a single element.
10763   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10764                                                         Mask, Subtarget, DAG))
10765     return Broadcast;
10766
10767   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10768                                                 Subtarget, DAG))
10769     return Blend;
10770
10771   // Use dedicated unpack instructions for masks that match their pattern.
10772   if (SDValue V =
10773           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10774     return V;
10775
10776   // Try to use shift instructions.
10777   if (SDValue Shift =
10778           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10779     return Shift;
10780
10781   // Try to use byte rotation instructions.
10782   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10783           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10784     return Rotate;
10785
10786   if (isSingleInputShuffleMask(Mask)) {
10787     // There are no generalized cross-lane shuffle operations available on i16
10788     // element types.
10789     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10790       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10791                                                      Mask, DAG);
10792
10793     SmallVector<int, 8> RepeatedMask;
10794     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10795       // As this is a single-input shuffle, the repeated mask should be
10796       // a strictly valid v8i16 mask that we can pass through to the v8i16
10797       // lowering to handle even the v16 case.
10798       return lowerV8I16GeneralSingleInputVectorShuffle(
10799           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10800     }
10801
10802     SDValue PSHUFBMask[32];
10803     for (int i = 0; i < 16; ++i) {
10804       if (Mask[i] == -1) {
10805         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10806         continue;
10807       }
10808
10809       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10810       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10811       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10812       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10813     }
10814     return DAG.getBitcast(MVT::v16i16,
10815                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10816                                       DAG.getBitcast(MVT::v32i8, V1),
10817                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10818                                                   MVT::v32i8, PSHUFBMask)));
10819   }
10820
10821   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10822   // shuffle.
10823   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10824           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10825     return Result;
10826
10827   // Otherwise fall back on generic lowering.
10828   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10829 }
10830
10831 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10832 ///
10833 /// This routine is only called when we have AVX2 and thus a reasonable
10834 /// instruction set for v32i8 shuffling..
10835 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10836                                        const X86Subtarget *Subtarget,
10837                                        SelectionDAG &DAG) {
10838   SDLoc DL(Op);
10839   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10840   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10841   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10842   ArrayRef<int> Mask = SVOp->getMask();
10843   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10844   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10845
10846   // Whenever we can lower this as a zext, that instruction is strictly faster
10847   // than any alternative. It also allows us to fold memory operands into the
10848   // shuffle in many cases.
10849   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10850                                                          Mask, Subtarget, DAG))
10851     return ZExt;
10852
10853   // Check for being able to broadcast a single element.
10854   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10855                                                         Mask, Subtarget, DAG))
10856     return Broadcast;
10857
10858   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10859                                                 Subtarget, DAG))
10860     return Blend;
10861
10862   // Use dedicated unpack instructions for masks that match their pattern.
10863   if (SDValue V =
10864           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10865     return V;
10866
10867   // Try to use shift instructions.
10868   if (SDValue Shift =
10869           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10870     return Shift;
10871
10872   // Try to use byte rotation instructions.
10873   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10874           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10875     return Rotate;
10876
10877   if (isSingleInputShuffleMask(Mask)) {
10878     // There are no generalized cross-lane shuffle operations available on i8
10879     // element types.
10880     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10881       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10882                                                      Mask, DAG);
10883
10884     SDValue PSHUFBMask[32];
10885     for (int i = 0; i < 32; ++i)
10886       PSHUFBMask[i] =
10887           Mask[i] < 0
10888               ? DAG.getUNDEF(MVT::i8)
10889               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10890                                 MVT::i8);
10891
10892     return DAG.getNode(
10893         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10894         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10895   }
10896
10897   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10898   // shuffle.
10899   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10900           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10901     return Result;
10902
10903   // Otherwise fall back on generic lowering.
10904   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10905 }
10906
10907 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10908 ///
10909 /// This routine either breaks down the specific type of a 256-bit x86 vector
10910 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10911 /// together based on the available instructions.
10912 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10913                                         MVT VT, const X86Subtarget *Subtarget,
10914                                         SelectionDAG &DAG) {
10915   SDLoc DL(Op);
10916   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10917   ArrayRef<int> Mask = SVOp->getMask();
10918
10919   // If we have a single input to the zero element, insert that into V1 if we
10920   // can do so cheaply.
10921   int NumElts = VT.getVectorNumElements();
10922   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10923     return M >= NumElts;
10924   });
10925
10926   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10927     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10928                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10929       return Insertion;
10930
10931   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10932   // can check for those subtargets here and avoid much of the subtarget
10933   // querying in the per-vector-type lowering routines. With AVX1 we have
10934   // essentially *zero* ability to manipulate a 256-bit vector with integer
10935   // types. Since we'll use floating point types there eventually, just
10936   // immediately cast everything to a float and operate entirely in that domain.
10937   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10938     int ElementBits = VT.getScalarSizeInBits();
10939     if (ElementBits < 32)
10940       // No floating point type available, decompose into 128-bit vectors.
10941       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10942
10943     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10944                                 VT.getVectorNumElements());
10945     V1 = DAG.getBitcast(FpVT, V1);
10946     V2 = DAG.getBitcast(FpVT, V2);
10947     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10948   }
10949
10950   switch (VT.SimpleTy) {
10951   case MVT::v4f64:
10952     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10953   case MVT::v4i64:
10954     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10955   case MVT::v8f32:
10956     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10957   case MVT::v8i32:
10958     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10959   case MVT::v16i16:
10960     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10961   case MVT::v32i8:
10962     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10963
10964   default:
10965     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10966   }
10967 }
10968
10969 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10970 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10971                                         ArrayRef<int> Mask,
10972                                         SDValue V1, SDValue V2,
10973                                         SelectionDAG &DAG) {
10974   assert(VT.getScalarSizeInBits() == 64 &&
10975          "Unexpected element type size for 128bit shuffle.");
10976
10977   // To handle 256 bit vector requires VLX and most probably
10978   // function lowerV2X128VectorShuffle() is better solution.
10979   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
10980
10981   SmallVector<int, 4> WidenedMask;
10982   if (!canWidenShuffleElements(Mask, WidenedMask))
10983     return SDValue();
10984
10985   // Form a 128-bit permutation.
10986   // Convert the 64-bit shuffle mask selection values into 128-bit selection
10987   // bits defined by a vshuf64x2 instruction's immediate control byte.
10988   unsigned PermMask = 0, Imm = 0;
10989   unsigned ControlBitsNum = WidenedMask.size() / 2;
10990
10991   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10992     if (WidenedMask[i] == SM_SentinelZero)
10993       return SDValue();
10994
10995     // Use first element in place of undef mask.
10996     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10997     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10998   }
10999
11000   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11001                      DAG.getConstant(PermMask, DL, MVT::i8));
11002 }
11003
11004 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11005                                            ArrayRef<int> Mask, SDValue V1,
11006                                            SDValue V2, SelectionDAG &DAG) {
11007
11008   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11009
11010   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11011   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11012
11013   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11014   if (isSingleInputShuffleMask(Mask))
11015     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11016
11017   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11018 }
11019
11020 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11021 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11022                                        const X86Subtarget *Subtarget,
11023                                        SelectionDAG &DAG) {
11024   SDLoc DL(Op);
11025   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11026   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11027   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11028   ArrayRef<int> Mask = SVOp->getMask();
11029   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11030
11031   if (SDValue Shuf128 =
11032           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11033     return Shuf128;
11034
11035   if (SDValue Unpck =
11036           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11037     return Unpck;
11038
11039   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11040 }
11041
11042 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11043 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11044                                         const X86Subtarget *Subtarget,
11045                                         SelectionDAG &DAG) {
11046   SDLoc DL(Op);
11047   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11048   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11049   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11050   ArrayRef<int> Mask = SVOp->getMask();
11051   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11052
11053   if (SDValue Unpck =
11054           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11055     return Unpck;
11056
11057   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11058 }
11059
11060 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11061 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11062                                        const X86Subtarget *Subtarget,
11063                                        SelectionDAG &DAG) {
11064   SDLoc DL(Op);
11065   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11066   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11067   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11068   ArrayRef<int> Mask = SVOp->getMask();
11069   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11070
11071   if (SDValue Shuf128 =
11072           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11073     return Shuf128;
11074
11075   if (SDValue Unpck =
11076           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11077     return Unpck;
11078
11079   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11080 }
11081
11082 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11083 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11084                                         const X86Subtarget *Subtarget,
11085                                         SelectionDAG &DAG) {
11086   SDLoc DL(Op);
11087   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11088   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11089   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11090   ArrayRef<int> Mask = SVOp->getMask();
11091   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11092
11093   if (SDValue Unpck =
11094           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11095     return Unpck;
11096
11097   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11098 }
11099
11100 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11101 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11102                                         const X86Subtarget *Subtarget,
11103                                         SelectionDAG &DAG) {
11104   SDLoc DL(Op);
11105   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11106   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11107   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11108   ArrayRef<int> Mask = SVOp->getMask();
11109   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11110   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11111
11112   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11113 }
11114
11115 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11116 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11117                                        const X86Subtarget *Subtarget,
11118                                        SelectionDAG &DAG) {
11119   SDLoc DL(Op);
11120   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11121   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11122   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11123   ArrayRef<int> Mask = SVOp->getMask();
11124   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11125   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11126
11127   // FIXME: Implement direct support for this type!
11128   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11129 }
11130
11131 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11132 ///
11133 /// This routine either breaks down the specific type of a 512-bit x86 vector
11134 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11135 /// together based on the available instructions.
11136 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11137                                         MVT VT, const X86Subtarget *Subtarget,
11138                                         SelectionDAG &DAG) {
11139   SDLoc DL(Op);
11140   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11141   ArrayRef<int> Mask = SVOp->getMask();
11142   assert(Subtarget->hasAVX512() &&
11143          "Cannot lower 512-bit vectors w/ basic ISA!");
11144
11145   // Check for being able to broadcast a single element.
11146   if (SDValue Broadcast =
11147           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11148     return Broadcast;
11149
11150   // Dispatch to each element type for lowering. If we don't have supprot for
11151   // specific element type shuffles at 512 bits, immediately split them and
11152   // lower them. Each lowering routine of a given type is allowed to assume that
11153   // the requisite ISA extensions for that element type are available.
11154   switch (VT.SimpleTy) {
11155   case MVT::v8f64:
11156     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11157   case MVT::v16f32:
11158     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11159   case MVT::v8i64:
11160     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11161   case MVT::v16i32:
11162     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11163   case MVT::v32i16:
11164     if (Subtarget->hasBWI())
11165       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11166     break;
11167   case MVT::v64i8:
11168     if (Subtarget->hasBWI())
11169       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11170     break;
11171
11172   default:
11173     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11174   }
11175
11176   // Otherwise fall back on splitting.
11177   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11178 }
11179
11180 // Lower vXi1 vector shuffles.
11181 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11182 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11183 // vector, shuffle and then truncate it back.
11184 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11185                                       MVT VT, const X86Subtarget *Subtarget,
11186                                       SelectionDAG &DAG) {
11187   SDLoc DL(Op);
11188   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11189   ArrayRef<int> Mask = SVOp->getMask();
11190   assert(Subtarget->hasAVX512() &&
11191          "Cannot lower 512-bit vectors w/o basic ISA!");
11192   MVT ExtVT;
11193   switch (VT.SimpleTy) {
11194   default:
11195     llvm_unreachable("Expected a vector of i1 elements");
11196   case MVT::v2i1:
11197     ExtVT = MVT::v2i64;
11198     break;
11199   case MVT::v4i1:
11200     ExtVT = MVT::v4i32;
11201     break;
11202   case MVT::v8i1:
11203     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11204     break;
11205   case MVT::v16i1:
11206     ExtVT = MVT::v16i32;
11207     break;
11208   case MVT::v32i1:
11209     ExtVT = MVT::v32i16;
11210     break;
11211   case MVT::v64i1:
11212     ExtVT = MVT::v64i8;
11213     break;
11214   }
11215
11216   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11217     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11218   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11219     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11220   else
11221     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11222
11223   if (V2.isUndef())
11224     V2 = DAG.getUNDEF(ExtVT);
11225   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11226     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11227   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11228     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11229   else
11230     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11231   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11232                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11233 }
11234 /// \brief Top-level lowering for x86 vector shuffles.
11235 ///
11236 /// This handles decomposition, canonicalization, and lowering of all x86
11237 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11238 /// above in helper routines. The canonicalization attempts to widen shuffles
11239 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11240 /// s.t. only one of the two inputs needs to be tested, etc.
11241 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11242                                   SelectionDAG &DAG) {
11243   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11244   ArrayRef<int> Mask = SVOp->getMask();
11245   SDValue V1 = Op.getOperand(0);
11246   SDValue V2 = Op.getOperand(1);
11247   MVT VT = Op.getSimpleValueType();
11248   int NumElements = VT.getVectorNumElements();
11249   SDLoc dl(Op);
11250   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11251
11252   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11253          "Can't lower MMX shuffles");
11254
11255   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11256   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11257   if (V1IsUndef && V2IsUndef)
11258     return DAG.getUNDEF(VT);
11259
11260   // When we create a shuffle node we put the UNDEF node to second operand,
11261   // but in some cases the first operand may be transformed to UNDEF.
11262   // In this case we should just commute the node.
11263   if (V1IsUndef)
11264     return DAG.getCommutedVectorShuffle(*SVOp);
11265
11266   // Check for non-undef masks pointing at an undef vector and make the masks
11267   // undef as well. This makes it easier to match the shuffle based solely on
11268   // the mask.
11269   if (V2IsUndef)
11270     for (int M : Mask)
11271       if (M >= NumElements) {
11272         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11273         for (int &M : NewMask)
11274           if (M >= NumElements)
11275             M = -1;
11276         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11277       }
11278
11279   // We actually see shuffles that are entirely re-arrangements of a set of
11280   // zero inputs. This mostly happens while decomposing complex shuffles into
11281   // simple ones. Directly lower these as a buildvector of zeros.
11282   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11283   if (Zeroable.all())
11284     return getZeroVector(VT, Subtarget, DAG, dl);
11285
11286   // Try to collapse shuffles into using a vector type with fewer elements but
11287   // wider element types. We cap this to not form integers or floating point
11288   // elements wider than 64 bits, but it might be interesting to form i128
11289   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11290   SmallVector<int, 16> WidenedMask;
11291   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11292       canWidenShuffleElements(Mask, WidenedMask)) {
11293     MVT NewEltVT = VT.isFloatingPoint()
11294                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11295                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11296     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11297     // Make sure that the new vector type is legal. For example, v2f64 isn't
11298     // legal on SSE1.
11299     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11300       V1 = DAG.getBitcast(NewVT, V1);
11301       V2 = DAG.getBitcast(NewVT, V2);
11302       return DAG.getBitcast(
11303           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11304     }
11305   }
11306
11307   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11308   for (int M : SVOp->getMask())
11309     if (M < 0)
11310       ++NumUndefElements;
11311     else if (M < NumElements)
11312       ++NumV1Elements;
11313     else
11314       ++NumV2Elements;
11315
11316   // Commute the shuffle as needed such that more elements come from V1 than
11317   // V2. This allows us to match the shuffle pattern strictly on how many
11318   // elements come from V1 without handling the symmetric cases.
11319   if (NumV2Elements > NumV1Elements)
11320     return DAG.getCommutedVectorShuffle(*SVOp);
11321
11322   // When the number of V1 and V2 elements are the same, try to minimize the
11323   // number of uses of V2 in the low half of the vector. When that is tied,
11324   // ensure that the sum of indices for V1 is equal to or lower than the sum
11325   // indices for V2. When those are equal, try to ensure that the number of odd
11326   // indices for V1 is lower than the number of odd indices for V2.
11327   if (NumV1Elements == NumV2Elements) {
11328     int LowV1Elements = 0, LowV2Elements = 0;
11329     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11330       if (M >= NumElements)
11331         ++LowV2Elements;
11332       else if (M >= 0)
11333         ++LowV1Elements;
11334     if (LowV2Elements > LowV1Elements) {
11335       return DAG.getCommutedVectorShuffle(*SVOp);
11336     } else if (LowV2Elements == LowV1Elements) {
11337       int SumV1Indices = 0, SumV2Indices = 0;
11338       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11339         if (SVOp->getMask()[i] >= NumElements)
11340           SumV2Indices += i;
11341         else if (SVOp->getMask()[i] >= 0)
11342           SumV1Indices += i;
11343       if (SumV2Indices < SumV1Indices) {
11344         return DAG.getCommutedVectorShuffle(*SVOp);
11345       } else if (SumV2Indices == SumV1Indices) {
11346         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11347         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11348           if (SVOp->getMask()[i] >= NumElements)
11349             NumV2OddIndices += i % 2;
11350           else if (SVOp->getMask()[i] >= 0)
11351             NumV1OddIndices += i % 2;
11352         if (NumV2OddIndices < NumV1OddIndices)
11353           return DAG.getCommutedVectorShuffle(*SVOp);
11354       }
11355     }
11356   }
11357
11358   // For each vector width, delegate to a specialized lowering routine.
11359   if (VT.is128BitVector())
11360     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11361
11362   if (VT.is256BitVector())
11363     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11364
11365   if (VT.is512BitVector())
11366     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11367
11368   if (Is1BitVector)
11369     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11370   llvm_unreachable("Unimplemented!");
11371 }
11372
11373 // This function assumes its argument is a BUILD_VECTOR of constants or
11374 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11375 // true.
11376 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11377                                     unsigned &MaskValue) {
11378   MaskValue = 0;
11379   unsigned NumElems = BuildVector->getNumOperands();
11380
11381   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11382   // We don't handle the >2 lanes case right now.
11383   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11384   if (NumLanes > 2)
11385     return false;
11386
11387   unsigned NumElemsInLane = NumElems / NumLanes;
11388
11389   // Blend for v16i16 should be symmetric for the both lanes.
11390   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11391     SDValue EltCond = BuildVector->getOperand(i);
11392     SDValue SndLaneEltCond =
11393         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11394
11395     int Lane1Cond = -1, Lane2Cond = -1;
11396     if (isa<ConstantSDNode>(EltCond))
11397       Lane1Cond = !isNullConstant(EltCond);
11398     if (isa<ConstantSDNode>(SndLaneEltCond))
11399       Lane2Cond = !isNullConstant(SndLaneEltCond);
11400
11401     unsigned LaneMask = 0;
11402     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11403       // Lane1Cond != 0, means we want the first argument.
11404       // Lane1Cond == 0, means we want the second argument.
11405       // The encoding of this argument is 0 for the first argument, 1
11406       // for the second. Therefore, invert the condition.
11407       LaneMask = !Lane1Cond << i;
11408     else if (Lane1Cond < 0)
11409       LaneMask = !Lane2Cond << i;
11410     else
11411       return false;
11412
11413     MaskValue |= LaneMask;
11414     if (NumLanes == 2)
11415       MaskValue |= LaneMask << NumElemsInLane;
11416   }
11417   return true;
11418 }
11419
11420 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11421 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11422                                            const X86Subtarget *Subtarget,
11423                                            SelectionDAG &DAG) {
11424   SDValue Cond = Op.getOperand(0);
11425   SDValue LHS = Op.getOperand(1);
11426   SDValue RHS = Op.getOperand(2);
11427   SDLoc dl(Op);
11428   MVT VT = Op.getSimpleValueType();
11429
11430   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11431     return SDValue();
11432   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11433
11434   // Only non-legal VSELECTs reach this lowering, convert those into generic
11435   // shuffles and re-use the shuffle lowering path for blends.
11436   SmallVector<int, 32> Mask;
11437   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11438     SDValue CondElt = CondBV->getOperand(i);
11439     Mask.push_back(
11440         isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11441                                      : -1);
11442   }
11443   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11444 }
11445
11446 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11447   // A vselect where all conditions and data are constants can be optimized into
11448   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11449   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11450       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11451       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11452     return SDValue();
11453
11454   // Try to lower this to a blend-style vector shuffle. This can handle all
11455   // constant condition cases.
11456   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11457     return BlendOp;
11458
11459   // Variable blends are only legal from SSE4.1 onward.
11460   if (!Subtarget->hasSSE41())
11461     return SDValue();
11462
11463   // Only some types will be legal on some subtargets. If we can emit a legal
11464   // VSELECT-matching blend, return Op, and but if we need to expand, return
11465   // a null value.
11466   switch (Op.getSimpleValueType().SimpleTy) {
11467   default:
11468     // Most of the vector types have blends past SSE4.1.
11469     return Op;
11470
11471   case MVT::v32i8:
11472     // The byte blends for AVX vectors were introduced only in AVX2.
11473     if (Subtarget->hasAVX2())
11474       return Op;
11475
11476     return SDValue();
11477
11478   case MVT::v8i16:
11479   case MVT::v16i16:
11480     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11481     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11482       return Op;
11483
11484     // FIXME: We should custom lower this by fixing the condition and using i8
11485     // blends.
11486     return SDValue();
11487   }
11488 }
11489
11490 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11491   MVT VT = Op.getSimpleValueType();
11492   SDLoc dl(Op);
11493
11494   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11495     return SDValue();
11496
11497   if (VT.getSizeInBits() == 8) {
11498     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11499                                   Op.getOperand(0), Op.getOperand(1));
11500     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11501                                   DAG.getValueType(VT));
11502     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11503   }
11504
11505   if (VT.getSizeInBits() == 16) {
11506     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11507     if (isNullConstant(Op.getOperand(1)))
11508       return DAG.getNode(
11509           ISD::TRUNCATE, dl, MVT::i16,
11510           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11511                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11512                       Op.getOperand(1)));
11513     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11514                                   Op.getOperand(0), Op.getOperand(1));
11515     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11516                                   DAG.getValueType(VT));
11517     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11518   }
11519
11520   if (VT == MVT::f32) {
11521     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11522     // the result back to FR32 register. It's only worth matching if the
11523     // result has a single use which is a store or a bitcast to i32.  And in
11524     // the case of a store, it's not worth it if the index is a constant 0,
11525     // because a MOVSSmr can be used instead, which is smaller and faster.
11526     if (!Op.hasOneUse())
11527       return SDValue();
11528     SDNode *User = *Op.getNode()->use_begin();
11529     if ((User->getOpcode() != ISD::STORE ||
11530          isNullConstant(Op.getOperand(1))) &&
11531         (User->getOpcode() != ISD::BITCAST ||
11532          User->getValueType(0) != MVT::i32))
11533       return SDValue();
11534     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11535                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11536                                   Op.getOperand(1));
11537     return DAG.getBitcast(MVT::f32, Extract);
11538   }
11539
11540   if (VT == MVT::i32 || VT == MVT::i64) {
11541     // ExtractPS/pextrq works with constant index.
11542     if (isa<ConstantSDNode>(Op.getOperand(1)))
11543       return Op;
11544   }
11545   return SDValue();
11546 }
11547
11548 /// Extract one bit from mask vector, like v16i1 or v8i1.
11549 /// AVX-512 feature.
11550 SDValue
11551 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11552   SDValue Vec = Op.getOperand(0);
11553   SDLoc dl(Vec);
11554   MVT VecVT = Vec.getSimpleValueType();
11555   SDValue Idx = Op.getOperand(1);
11556   MVT EltVT = Op.getSimpleValueType();
11557
11558   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11559   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11560          "Unexpected vector type in ExtractBitFromMaskVector");
11561
11562   // variable index can't be handled in mask registers,
11563   // extend vector to VR512
11564   if (!isa<ConstantSDNode>(Idx)) {
11565     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11566     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11567     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11568                               ExtVT.getVectorElementType(), Ext, Idx);
11569     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11570   }
11571
11572   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11573   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11574   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11575     rc = getRegClassFor(MVT::v16i1);
11576   unsigned MaxSift = rc->getSize()*8 - 1;
11577   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11578                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11579   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11580                     DAG.getConstant(MaxSift, dl, MVT::i8));
11581   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11582                        DAG.getIntPtrConstant(0, dl));
11583 }
11584
11585 SDValue
11586 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11587                                            SelectionDAG &DAG) const {
11588   SDLoc dl(Op);
11589   SDValue Vec = Op.getOperand(0);
11590   MVT VecVT = Vec.getSimpleValueType();
11591   SDValue Idx = Op.getOperand(1);
11592
11593   if (Op.getSimpleValueType() == MVT::i1)
11594     return ExtractBitFromMaskVector(Op, DAG);
11595
11596   if (!isa<ConstantSDNode>(Idx)) {
11597     if (VecVT.is512BitVector() ||
11598         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11599          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11600
11601       MVT MaskEltVT =
11602         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11603       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11604                                     MaskEltVT.getSizeInBits());
11605
11606       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11607       auto PtrVT = getPointerTy(DAG.getDataLayout());
11608       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11609                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11610                                  DAG.getConstant(0, dl, PtrVT));
11611       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11612       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11613                          DAG.getConstant(0, dl, PtrVT));
11614     }
11615     return SDValue();
11616   }
11617
11618   // If this is a 256-bit vector result, first extract the 128-bit vector and
11619   // then extract the element from the 128-bit vector.
11620   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11621
11622     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11623     // Get the 128-bit vector.
11624     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11625     MVT EltVT = VecVT.getVectorElementType();
11626
11627     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11628     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11629
11630     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11631     // this can be done with a mask.
11632     IdxVal &= ElemsPerChunk - 1;
11633     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11634                        DAG.getConstant(IdxVal, dl, MVT::i32));
11635   }
11636
11637   assert(VecVT.is128BitVector() && "Unexpected vector length");
11638
11639   if (Subtarget->hasSSE41())
11640     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11641       return Res;
11642
11643   MVT VT = Op.getSimpleValueType();
11644   // TODO: handle v16i8.
11645   if (VT.getSizeInBits() == 16) {
11646     SDValue Vec = Op.getOperand(0);
11647     if (isNullConstant(Op.getOperand(1)))
11648       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11649                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11650                                      DAG.getBitcast(MVT::v4i32, Vec),
11651                                      Op.getOperand(1)));
11652     // Transform it so it match pextrw which produces a 32-bit result.
11653     MVT EltVT = MVT::i32;
11654     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11655                                   Op.getOperand(0), Op.getOperand(1));
11656     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11657                                   DAG.getValueType(VT));
11658     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11659   }
11660
11661   if (VT.getSizeInBits() == 32) {
11662     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11663     if (Idx == 0)
11664       return Op;
11665
11666     // SHUFPS the element to the lowest double word, then movss.
11667     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11668     MVT VVT = Op.getOperand(0).getSimpleValueType();
11669     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11670                                        DAG.getUNDEF(VVT), Mask);
11671     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11672                        DAG.getIntPtrConstant(0, dl));
11673   }
11674
11675   if (VT.getSizeInBits() == 64) {
11676     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11677     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11678     //        to match extract_elt for f64.
11679     if (isNullConstant(Op.getOperand(1)))
11680       return Op;
11681
11682     // UNPCKHPD the element to the lowest double word, then movsd.
11683     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11684     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11685     int Mask[2] = { 1, -1 };
11686     MVT VVT = Op.getOperand(0).getSimpleValueType();
11687     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11688                                        DAG.getUNDEF(VVT), Mask);
11689     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11690                        DAG.getIntPtrConstant(0, dl));
11691   }
11692
11693   return SDValue();
11694 }
11695
11696 /// Insert one bit to mask vector, like v16i1 or v8i1.
11697 /// AVX-512 feature.
11698 SDValue
11699 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11700   SDLoc dl(Op);
11701   SDValue Vec = Op.getOperand(0);
11702   SDValue Elt = Op.getOperand(1);
11703   SDValue Idx = Op.getOperand(2);
11704   MVT VecVT = Vec.getSimpleValueType();
11705
11706   if (!isa<ConstantSDNode>(Idx)) {
11707     // Non constant index. Extend source and destination,
11708     // insert element and then truncate the result.
11709     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11710     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11711     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11712       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11713       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11714     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11715   }
11716
11717   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11718   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11719   if (IdxVal)
11720     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11721                            DAG.getConstant(IdxVal, dl, MVT::i8));
11722   if (Vec.getOpcode() == ISD::UNDEF)
11723     return EltInVec;
11724   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11725 }
11726
11727 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11728                                                   SelectionDAG &DAG) const {
11729   MVT VT = Op.getSimpleValueType();
11730   MVT EltVT = VT.getVectorElementType();
11731
11732   if (EltVT == MVT::i1)
11733     return InsertBitToMaskVector(Op, DAG);
11734
11735   SDLoc dl(Op);
11736   SDValue N0 = Op.getOperand(0);
11737   SDValue N1 = Op.getOperand(1);
11738   SDValue N2 = Op.getOperand(2);
11739   if (!isa<ConstantSDNode>(N2))
11740     return SDValue();
11741   auto *N2C = cast<ConstantSDNode>(N2);
11742   unsigned IdxVal = N2C->getZExtValue();
11743
11744   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11745   // into that, and then insert the subvector back into the result.
11746   if (VT.is256BitVector() || VT.is512BitVector()) {
11747     // With a 256-bit vector, we can insert into the zero element efficiently
11748     // using a blend if we have AVX or AVX2 and the right data type.
11749     if (VT.is256BitVector() && IdxVal == 0) {
11750       // TODO: It is worthwhile to cast integer to floating point and back
11751       // and incur a domain crossing penalty if that's what we'll end up
11752       // doing anyway after extracting to a 128-bit vector.
11753       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11754           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11755         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11756         N2 = DAG.getIntPtrConstant(1, dl);
11757         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11758       }
11759     }
11760
11761     // Get the desired 128-bit vector chunk.
11762     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11763
11764     // Insert the element into the desired chunk.
11765     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11766     assert(isPowerOf2_32(NumEltsIn128));
11767     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11768     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11769
11770     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11771                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11772
11773     // Insert the changed part back into the bigger vector
11774     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11775   }
11776   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11777
11778   if (Subtarget->hasSSE41()) {
11779     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11780       unsigned Opc;
11781       if (VT == MVT::v8i16) {
11782         Opc = X86ISD::PINSRW;
11783       } else {
11784         assert(VT == MVT::v16i8);
11785         Opc = X86ISD::PINSRB;
11786       }
11787
11788       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11789       // argument.
11790       if (N1.getValueType() != MVT::i32)
11791         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11792       if (N2.getValueType() != MVT::i32)
11793         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11794       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11795     }
11796
11797     if (EltVT == MVT::f32) {
11798       // Bits [7:6] of the constant are the source select. This will always be
11799       //   zero here. The DAG Combiner may combine an extract_elt index into
11800       //   these bits. For example (insert (extract, 3), 2) could be matched by
11801       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11802       // Bits [5:4] of the constant are the destination select. This is the
11803       //   value of the incoming immediate.
11804       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11805       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11806
11807       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11808       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11809         // If this is an insertion of 32-bits into the low 32-bits of
11810         // a vector, we prefer to generate a blend with immediate rather
11811         // than an insertps. Blends are simpler operations in hardware and so
11812         // will always have equal or better performance than insertps.
11813         // But if optimizing for size and there's a load folding opportunity,
11814         // generate insertps because blendps does not have a 32-bit memory
11815         // operand form.
11816         N2 = DAG.getIntPtrConstant(1, dl);
11817         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11818         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11819       }
11820       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11821       // Create this as a scalar to vector..
11822       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11823       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11824     }
11825
11826     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11827       // PINSR* works with constant index.
11828       return Op;
11829     }
11830   }
11831
11832   if (EltVT == MVT::i8)
11833     return SDValue();
11834
11835   if (EltVT.getSizeInBits() == 16) {
11836     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11837     // as its second argument.
11838     if (N1.getValueType() != MVT::i32)
11839       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11840     if (N2.getValueType() != MVT::i32)
11841       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11842     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11843   }
11844   return SDValue();
11845 }
11846
11847 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11848   SDLoc dl(Op);
11849   MVT OpVT = Op.getSimpleValueType();
11850
11851   // If this is a 256-bit vector result, first insert into a 128-bit
11852   // vector and then insert into the 256-bit vector.
11853   if (!OpVT.is128BitVector()) {
11854     // Insert into a 128-bit vector.
11855     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11856     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11857                                  OpVT.getVectorNumElements() / SizeFactor);
11858
11859     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11860
11861     // Insert the 128-bit vector.
11862     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11863   }
11864
11865   if (OpVT == MVT::v1i64 &&
11866       Op.getOperand(0).getValueType() == MVT::i64)
11867     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11868
11869   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11870   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11871   return DAG.getBitcast(
11872       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11873 }
11874
11875 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11876 // a simple subregister reference or explicit instructions to grab
11877 // upper bits of a vector.
11878 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11879                                       SelectionDAG &DAG) {
11880   SDLoc dl(Op);
11881   SDValue In =  Op.getOperand(0);
11882   SDValue Idx = Op.getOperand(1);
11883   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11884   MVT ResVT   = Op.getSimpleValueType();
11885   MVT InVT    = In.getSimpleValueType();
11886
11887   if (Subtarget->hasFp256()) {
11888     if (ResVT.is128BitVector() &&
11889         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11890         isa<ConstantSDNode>(Idx)) {
11891       return Extract128BitVector(In, IdxVal, DAG, dl);
11892     }
11893     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11894         isa<ConstantSDNode>(Idx)) {
11895       return Extract256BitVector(In, IdxVal, DAG, dl);
11896     }
11897   }
11898   return SDValue();
11899 }
11900
11901 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11902 // simple superregister reference or explicit instructions to insert
11903 // the upper bits of a vector.
11904 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11905                                      SelectionDAG &DAG) {
11906   if (!Subtarget->hasAVX())
11907     return SDValue();
11908
11909   SDLoc dl(Op);
11910   SDValue Vec = Op.getOperand(0);
11911   SDValue SubVec = Op.getOperand(1);
11912   SDValue Idx = Op.getOperand(2);
11913
11914   if (!isa<ConstantSDNode>(Idx))
11915     return SDValue();
11916
11917   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11918   MVT OpVT = Op.getSimpleValueType();
11919   MVT SubVecVT = SubVec.getSimpleValueType();
11920
11921   // Fold two 16-byte subvector loads into one 32-byte load:
11922   // (insert_subvector (insert_subvector undef, (load addr), 0),
11923   //                   (load addr + 16), Elts/2)
11924   // --> load32 addr
11925   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11926       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11927       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11928     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11929     if (Idx2 && Idx2->getZExtValue() == 0) {
11930       SDValue SubVec2 = Vec.getOperand(1);
11931       // If needed, look through a bitcast to get to the load.
11932       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11933         SubVec2 = SubVec2.getOperand(0);
11934
11935       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11936         bool Fast;
11937         unsigned Alignment = FirstLd->getAlignment();
11938         unsigned AS = FirstLd->getAddressSpace();
11939         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11940         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11941                                     OpVT, AS, Alignment, &Fast) && Fast) {
11942           SDValue Ops[] = { SubVec2, SubVec };
11943           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11944             return Ld;
11945         }
11946       }
11947     }
11948   }
11949
11950   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11951       SubVecVT.is128BitVector())
11952     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11953
11954   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11955     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11956
11957   if (OpVT.getVectorElementType() == MVT::i1)
11958     return Insert1BitVector(Op, DAG);
11959
11960   return SDValue();
11961 }
11962
11963 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11964 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11965 // one of the above mentioned nodes. It has to be wrapped because otherwise
11966 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11967 // be used to form addressing mode. These wrapped nodes will be selected
11968 // into MOV32ri.
11969 SDValue
11970 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11971   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11972
11973   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11974   // global base reg.
11975   unsigned char OpFlag = 0;
11976   unsigned WrapperKind = X86ISD::Wrapper;
11977   CodeModel::Model M = DAG.getTarget().getCodeModel();
11978
11979   if (Subtarget->isPICStyleRIPRel() &&
11980       (M == CodeModel::Small || M == CodeModel::Kernel))
11981     WrapperKind = X86ISD::WrapperRIP;
11982   else if (Subtarget->isPICStyleGOT())
11983     OpFlag = X86II::MO_GOTOFF;
11984   else if (Subtarget->isPICStyleStubPIC())
11985     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11986
11987   auto PtrVT = getPointerTy(DAG.getDataLayout());
11988   SDValue Result = DAG.getTargetConstantPool(
11989       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11990   SDLoc DL(CP);
11991   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11992   // With PIC, the address is actually $g + Offset.
11993   if (OpFlag) {
11994     Result =
11995         DAG.getNode(ISD::ADD, DL, PtrVT,
11996                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11997   }
11998
11999   return Result;
12000 }
12001
12002 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12003   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12004
12005   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12006   // global base reg.
12007   unsigned char OpFlag = 0;
12008   unsigned WrapperKind = X86ISD::Wrapper;
12009   CodeModel::Model M = DAG.getTarget().getCodeModel();
12010
12011   if (Subtarget->isPICStyleRIPRel() &&
12012       (M == CodeModel::Small || M == CodeModel::Kernel))
12013     WrapperKind = X86ISD::WrapperRIP;
12014   else if (Subtarget->isPICStyleGOT())
12015     OpFlag = X86II::MO_GOTOFF;
12016   else if (Subtarget->isPICStyleStubPIC())
12017     OpFlag = X86II::MO_PIC_BASE_OFFSET;
12018
12019   auto PtrVT = getPointerTy(DAG.getDataLayout());
12020   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12021   SDLoc DL(JT);
12022   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12023
12024   // With PIC, the address is actually $g + Offset.
12025   if (OpFlag)
12026     Result =
12027         DAG.getNode(ISD::ADD, DL, PtrVT,
12028                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12029
12030   return Result;
12031 }
12032
12033 SDValue
12034 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12035   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12036
12037   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12038   // global base reg.
12039   unsigned char OpFlag = 0;
12040   unsigned WrapperKind = X86ISD::Wrapper;
12041   CodeModel::Model M = DAG.getTarget().getCodeModel();
12042
12043   if (Subtarget->isPICStyleRIPRel() &&
12044       (M == CodeModel::Small || M == CodeModel::Kernel)) {
12045     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12046       OpFlag = X86II::MO_GOTPCREL;
12047     WrapperKind = X86ISD::WrapperRIP;
12048   } else if (Subtarget->isPICStyleGOT()) {
12049     OpFlag = X86II::MO_GOT;
12050   } else if (Subtarget->isPICStyleStubPIC()) {
12051     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12052   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12053     OpFlag = X86II::MO_DARWIN_NONLAZY;
12054   }
12055
12056   auto PtrVT = getPointerTy(DAG.getDataLayout());
12057   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12058
12059   SDLoc DL(Op);
12060   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12061
12062   // With PIC, the address is actually $g + Offset.
12063   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12064       !Subtarget->is64Bit()) {
12065     Result =
12066         DAG.getNode(ISD::ADD, DL, PtrVT,
12067                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12068   }
12069
12070   // For symbols that require a load from a stub to get the address, emit the
12071   // load.
12072   if (isGlobalStubReference(OpFlag))
12073     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12074                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12075                          false, false, false, 0);
12076
12077   return Result;
12078 }
12079
12080 SDValue
12081 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12082   // Create the TargetBlockAddressAddress node.
12083   unsigned char OpFlags =
12084     Subtarget->ClassifyBlockAddressReference();
12085   CodeModel::Model M = DAG.getTarget().getCodeModel();
12086   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12087   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12088   SDLoc dl(Op);
12089   auto PtrVT = getPointerTy(DAG.getDataLayout());
12090   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12091
12092   if (Subtarget->isPICStyleRIPRel() &&
12093       (M == CodeModel::Small || M == CodeModel::Kernel))
12094     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12095   else
12096     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12097
12098   // With PIC, the address is actually $g + Offset.
12099   if (isGlobalRelativeToPICBase(OpFlags)) {
12100     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12101                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12102   }
12103
12104   return Result;
12105 }
12106
12107 SDValue
12108 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12109                                       int64_t Offset, SelectionDAG &DAG) const {
12110   // Create the TargetGlobalAddress node, folding in the constant
12111   // offset if it is legal.
12112   unsigned char OpFlags =
12113       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12114   CodeModel::Model M = DAG.getTarget().getCodeModel();
12115   auto PtrVT = getPointerTy(DAG.getDataLayout());
12116   SDValue Result;
12117   if (OpFlags == X86II::MO_NO_FLAG &&
12118       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12119     // A direct static reference to a global.
12120     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12121     Offset = 0;
12122   } else {
12123     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12124   }
12125
12126   if (Subtarget->isPICStyleRIPRel() &&
12127       (M == CodeModel::Small || M == CodeModel::Kernel))
12128     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12129   else
12130     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12131
12132   // With PIC, the address is actually $g + Offset.
12133   if (isGlobalRelativeToPICBase(OpFlags)) {
12134     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12135                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12136   }
12137
12138   // For globals that require a load from a stub to get the address, emit the
12139   // load.
12140   if (isGlobalStubReference(OpFlags))
12141     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12142                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12143                          false, false, false, 0);
12144
12145   // If there was a non-zero offset that we didn't fold, create an explicit
12146   // addition for it.
12147   if (Offset != 0)
12148     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12149                          DAG.getConstant(Offset, dl, PtrVT));
12150
12151   return Result;
12152 }
12153
12154 SDValue
12155 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12156   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12157   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12158   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12159 }
12160
12161 static SDValue
12162 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12163            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12164            unsigned char OperandFlags, bool LocalDynamic = false) {
12165   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12166   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12167   SDLoc dl(GA);
12168   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12169                                            GA->getValueType(0),
12170                                            GA->getOffset(),
12171                                            OperandFlags);
12172
12173   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12174                                            : X86ISD::TLSADDR;
12175
12176   if (InFlag) {
12177     SDValue Ops[] = { Chain,  TGA, *InFlag };
12178     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12179   } else {
12180     SDValue Ops[]  = { Chain, TGA };
12181     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12182   }
12183
12184   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12185   MFI->setAdjustsStack(true);
12186   MFI->setHasCalls(true);
12187
12188   SDValue Flag = Chain.getValue(1);
12189   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12190 }
12191
12192 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12193 static SDValue
12194 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12195                                 const EVT PtrVT) {
12196   SDValue InFlag;
12197   SDLoc dl(GA);  // ? function entry point might be better
12198   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12199                                    DAG.getNode(X86ISD::GlobalBaseReg,
12200                                                SDLoc(), PtrVT), InFlag);
12201   InFlag = Chain.getValue(1);
12202
12203   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12204 }
12205
12206 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12207 static SDValue
12208 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12209                                 const EVT PtrVT) {
12210   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12211                     X86::RAX, X86II::MO_TLSGD);
12212 }
12213
12214 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12215                                            SelectionDAG &DAG,
12216                                            const EVT PtrVT,
12217                                            bool is64Bit) {
12218   SDLoc dl(GA);
12219
12220   // Get the start address of the TLS block for this module.
12221   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12222       .getInfo<X86MachineFunctionInfo>();
12223   MFI->incNumLocalDynamicTLSAccesses();
12224
12225   SDValue Base;
12226   if (is64Bit) {
12227     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12228                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12229   } else {
12230     SDValue InFlag;
12231     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12232         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12233     InFlag = Chain.getValue(1);
12234     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12235                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12236   }
12237
12238   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12239   // of Base.
12240
12241   // Build x@dtpoff.
12242   unsigned char OperandFlags = X86II::MO_DTPOFF;
12243   unsigned WrapperKind = X86ISD::Wrapper;
12244   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12245                                            GA->getValueType(0),
12246                                            GA->getOffset(), OperandFlags);
12247   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12248
12249   // Add x@dtpoff with the base.
12250   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12251 }
12252
12253 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12254 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12255                                    const EVT PtrVT, TLSModel::Model model,
12256                                    bool is64Bit, bool isPIC) {
12257   SDLoc dl(GA);
12258
12259   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12260   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12261                                                          is64Bit ? 257 : 256));
12262
12263   SDValue ThreadPointer =
12264       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12265                   MachinePointerInfo(Ptr), false, false, false, 0);
12266
12267   unsigned char OperandFlags = 0;
12268   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12269   // initialexec.
12270   unsigned WrapperKind = X86ISD::Wrapper;
12271   if (model == TLSModel::LocalExec) {
12272     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12273   } else if (model == TLSModel::InitialExec) {
12274     if (is64Bit) {
12275       OperandFlags = X86II::MO_GOTTPOFF;
12276       WrapperKind = X86ISD::WrapperRIP;
12277     } else {
12278       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12279     }
12280   } else {
12281     llvm_unreachable("Unexpected model");
12282   }
12283
12284   // emit "addl x@ntpoff,%eax" (local exec)
12285   // or "addl x@indntpoff,%eax" (initial exec)
12286   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12287   SDValue TGA =
12288       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12289                                  GA->getOffset(), OperandFlags);
12290   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12291
12292   if (model == TLSModel::InitialExec) {
12293     if (isPIC && !is64Bit) {
12294       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12295                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12296                            Offset);
12297     }
12298
12299     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12300                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12301                          false, false, false, 0);
12302   }
12303
12304   // The address of the thread local variable is the add of the thread
12305   // pointer with the offset of the variable.
12306   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12307 }
12308
12309 SDValue
12310 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12311
12312   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12313
12314   // Cygwin uses emutls.
12315   // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12316   if (Subtarget->isTargetWindowsCygwin())
12317     return LowerToTLSEmulatedModel(GA, DAG);
12318
12319   const GlobalValue *GV = GA->getGlobal();
12320   auto PtrVT = getPointerTy(DAG.getDataLayout());
12321
12322   if (Subtarget->isTargetELF()) {
12323     if (DAG.getTarget().Options.EmulatedTLS)
12324       return LowerToTLSEmulatedModel(GA, DAG);
12325     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12326     switch (model) {
12327       case TLSModel::GeneralDynamic:
12328         if (Subtarget->is64Bit())
12329           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12330         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12331       case TLSModel::LocalDynamic:
12332         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12333                                            Subtarget->is64Bit());
12334       case TLSModel::InitialExec:
12335       case TLSModel::LocalExec:
12336         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12337                                    DAG.getTarget().getRelocationModel() ==
12338                                        Reloc::PIC_);
12339     }
12340     llvm_unreachable("Unknown TLS model.");
12341   }
12342
12343   if (Subtarget->isTargetDarwin()) {
12344     // Darwin only has one model of TLS.  Lower to that.
12345     unsigned char OpFlag = 0;
12346     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12347                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12348
12349     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12350     // global base reg.
12351     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12352                  !Subtarget->is64Bit();
12353     if (PIC32)
12354       OpFlag = X86II::MO_TLVP_PIC_BASE;
12355     else
12356       OpFlag = X86II::MO_TLVP;
12357     SDLoc DL(Op);
12358     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12359                                                 GA->getValueType(0),
12360                                                 GA->getOffset(), OpFlag);
12361     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12362
12363     // With PIC32, the address is actually $g + Offset.
12364     if (PIC32)
12365       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12366                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12367                            Offset);
12368
12369     // Lowering the machine isd will make sure everything is in the right
12370     // location.
12371     SDValue Chain = DAG.getEntryNode();
12372     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12373     SDValue Args[] = { Chain, Offset };
12374     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12375
12376     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12377     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12378     MFI->setAdjustsStack(true);
12379
12380     // And our return value (tls address) is in the standard call return value
12381     // location.
12382     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12383     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12384   }
12385
12386   if (Subtarget->isTargetKnownWindowsMSVC() ||
12387       Subtarget->isTargetWindowsGNU()) {
12388     // Just use the implicit TLS architecture
12389     // Need to generate someting similar to:
12390     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12391     //                                  ; from TEB
12392     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12393     //   mov     rcx, qword [rdx+rcx*8]
12394     //   mov     eax, .tls$:tlsvar
12395     //   [rax+rcx] contains the address
12396     // Windows 64bit: gs:0x58
12397     // Windows 32bit: fs:__tls_array
12398
12399     SDLoc dl(GA);
12400     SDValue Chain = DAG.getEntryNode();
12401
12402     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12403     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12404     // use its literal value of 0x2C.
12405     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12406                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12407                                                              256)
12408                                         : Type::getInt32PtrTy(*DAG.getContext(),
12409                                                               257));
12410
12411     SDValue TlsArray = Subtarget->is64Bit()
12412                            ? DAG.getIntPtrConstant(0x58, dl)
12413                            : (Subtarget->isTargetWindowsGNU()
12414                                   ? DAG.getIntPtrConstant(0x2C, dl)
12415                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12416
12417     SDValue ThreadPointer =
12418         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12419                     false, false, 0);
12420
12421     SDValue res;
12422     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12423       res = ThreadPointer;
12424     } else {
12425       // Load the _tls_index variable
12426       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12427       if (Subtarget->is64Bit())
12428         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12429                              MachinePointerInfo(), MVT::i32, false, false,
12430                              false, 0);
12431       else
12432         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12433                           false, false, 0);
12434
12435       auto &DL = DAG.getDataLayout();
12436       SDValue Scale =
12437           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12438       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12439
12440       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12441     }
12442
12443     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12444                       false, 0);
12445
12446     // Get the offset of start of .tls section
12447     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12448                                              GA->getValueType(0),
12449                                              GA->getOffset(), X86II::MO_SECREL);
12450     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12451
12452     // The address of the thread local variable is the add of the thread
12453     // pointer with the offset of the variable.
12454     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12455   }
12456
12457   llvm_unreachable("TLS not implemented for this target.");
12458 }
12459
12460 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12461 /// and take a 2 x i32 value to shift plus a shift amount.
12462 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12463   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12464   MVT VT = Op.getSimpleValueType();
12465   unsigned VTBits = VT.getSizeInBits();
12466   SDLoc dl(Op);
12467   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12468   SDValue ShOpLo = Op.getOperand(0);
12469   SDValue ShOpHi = Op.getOperand(1);
12470   SDValue ShAmt  = Op.getOperand(2);
12471   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12472   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12473   // during isel.
12474   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12475                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12476   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12477                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12478                        : DAG.getConstant(0, dl, VT);
12479
12480   SDValue Tmp2, Tmp3;
12481   if (Op.getOpcode() == ISD::SHL_PARTS) {
12482     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12483     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12484   } else {
12485     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12486     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12487   }
12488
12489   // If the shift amount is larger or equal than the width of a part we can't
12490   // rely on the results of shld/shrd. Insert a test and select the appropriate
12491   // values for large shift amounts.
12492   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12493                                 DAG.getConstant(VTBits, dl, MVT::i8));
12494   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12495                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12496
12497   SDValue Hi, Lo;
12498   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12499   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12500   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12501
12502   if (Op.getOpcode() == ISD::SHL_PARTS) {
12503     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12504     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12505   } else {
12506     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12507     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12508   }
12509
12510   SDValue Ops[2] = { Lo, Hi };
12511   return DAG.getMergeValues(Ops, dl);
12512 }
12513
12514 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12515                                            SelectionDAG &DAG) const {
12516   SDValue Src = Op.getOperand(0);
12517   MVT SrcVT = Src.getSimpleValueType();
12518   MVT VT = Op.getSimpleValueType();
12519   SDLoc dl(Op);
12520
12521   if (SrcVT.isVector()) {
12522     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12523       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12524                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12525                          DAG.getUNDEF(SrcVT)));
12526     }
12527     if (SrcVT.getVectorElementType() == MVT::i1) {
12528       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12529       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12530                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12531     }
12532     return SDValue();
12533   }
12534
12535   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12536          "Unknown SINT_TO_FP to lower!");
12537
12538   // These are really Legal; return the operand so the caller accepts it as
12539   // Legal.
12540   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12541     return Op;
12542   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12543       Subtarget->is64Bit()) {
12544     return Op;
12545   }
12546
12547   unsigned Size = SrcVT.getSizeInBits()/8;
12548   MachineFunction &MF = DAG.getMachineFunction();
12549   auto PtrVT = getPointerTy(MF.getDataLayout());
12550   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12551   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12552   SDValue Chain = DAG.getStore(
12553       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12554       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12555       false, 0);
12556   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12557 }
12558
12559 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12560                                      SDValue StackSlot,
12561                                      SelectionDAG &DAG) const {
12562   // Build the FILD
12563   SDLoc DL(Op);
12564   SDVTList Tys;
12565   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12566   if (useSSE)
12567     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12568   else
12569     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12570
12571   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12572
12573   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12574   MachineMemOperand *MMO;
12575   if (FI) {
12576     int SSFI = FI->getIndex();
12577     MMO = DAG.getMachineFunction().getMachineMemOperand(
12578         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12579         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12580   } else {
12581     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12582     StackSlot = StackSlot.getOperand(1);
12583   }
12584   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12585   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12586                                            X86ISD::FILD, DL,
12587                                            Tys, Ops, SrcVT, MMO);
12588
12589   if (useSSE) {
12590     Chain = Result.getValue(1);
12591     SDValue InFlag = Result.getValue(2);
12592
12593     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12594     // shouldn't be necessary except that RFP cannot be live across
12595     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12596     MachineFunction &MF = DAG.getMachineFunction();
12597     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12598     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12599     auto PtrVT = getPointerTy(MF.getDataLayout());
12600     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12601     Tys = DAG.getVTList(MVT::Other);
12602     SDValue Ops[] = {
12603       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12604     };
12605     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12606         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12607         MachineMemOperand::MOStore, SSFISize, SSFISize);
12608
12609     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12610                                     Ops, Op.getValueType(), MMO);
12611     Result = DAG.getLoad(
12612         Op.getValueType(), DL, Chain, StackSlot,
12613         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12614         false, false, false, 0);
12615   }
12616
12617   return Result;
12618 }
12619
12620 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12621 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12622                                                SelectionDAG &DAG) const {
12623   // This algorithm is not obvious. Here it is what we're trying to output:
12624   /*
12625      movq       %rax,  %xmm0
12626      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12627      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12628      #ifdef __SSE3__
12629        haddpd   %xmm0, %xmm0
12630      #else
12631        pshufd   $0x4e, %xmm0, %xmm1
12632        addpd    %xmm1, %xmm0
12633      #endif
12634   */
12635
12636   SDLoc dl(Op);
12637   LLVMContext *Context = DAG.getContext();
12638
12639   // Build some magic constants.
12640   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12641   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12642   auto PtrVT = getPointerTy(DAG.getDataLayout());
12643   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12644
12645   SmallVector<Constant*,2> CV1;
12646   CV1.push_back(
12647     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12648                                       APInt(64, 0x4330000000000000ULL))));
12649   CV1.push_back(
12650     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12651                                       APInt(64, 0x4530000000000000ULL))));
12652   Constant *C1 = ConstantVector::get(CV1);
12653   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12654
12655   // Load the 64-bit value into an XMM register.
12656   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12657                             Op.getOperand(0));
12658   SDValue CLod0 =
12659       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12660                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12661                   false, false, false, 16);
12662   SDValue Unpck1 =
12663       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12664
12665   SDValue CLod1 =
12666       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12667                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12668                   false, false, false, 16);
12669   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12670   // TODO: Are there any fast-math-flags to propagate here?
12671   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12672   SDValue Result;
12673
12674   if (Subtarget->hasSSE3()) {
12675     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12676     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12677   } else {
12678     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12679     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12680                                            S2F, 0x4E, DAG);
12681     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12682                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12683   }
12684
12685   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12686                      DAG.getIntPtrConstant(0, dl));
12687 }
12688
12689 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12690 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12691                                                SelectionDAG &DAG) const {
12692   SDLoc dl(Op);
12693   // FP constant to bias correct the final result.
12694   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12695                                    MVT::f64);
12696
12697   // Load the 32-bit value into an XMM register.
12698   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12699                              Op.getOperand(0));
12700
12701   // Zero out the upper parts of the register.
12702   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12703
12704   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12705                      DAG.getBitcast(MVT::v2f64, Load),
12706                      DAG.getIntPtrConstant(0, dl));
12707
12708   // Or the load with the bias.
12709   SDValue Or = DAG.getNode(
12710       ISD::OR, dl, MVT::v2i64,
12711       DAG.getBitcast(MVT::v2i64,
12712                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12713       DAG.getBitcast(MVT::v2i64,
12714                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12715   Or =
12716       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12717                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12718
12719   // Subtract the bias.
12720   // TODO: Are there any fast-math-flags to propagate here?
12721   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12722
12723   // Handle final rounding.
12724   MVT DestVT = Op.getSimpleValueType();
12725
12726   if (DestVT.bitsLT(MVT::f64))
12727     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12728                        DAG.getIntPtrConstant(0, dl));
12729   if (DestVT.bitsGT(MVT::f64))
12730     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12731
12732   // Handle final rounding.
12733   return Sub;
12734 }
12735
12736 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12737                                      const X86Subtarget &Subtarget) {
12738   // The algorithm is the following:
12739   // #ifdef __SSE4_1__
12740   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12741   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12742   //                                 (uint4) 0x53000000, 0xaa);
12743   // #else
12744   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12745   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12746   // #endif
12747   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12748   //     return (float4) lo + fhi;
12749
12750   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12751   // reassociate the two FADDs, and if we do that, the algorithm fails
12752   // spectacularly (PR24512).
12753   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12754   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12755   // there's also the MachineCombiner reassociations happening on Machine IR.
12756   if (DAG.getTarget().Options.UnsafeFPMath)
12757     return SDValue();
12758
12759   SDLoc DL(Op);
12760   SDValue V = Op->getOperand(0);
12761   MVT VecIntVT = V.getSimpleValueType();
12762   bool Is128 = VecIntVT == MVT::v4i32;
12763   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12764   // If we convert to something else than the supported type, e.g., to v4f64,
12765   // abort early.
12766   if (VecFloatVT != Op->getSimpleValueType(0))
12767     return SDValue();
12768
12769   unsigned NumElts = VecIntVT.getVectorNumElements();
12770   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12771          "Unsupported custom type");
12772   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12773
12774   // In the #idef/#else code, we have in common:
12775   // - The vector of constants:
12776   // -- 0x4b000000
12777   // -- 0x53000000
12778   // - A shift:
12779   // -- v >> 16
12780
12781   // Create the splat vector for 0x4b000000.
12782   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12783   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12784                            CstLow, CstLow, CstLow, CstLow};
12785   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12786                                   makeArrayRef(&CstLowArray[0], NumElts));
12787   // Create the splat vector for 0x53000000.
12788   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12789   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12790                             CstHigh, CstHigh, CstHigh, CstHigh};
12791   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12792                                    makeArrayRef(&CstHighArray[0], NumElts));
12793
12794   // Create the right shift.
12795   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12796   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12797                              CstShift, CstShift, CstShift, CstShift};
12798   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12799                                     makeArrayRef(&CstShiftArray[0], NumElts));
12800   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12801
12802   SDValue Low, High;
12803   if (Subtarget.hasSSE41()) {
12804     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12805     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12806     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12807     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12808     // Low will be bitcasted right away, so do not bother bitcasting back to its
12809     // original type.
12810     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12811                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12812     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12813     //                                 (uint4) 0x53000000, 0xaa);
12814     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12815     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12816     // High will be bitcasted right away, so do not bother bitcasting back to
12817     // its original type.
12818     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12819                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12820   } else {
12821     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12822     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12823                                      CstMask, CstMask, CstMask);
12824     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12825     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12826     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12827
12828     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12829     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12830   }
12831
12832   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12833   SDValue CstFAdd = DAG.getConstantFP(
12834       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12835   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12836                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12837   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12838                                    makeArrayRef(&CstFAddArray[0], NumElts));
12839
12840   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12841   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12842   // TODO: Are there any fast-math-flags to propagate here?
12843   SDValue FHigh =
12844       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12845   //     return (float4) lo + fhi;
12846   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12847   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12848 }
12849
12850 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12851                                                SelectionDAG &DAG) const {
12852   SDValue N0 = Op.getOperand(0);
12853   MVT SVT = N0.getSimpleValueType();
12854   SDLoc dl(Op);
12855
12856   switch (SVT.SimpleTy) {
12857   default:
12858     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12859   case MVT::v4i8:
12860   case MVT::v4i16:
12861   case MVT::v8i8:
12862   case MVT::v8i16: {
12863     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12864     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12865                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12866   }
12867   case MVT::v4i32:
12868   case MVT::v8i32:
12869     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12870   case MVT::v16i8:
12871   case MVT::v16i16:
12872     assert(Subtarget->hasAVX512());
12873     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12874                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12875   }
12876 }
12877
12878 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12879                                            SelectionDAG &DAG) const {
12880   SDValue N0 = Op.getOperand(0);
12881   SDLoc dl(Op);
12882   auto PtrVT = getPointerTy(DAG.getDataLayout());
12883
12884   if (Op.getSimpleValueType().isVector())
12885     return lowerUINT_TO_FP_vec(Op, DAG);
12886
12887   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12888   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12889   // the optimization here.
12890   if (DAG.SignBitIsZero(N0))
12891     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12892
12893   MVT SrcVT = N0.getSimpleValueType();
12894   MVT DstVT = Op.getSimpleValueType();
12895
12896   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12897       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12898     // Conversions from unsigned i32 to f32/f64 are legal,
12899     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12900     return Op;
12901   }
12902
12903   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12904     return LowerUINT_TO_FP_i64(Op, DAG);
12905   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12906     return LowerUINT_TO_FP_i32(Op, DAG);
12907   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12908     return SDValue();
12909
12910   // Make a 64-bit buffer, and use it to build an FILD.
12911   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12912   if (SrcVT == MVT::i32) {
12913     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12914     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12915     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12916                                   StackSlot, MachinePointerInfo(),
12917                                   false, false, 0);
12918     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12919                                   OffsetSlot, MachinePointerInfo(),
12920                                   false, false, 0);
12921     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12922     return Fild;
12923   }
12924
12925   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12926   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12927                                StackSlot, MachinePointerInfo(),
12928                                false, false, 0);
12929   // For i64 source, we need to add the appropriate power of 2 if the input
12930   // was negative.  This is the same as the optimization in
12931   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12932   // we must be careful to do the computation in x87 extended precision, not
12933   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12934   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12935   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12936       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12937       MachineMemOperand::MOLoad, 8, 8);
12938
12939   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12940   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12941   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12942                                          MVT::i64, MMO);
12943
12944   APInt FF(32, 0x5F800000ULL);
12945
12946   // Check whether the sign bit is set.
12947   SDValue SignSet = DAG.getSetCC(
12948       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12949       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12950
12951   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12952   SDValue FudgePtr = DAG.getConstantPool(
12953       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12954
12955   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12956   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12957   SDValue Four = DAG.getIntPtrConstant(4, dl);
12958   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12959                                Zero, Four);
12960   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12961
12962   // Load the value out, extending it from f32 to f80.
12963   // FIXME: Avoid the extend by constructing the right constant pool?
12964   SDValue Fudge = DAG.getExtLoad(
12965       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12966       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12967       false, false, false, 4);
12968   // Extend everything to 80 bits to force it to be done on x87.
12969   // TODO: Are there any fast-math-flags to propagate here?
12970   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12971   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12972                      DAG.getIntPtrConstant(0, dl));
12973 }
12974
12975 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12976 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12977 // just return an <SDValue(), SDValue()> pair.
12978 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12979 // to i16, i32 or i64, and we lower it to a legal sequence.
12980 // If lowered to the final integer result we return a <result, SDValue()> pair.
12981 // Otherwise we lower it to a sequence ending with a FIST, return a
12982 // <FIST, StackSlot> pair, and the caller is responsible for loading
12983 // the final integer result from StackSlot.
12984 std::pair<SDValue,SDValue>
12985 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12986                                    bool IsSigned, bool IsReplace) const {
12987   SDLoc DL(Op);
12988
12989   EVT DstTy = Op.getValueType();
12990   EVT TheVT = Op.getOperand(0).getValueType();
12991   auto PtrVT = getPointerTy(DAG.getDataLayout());
12992
12993   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12994     // f16 must be promoted before using the lowering in this routine.
12995     // fp128 does not use this lowering.
12996     return std::make_pair(SDValue(), SDValue());
12997   }
12998
12999   // If using FIST to compute an unsigned i64, we'll need some fixup
13000   // to handle values above the maximum signed i64.  A FIST is always
13001   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13002   bool UnsignedFixup = !IsSigned &&
13003                        DstTy == MVT::i64 &&
13004                        (!Subtarget->is64Bit() ||
13005                         !isScalarFPTypeInSSEReg(TheVT));
13006
13007   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13008     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13009     // The low 32 bits of the fist result will have the correct uint32 result.
13010     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13011     DstTy = MVT::i64;
13012   }
13013
13014   assert(DstTy.getSimpleVT() <= MVT::i64 &&
13015          DstTy.getSimpleVT() >= MVT::i16 &&
13016          "Unknown FP_TO_INT to lower!");
13017
13018   // These are really Legal.
13019   if (DstTy == MVT::i32 &&
13020       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13021     return std::make_pair(SDValue(), SDValue());
13022   if (Subtarget->is64Bit() &&
13023       DstTy == MVT::i64 &&
13024       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13025     return std::make_pair(SDValue(), SDValue());
13026
13027   // We lower FP->int64 into FISTP64 followed by a load from a temporary
13028   // stack slot.
13029   MachineFunction &MF = DAG.getMachineFunction();
13030   unsigned MemSize = DstTy.getSizeInBits()/8;
13031   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13032   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13033
13034   unsigned Opc;
13035   switch (DstTy.getSimpleVT().SimpleTy) {
13036   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13037   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13038   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13039   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13040   }
13041
13042   SDValue Chain = DAG.getEntryNode();
13043   SDValue Value = Op.getOperand(0);
13044   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13045
13046   if (UnsignedFixup) {
13047     //
13048     // Conversion to unsigned i64 is implemented with a select,
13049     // depending on whether the source value fits in the range
13050     // of a signed i64.  Let Thresh be the FP equivalent of
13051     // 0x8000000000000000ULL.
13052     //
13053     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13054     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
13055     //  Fist-to-mem64 FistSrc
13056     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13057     //  to XOR'ing the high 32 bits with Adjust.
13058     //
13059     // Being a power of 2, Thresh is exactly representable in all FP formats.
13060     // For X87 we'd like to use the smallest FP type for this constant, but
13061     // for DAG type consistency we have to match the FP operand type.
13062
13063     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13064     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13065     bool LosesInfo = false;
13066     if (TheVT == MVT::f64)
13067       // The rounding mode is irrelevant as the conversion should be exact.
13068       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13069                               &LosesInfo);
13070     else if (TheVT == MVT::f80)
13071       Status = Thresh.convert(APFloat::x87DoubleExtended,
13072                               APFloat::rmNearestTiesToEven, &LosesInfo);
13073
13074     assert(Status == APFloat::opOK && !LosesInfo &&
13075            "FP conversion should have been exact");
13076
13077     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13078
13079     SDValue Cmp = DAG.getSetCC(DL,
13080                                getSetCCResultType(DAG.getDataLayout(),
13081                                                   *DAG.getContext(), TheVT),
13082                                Value, ThreshVal, ISD::SETLT);
13083     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13084                            DAG.getConstant(0, DL, MVT::i32),
13085                            DAG.getConstant(0x80000000, DL, MVT::i32));
13086     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13087     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13088                                               *DAG.getContext(), TheVT),
13089                        Value, ThreshVal, ISD::SETLT);
13090     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13091   }
13092
13093   // FIXME This causes a redundant load/store if the SSE-class value is already
13094   // in memory, such as if it is on the callstack.
13095   if (isScalarFPTypeInSSEReg(TheVT)) {
13096     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13097     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13098                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13099                          false, 0);
13100     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13101     SDValue Ops[] = {
13102       Chain, StackSlot, DAG.getValueType(TheVT)
13103     };
13104
13105     MachineMemOperand *MMO =
13106         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13107                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13108     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13109     Chain = Value.getValue(1);
13110     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13111     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13112   }
13113
13114   MachineMemOperand *MMO =
13115       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13116                               MachineMemOperand::MOStore, MemSize, MemSize);
13117
13118   if (UnsignedFixup) {
13119
13120     // Insert the FIST, load its result as two i32's,
13121     // and XOR the high i32 with Adjust.
13122
13123     SDValue FistOps[] = { Chain, Value, StackSlot };
13124     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13125                                            FistOps, DstTy, MMO);
13126
13127     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13128                                 MachinePointerInfo(),
13129                                 false, false, false, 0);
13130     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13131                                    DAG.getConstant(4, DL, PtrVT));
13132
13133     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13134                                  MachinePointerInfo(),
13135                                  false, false, false, 0);
13136     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13137
13138     if (Subtarget->is64Bit()) {
13139       // Join High32 and Low32 into a 64-bit result.
13140       // (High32 << 32) | Low32
13141       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13142       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13143       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13144                            DAG.getConstant(32, DL, MVT::i8));
13145       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13146       return std::make_pair(Result, SDValue());
13147     }
13148
13149     SDValue ResultOps[] = { Low32, High32 };
13150
13151     SDValue pair = IsReplace
13152       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13153       : DAG.getMergeValues(ResultOps, DL);
13154     return std::make_pair(pair, SDValue());
13155   } else {
13156     // Build the FP_TO_INT*_IN_MEM
13157     SDValue Ops[] = { Chain, Value, StackSlot };
13158     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13159                                            Ops, DstTy, MMO);
13160     return std::make_pair(FIST, StackSlot);
13161   }
13162 }
13163
13164 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13165                               const X86Subtarget *Subtarget) {
13166   MVT VT = Op->getSimpleValueType(0);
13167   SDValue In = Op->getOperand(0);
13168   MVT InVT = In.getSimpleValueType();
13169   SDLoc dl(Op);
13170
13171   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13172     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13173
13174   // Optimize vectors in AVX mode:
13175   //
13176   //   v8i16 -> v8i32
13177   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13178   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13179   //   Concat upper and lower parts.
13180   //
13181   //   v4i32 -> v4i64
13182   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13183   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13184   //   Concat upper and lower parts.
13185   //
13186
13187   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13188       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13189       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13190     return SDValue();
13191
13192   if (Subtarget->hasInt256())
13193     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13194
13195   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13196   SDValue Undef = DAG.getUNDEF(InVT);
13197   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13198   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13199   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13200
13201   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13202                              VT.getVectorNumElements()/2);
13203
13204   OpLo = DAG.getBitcast(HVT, OpLo);
13205   OpHi = DAG.getBitcast(HVT, OpHi);
13206
13207   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13208 }
13209
13210 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13211                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13212   MVT VT = Op->getSimpleValueType(0);
13213   SDValue In = Op->getOperand(0);
13214   MVT InVT = In.getSimpleValueType();
13215   SDLoc DL(Op);
13216   unsigned int NumElts = VT.getVectorNumElements();
13217   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13218     return SDValue();
13219
13220   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13221     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13222
13223   assert(InVT.getVectorElementType() == MVT::i1);
13224   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13225   SDValue One =
13226    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13227   SDValue Zero =
13228    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13229
13230   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13231   if (VT.is512BitVector())
13232     return V;
13233   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13234 }
13235
13236 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13237                                SelectionDAG &DAG) {
13238   if (Subtarget->hasFp256())
13239     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13240       return Res;
13241
13242   return SDValue();
13243 }
13244
13245 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13246                                 SelectionDAG &DAG) {
13247   SDLoc DL(Op);
13248   MVT VT = Op.getSimpleValueType();
13249   SDValue In = Op.getOperand(0);
13250   MVT SVT = In.getSimpleValueType();
13251
13252   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13253     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13254
13255   if (Subtarget->hasFp256())
13256     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13257       return Res;
13258
13259   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13260          VT.getVectorNumElements() != SVT.getVectorNumElements());
13261   return SDValue();
13262 }
13263
13264 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13265   SDLoc DL(Op);
13266   MVT VT = Op.getSimpleValueType();
13267   SDValue In = Op.getOperand(0);
13268   MVT InVT = In.getSimpleValueType();
13269
13270   if (VT == MVT::i1) {
13271     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13272            "Invalid scalar TRUNCATE operation");
13273     if (InVT.getSizeInBits() >= 32)
13274       return SDValue();
13275     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13276     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13277   }
13278   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13279          "Invalid TRUNCATE operation");
13280
13281   // move vector to mask - truncate solution for SKX
13282   if (VT.getVectorElementType() == MVT::i1) {
13283     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13284         Subtarget->hasBWI())
13285       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13286     if ((InVT.is256BitVector() || InVT.is128BitVector())
13287         && InVT.getScalarSizeInBits() <= 16 &&
13288         Subtarget->hasBWI() && Subtarget->hasVLX())
13289       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13290     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13291         Subtarget->hasDQI())
13292       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13293     if ((InVT.is256BitVector() || InVT.is128BitVector())
13294         && InVT.getScalarSizeInBits() >= 32 &&
13295         Subtarget->hasDQI() && Subtarget->hasVLX())
13296       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13297     }
13298
13299   if (VT.getVectorElementType() == MVT::i1) {
13300     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13301     unsigned NumElts = InVT.getVectorNumElements();
13302     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13303     if (InVT.getSizeInBits() < 512) {
13304       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13305       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13306       InVT = ExtVT;
13307     }
13308
13309     SDValue OneV =
13310      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13311     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13312     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13313   }
13314
13315   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13316   if (Subtarget->hasAVX512()) {
13317     // word to byte only under BWI
13318     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13319       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13320                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13321     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13322   }
13323   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13324     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13325     if (Subtarget->hasInt256()) {
13326       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13327       In = DAG.getBitcast(MVT::v8i32, In);
13328       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13329                                 ShufMask);
13330       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13331                          DAG.getIntPtrConstant(0, DL));
13332     }
13333
13334     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13335                                DAG.getIntPtrConstant(0, DL));
13336     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13337                                DAG.getIntPtrConstant(2, DL));
13338     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13339     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13340     static const int ShufMask[] = {0, 2, 4, 6};
13341     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13342   }
13343
13344   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13345     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13346     if (Subtarget->hasInt256()) {
13347       In = DAG.getBitcast(MVT::v32i8, In);
13348
13349       SmallVector<SDValue,32> pshufbMask;
13350       for (unsigned i = 0; i < 2; ++i) {
13351         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13352         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13353         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13354         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13355         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13356         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13357         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13358         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13359         for (unsigned j = 0; j < 8; ++j)
13360           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13361       }
13362       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13363       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13364       In = DAG.getBitcast(MVT::v4i64, In);
13365
13366       static const int ShufMask[] = {0,  2,  -1,  -1};
13367       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13368                                 &ShufMask[0]);
13369       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13370                        DAG.getIntPtrConstant(0, DL));
13371       return DAG.getBitcast(VT, In);
13372     }
13373
13374     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13375                                DAG.getIntPtrConstant(0, DL));
13376
13377     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13378                                DAG.getIntPtrConstant(4, DL));
13379
13380     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13381     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13382
13383     // The PSHUFB mask:
13384     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13385                                    -1, -1, -1, -1, -1, -1, -1, -1};
13386
13387     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13388     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13389     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13390
13391     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13392     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13393
13394     // The MOVLHPS Mask:
13395     static const int ShufMask2[] = {0, 1, 4, 5};
13396     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13397     return DAG.getBitcast(MVT::v8i16, res);
13398   }
13399
13400   // Handle truncation of V256 to V128 using shuffles.
13401   if (!VT.is128BitVector() || !InVT.is256BitVector())
13402     return SDValue();
13403
13404   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13405
13406   unsigned NumElems = VT.getVectorNumElements();
13407   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13408
13409   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13410   // Prepare truncation shuffle mask
13411   for (unsigned i = 0; i != NumElems; ++i)
13412     MaskVec[i] = i * 2;
13413   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13414                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13415   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13416                      DAG.getIntPtrConstant(0, DL));
13417 }
13418
13419 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13420                                            SelectionDAG &DAG) const {
13421   assert(!Op.getSimpleValueType().isVector());
13422
13423   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13424     /*IsSigned=*/ true, /*IsReplace=*/ false);
13425   SDValue FIST = Vals.first, StackSlot = Vals.second;
13426   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13427   if (!FIST.getNode())
13428     return Op;
13429
13430   if (StackSlot.getNode())
13431     // Load the result.
13432     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13433                        FIST, StackSlot, MachinePointerInfo(),
13434                        false, false, false, 0);
13435
13436   // The node is the result.
13437   return FIST;
13438 }
13439
13440 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13441                                            SelectionDAG &DAG) const {
13442   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13443     /*IsSigned=*/ false, /*IsReplace=*/ false);
13444   SDValue FIST = Vals.first, StackSlot = Vals.second;
13445   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13446   if (!FIST.getNode())
13447     return Op;
13448
13449   if (StackSlot.getNode())
13450     // Load the result.
13451     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13452                        FIST, StackSlot, MachinePointerInfo(),
13453                        false, false, false, 0);
13454
13455   // The node is the result.
13456   return FIST;
13457 }
13458
13459 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13460   SDLoc DL(Op);
13461   MVT VT = Op.getSimpleValueType();
13462   SDValue In = Op.getOperand(0);
13463   MVT SVT = In.getSimpleValueType();
13464
13465   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13466
13467   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13468                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13469                                  In, DAG.getUNDEF(SVT)));
13470 }
13471
13472 /// The only differences between FABS and FNEG are the mask and the logic op.
13473 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13474 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13475   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13476          "Wrong opcode for lowering FABS or FNEG.");
13477
13478   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13479
13480   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13481   // into an FNABS. We'll lower the FABS after that if it is still in use.
13482   if (IsFABS)
13483     for (SDNode *User : Op->uses())
13484       if (User->getOpcode() == ISD::FNEG)
13485         return Op;
13486
13487   SDLoc dl(Op);
13488   MVT VT = Op.getSimpleValueType();
13489
13490   bool IsF128 = (VT == MVT::f128);
13491
13492   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13493   // decide if we should generate a 16-byte constant mask when we only need 4 or
13494   // 8 bytes for the scalar case.
13495
13496   MVT LogicVT;
13497   MVT EltVT;
13498   unsigned NumElts;
13499
13500   if (VT.isVector()) {
13501     LogicVT = VT;
13502     EltVT = VT.getVectorElementType();
13503     NumElts = VT.getVectorNumElements();
13504   } else if (IsF128) {
13505     // SSE instructions are used for optimized f128 logical operations.
13506     LogicVT = MVT::f128;
13507     EltVT = VT;
13508     NumElts = 1;
13509   } else {
13510     // There are no scalar bitwise logical SSE/AVX instructions, so we
13511     // generate a 16-byte vector constant and logic op even for the scalar case.
13512     // Using a 16-byte mask allows folding the load of the mask with
13513     // the logic op, so it can save (~4 bytes) on code size.
13514     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13515     EltVT = VT;
13516     NumElts = (VT == MVT::f64) ? 2 : 4;
13517   }
13518
13519   unsigned EltBits = EltVT.getSizeInBits();
13520   LLVMContext *Context = DAG.getContext();
13521   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13522   APInt MaskElt =
13523     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13524   Constant *C = ConstantInt::get(*Context, MaskElt);
13525   C = ConstantVector::getSplat(NumElts, C);
13526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13527   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13528   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13529   SDValue Mask =
13530       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13531                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13532                   false, false, false, Alignment);
13533
13534   SDValue Op0 = Op.getOperand(0);
13535   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13536   unsigned LogicOp =
13537     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13538   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13539
13540   if (VT.isVector() || IsF128)
13541     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13542
13543   // For the scalar case extend to a 128-bit vector, perform the logic op,
13544   // and extract the scalar result back out.
13545   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13546   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13547   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13548                      DAG.getIntPtrConstant(0, dl));
13549 }
13550
13551 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13553   LLVMContext *Context = DAG.getContext();
13554   SDValue Op0 = Op.getOperand(0);
13555   SDValue Op1 = Op.getOperand(1);
13556   SDLoc dl(Op);
13557   MVT VT = Op.getSimpleValueType();
13558   MVT SrcVT = Op1.getSimpleValueType();
13559   bool IsF128 = (VT == MVT::f128);
13560
13561   // If second operand is smaller, extend it first.
13562   if (SrcVT.bitsLT(VT)) {
13563     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13564     SrcVT = VT;
13565   }
13566   // And if it is bigger, shrink it first.
13567   if (SrcVT.bitsGT(VT)) {
13568     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13569     SrcVT = VT;
13570   }
13571
13572   // At this point the operands and the result should have the same
13573   // type, and that won't be f80 since that is not custom lowered.
13574   assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13575          "Unexpected type in LowerFCOPYSIGN");
13576
13577   const fltSemantics &Sem =
13578       VT == MVT::f64 ? APFloat::IEEEdouble :
13579           (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13580   const unsigned SizeInBits = VT.getSizeInBits();
13581
13582   SmallVector<Constant *, 4> CV(
13583       VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13584       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13585
13586   // First, clear all bits but the sign bit from the second operand (sign).
13587   CV[0] = ConstantFP::get(*Context,
13588                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13589   Constant *C = ConstantVector::get(CV);
13590   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13591   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13592
13593   // Perform all logic operations as 16-byte vectors because there are no
13594   // scalar FP logic instructions in SSE. This allows load folding of the
13595   // constants into the logic instructions.
13596   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13597   SDValue Mask1 =
13598       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13599                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13600                   false, false, false, 16);
13601   if (!IsF128)
13602     Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13603   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13604
13605   // Next, clear the sign bit from the first operand (magnitude).
13606   // If it's a constant, we can clear it here.
13607   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13608     APFloat APF = Op0CN->getValueAPF();
13609     // If the magnitude is a positive zero, the sign bit alone is enough.
13610     if (APF.isPosZero())
13611       return IsF128 ? SignBit :
13612           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13613                       DAG.getIntPtrConstant(0, dl));
13614     APF.clearSign();
13615     CV[0] = ConstantFP::get(*Context, APF);
13616   } else {
13617     CV[0] = ConstantFP::get(
13618         *Context,
13619         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13620   }
13621   C = ConstantVector::get(CV);
13622   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13623   SDValue Val =
13624       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13625                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13626                   false, false, false, 16);
13627   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13628   if (!isa<ConstantFPSDNode>(Op0)) {
13629     if (!IsF128)
13630       Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13631     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13632   }
13633   // OR the magnitude value with the sign bit.
13634   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13635   return IsF128 ? Val :
13636       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13637                   DAG.getIntPtrConstant(0, dl));
13638 }
13639
13640 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13641   SDValue N0 = Op.getOperand(0);
13642   SDLoc dl(Op);
13643   MVT VT = Op.getSimpleValueType();
13644
13645   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13646   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13647                                   DAG.getConstant(1, dl, VT));
13648   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13649 }
13650
13651 // Check whether an OR'd tree is PTEST-able.
13652 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13653                                       SelectionDAG &DAG) {
13654   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13655
13656   if (!Subtarget->hasSSE41())
13657     return SDValue();
13658
13659   if (!Op->hasOneUse())
13660     return SDValue();
13661
13662   SDNode *N = Op.getNode();
13663   SDLoc DL(N);
13664
13665   SmallVector<SDValue, 8> Opnds;
13666   DenseMap<SDValue, unsigned> VecInMap;
13667   SmallVector<SDValue, 8> VecIns;
13668   EVT VT = MVT::Other;
13669
13670   // Recognize a special case where a vector is casted into wide integer to
13671   // test all 0s.
13672   Opnds.push_back(N->getOperand(0));
13673   Opnds.push_back(N->getOperand(1));
13674
13675   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13676     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13677     // BFS traverse all OR'd operands.
13678     if (I->getOpcode() == ISD::OR) {
13679       Opnds.push_back(I->getOperand(0));
13680       Opnds.push_back(I->getOperand(1));
13681       // Re-evaluate the number of nodes to be traversed.
13682       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13683       continue;
13684     }
13685
13686     // Quit if a non-EXTRACT_VECTOR_ELT
13687     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13688       return SDValue();
13689
13690     // Quit if without a constant index.
13691     SDValue Idx = I->getOperand(1);
13692     if (!isa<ConstantSDNode>(Idx))
13693       return SDValue();
13694
13695     SDValue ExtractedFromVec = I->getOperand(0);
13696     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13697     if (M == VecInMap.end()) {
13698       VT = ExtractedFromVec.getValueType();
13699       // Quit if not 128/256-bit vector.
13700       if (!VT.is128BitVector() && !VT.is256BitVector())
13701         return SDValue();
13702       // Quit if not the same type.
13703       if (VecInMap.begin() != VecInMap.end() &&
13704           VT != VecInMap.begin()->first.getValueType())
13705         return SDValue();
13706       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13707       VecIns.push_back(ExtractedFromVec);
13708     }
13709     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13710   }
13711
13712   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13713          "Not extracted from 128-/256-bit vector.");
13714
13715   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13716
13717   for (DenseMap<SDValue, unsigned>::const_iterator
13718         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13719     // Quit if not all elements are used.
13720     if (I->second != FullMask)
13721       return SDValue();
13722   }
13723
13724   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13725
13726   // Cast all vectors into TestVT for PTEST.
13727   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13728     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13729
13730   // If more than one full vectors are evaluated, OR them first before PTEST.
13731   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13732     // Each iteration will OR 2 nodes and append the result until there is only
13733     // 1 node left, i.e. the final OR'd value of all vectors.
13734     SDValue LHS = VecIns[Slot];
13735     SDValue RHS = VecIns[Slot + 1];
13736     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13737   }
13738
13739   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13740                      VecIns.back(), VecIns.back());
13741 }
13742
13743 /// \brief return true if \c Op has a use that doesn't just read flags.
13744 static bool hasNonFlagsUse(SDValue Op) {
13745   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13746        ++UI) {
13747     SDNode *User = *UI;
13748     unsigned UOpNo = UI.getOperandNo();
13749     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13750       // Look pass truncate.
13751       UOpNo = User->use_begin().getOperandNo();
13752       User = *User->use_begin();
13753     }
13754
13755     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13756         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13757       return true;
13758   }
13759   return false;
13760 }
13761
13762 /// Emit nodes that will be selected as "test Op0,Op0", or something
13763 /// equivalent.
13764 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13765                                     SelectionDAG &DAG) const {
13766   if (Op.getValueType() == MVT::i1) {
13767     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13768     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13769                        DAG.getConstant(0, dl, MVT::i8));
13770   }
13771   // CF and OF aren't always set the way we want. Determine which
13772   // of these we need.
13773   bool NeedCF = false;
13774   bool NeedOF = false;
13775   switch (X86CC) {
13776   default: break;
13777   case X86::COND_A: case X86::COND_AE:
13778   case X86::COND_B: case X86::COND_BE:
13779     NeedCF = true;
13780     break;
13781   case X86::COND_G: case X86::COND_GE:
13782   case X86::COND_L: case X86::COND_LE:
13783   case X86::COND_O: case X86::COND_NO: {
13784     // Check if we really need to set the
13785     // Overflow flag. If NoSignedWrap is present
13786     // that is not actually needed.
13787     switch (Op->getOpcode()) {
13788     case ISD::ADD:
13789     case ISD::SUB:
13790     case ISD::MUL:
13791     case ISD::SHL: {
13792       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13793       if (BinNode->Flags.hasNoSignedWrap())
13794         break;
13795     }
13796     default:
13797       NeedOF = true;
13798       break;
13799     }
13800     break;
13801   }
13802   }
13803   // See if we can use the EFLAGS value from the operand instead of
13804   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13805   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13806   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13807     // Emit a CMP with 0, which is the TEST pattern.
13808     //if (Op.getValueType() == MVT::i1)
13809     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13810     //                     DAG.getConstant(0, MVT::i1));
13811     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13812                        DAG.getConstant(0, dl, Op.getValueType()));
13813   }
13814   unsigned Opcode = 0;
13815   unsigned NumOperands = 0;
13816
13817   // Truncate operations may prevent the merge of the SETCC instruction
13818   // and the arithmetic instruction before it. Attempt to truncate the operands
13819   // of the arithmetic instruction and use a reduced bit-width instruction.
13820   bool NeedTruncation = false;
13821   SDValue ArithOp = Op;
13822   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13823     SDValue Arith = Op->getOperand(0);
13824     // Both the trunc and the arithmetic op need to have one user each.
13825     if (Arith->hasOneUse())
13826       switch (Arith.getOpcode()) {
13827         default: break;
13828         case ISD::ADD:
13829         case ISD::SUB:
13830         case ISD::AND:
13831         case ISD::OR:
13832         case ISD::XOR: {
13833           NeedTruncation = true;
13834           ArithOp = Arith;
13835         }
13836       }
13837   }
13838
13839   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13840   // which may be the result of a CAST.  We use the variable 'Op', which is the
13841   // non-casted variable when we check for possible users.
13842   switch (ArithOp.getOpcode()) {
13843   case ISD::ADD:
13844     // Due to an isel shortcoming, be conservative if this add is likely to be
13845     // selected as part of a load-modify-store instruction. When the root node
13846     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13847     // uses of other nodes in the match, such as the ADD in this case. This
13848     // leads to the ADD being left around and reselected, with the result being
13849     // two adds in the output.  Alas, even if none our users are stores, that
13850     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13851     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13852     // climbing the DAG back to the root, and it doesn't seem to be worth the
13853     // effort.
13854     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13855          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13856       if (UI->getOpcode() != ISD::CopyToReg &&
13857           UI->getOpcode() != ISD::SETCC &&
13858           UI->getOpcode() != ISD::STORE)
13859         goto default_case;
13860
13861     if (ConstantSDNode *C =
13862         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13863       // An add of one will be selected as an INC.
13864       if (C->isOne() && !Subtarget->slowIncDec()) {
13865         Opcode = X86ISD::INC;
13866         NumOperands = 1;
13867         break;
13868       }
13869
13870       // An add of negative one (subtract of one) will be selected as a DEC.
13871       if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
13872         Opcode = X86ISD::DEC;
13873         NumOperands = 1;
13874         break;
13875       }
13876     }
13877
13878     // Otherwise use a regular EFLAGS-setting add.
13879     Opcode = X86ISD::ADD;
13880     NumOperands = 2;
13881     break;
13882   case ISD::SHL:
13883   case ISD::SRL:
13884     // If we have a constant logical shift that's only used in a comparison
13885     // against zero turn it into an equivalent AND. This allows turning it into
13886     // a TEST instruction later.
13887     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13888         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13889       EVT VT = Op.getValueType();
13890       unsigned BitWidth = VT.getSizeInBits();
13891       unsigned ShAmt = Op->getConstantOperandVal(1);
13892       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13893         break;
13894       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13895                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13896                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13897       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13898         break;
13899       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13900                                 DAG.getConstant(Mask, dl, VT));
13901       DAG.ReplaceAllUsesWith(Op, New);
13902       Op = New;
13903     }
13904     break;
13905
13906   case ISD::AND:
13907     // If the primary and result isn't used, don't bother using X86ISD::AND,
13908     // because a TEST instruction will be better.
13909     if (!hasNonFlagsUse(Op))
13910       break;
13911     // FALL THROUGH
13912   case ISD::SUB:
13913   case ISD::OR:
13914   case ISD::XOR:
13915     // Due to the ISEL shortcoming noted above, be conservative if this op is
13916     // likely to be selected as part of a load-modify-store instruction.
13917     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13918            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13919       if (UI->getOpcode() == ISD::STORE)
13920         goto default_case;
13921
13922     // Otherwise use a regular EFLAGS-setting instruction.
13923     switch (ArithOp.getOpcode()) {
13924     default: llvm_unreachable("unexpected operator!");
13925     case ISD::SUB: Opcode = X86ISD::SUB; break;
13926     case ISD::XOR: Opcode = X86ISD::XOR; break;
13927     case ISD::AND: Opcode = X86ISD::AND; break;
13928     case ISD::OR: {
13929       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13930         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13931         if (EFLAGS.getNode())
13932           return EFLAGS;
13933       }
13934       Opcode = X86ISD::OR;
13935       break;
13936     }
13937     }
13938
13939     NumOperands = 2;
13940     break;
13941   case X86ISD::ADD:
13942   case X86ISD::SUB:
13943   case X86ISD::INC:
13944   case X86ISD::DEC:
13945   case X86ISD::OR:
13946   case X86ISD::XOR:
13947   case X86ISD::AND:
13948     return SDValue(Op.getNode(), 1);
13949   default:
13950   default_case:
13951     break;
13952   }
13953
13954   // If we found that truncation is beneficial, perform the truncation and
13955   // update 'Op'.
13956   if (NeedTruncation) {
13957     EVT VT = Op.getValueType();
13958     SDValue WideVal = Op->getOperand(0);
13959     EVT WideVT = WideVal.getValueType();
13960     unsigned ConvertedOp = 0;
13961     // Use a target machine opcode to prevent further DAGCombine
13962     // optimizations that may separate the arithmetic operations
13963     // from the setcc node.
13964     switch (WideVal.getOpcode()) {
13965       default: break;
13966       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13967       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13968       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13969       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13970       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13971     }
13972
13973     if (ConvertedOp) {
13974       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13975       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13976         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13977         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13978         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13979       }
13980     }
13981   }
13982
13983   if (Opcode == 0)
13984     // Emit a CMP with 0, which is the TEST pattern.
13985     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13986                        DAG.getConstant(0, dl, Op.getValueType()));
13987
13988   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13989   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13990
13991   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13992   DAG.ReplaceAllUsesWith(Op, New);
13993   return SDValue(New.getNode(), 1);
13994 }
13995
13996 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13997 /// equivalent.
13998 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13999                                    SDLoc dl, SelectionDAG &DAG) const {
14000   if (isNullConstant(Op1))
14001     return EmitTest(Op0, X86CC, dl, DAG);
14002
14003   assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14004          "Unexpected comparison operation for MVT::i1 operands");
14005
14006   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14007        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14008     // Do the comparison at i32 if it's smaller, besides the Atom case.
14009     // This avoids subregister aliasing issues. Keep the smaller reference
14010     // if we're optimizing for size, however, as that'll allow better folding
14011     // of memory operations.
14012     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14013         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14014         !Subtarget->isAtom()) {
14015       unsigned ExtendOp =
14016           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14017       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14018       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14019     }
14020     // Use SUB instead of CMP to enable CSE between SUB and CMP.
14021     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14022     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14023                               Op0, Op1);
14024     return SDValue(Sub.getNode(), 1);
14025   }
14026   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14027 }
14028
14029 /// Convert a comparison if required by the subtarget.
14030 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14031                                                  SelectionDAG &DAG) const {
14032   // If the subtarget does not support the FUCOMI instruction, floating-point
14033   // comparisons have to be converted.
14034   if (Subtarget->hasCMov() ||
14035       Cmp.getOpcode() != X86ISD::CMP ||
14036       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14037       !Cmp.getOperand(1).getValueType().isFloatingPoint())
14038     return Cmp;
14039
14040   // The instruction selector will select an FUCOM instruction instead of
14041   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14042   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14043   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14044   SDLoc dl(Cmp);
14045   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14046   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14047   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14048                             DAG.getConstant(8, dl, MVT::i8));
14049   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14050
14051   // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14052   assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14053   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14054 }
14055
14056 /// The minimum architected relative accuracy is 2^-12. We need one
14057 /// Newton-Raphson step to have a good float result (24 bits of precision).
14058 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14059                                             DAGCombinerInfo &DCI,
14060                                             unsigned &RefinementSteps,
14061                                             bool &UseOneConstNR) const {
14062   EVT VT = Op.getValueType();
14063   const char *RecipOp;
14064
14065   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14066   // TODO: Add support for AVX512 (v16f32).
14067   // It is likely not profitable to do this for f64 because a double-precision
14068   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14069   // instructions: convert to single, rsqrtss, convert back to double, refine
14070   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14071   // along with FMA, this could be a throughput win.
14072   if (VT == MVT::f32 && Subtarget->hasSSE1())
14073     RecipOp = "sqrtf";
14074   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14075            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14076     RecipOp = "vec-sqrtf";
14077   else
14078     return SDValue();
14079
14080   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14081   if (!Recips.isEnabled(RecipOp))
14082     return SDValue();
14083
14084   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14085   UseOneConstNR = false;
14086   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14087 }
14088
14089 /// The minimum architected relative accuracy is 2^-12. We need one
14090 /// Newton-Raphson step to have a good float result (24 bits of precision).
14091 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14092                                             DAGCombinerInfo &DCI,
14093                                             unsigned &RefinementSteps) const {
14094   EVT VT = Op.getValueType();
14095   const char *RecipOp;
14096
14097   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14098   // TODO: Add support for AVX512 (v16f32).
14099   // It is likely not profitable to do this for f64 because a double-precision
14100   // reciprocal estimate with refinement on x86 prior to FMA requires
14101   // 15 instructions: convert to single, rcpss, convert back to double, refine
14102   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14103   // along with FMA, this could be a throughput win.
14104   if (VT == MVT::f32 && Subtarget->hasSSE1())
14105     RecipOp = "divf";
14106   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14107            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14108     RecipOp = "vec-divf";
14109   else
14110     return SDValue();
14111
14112   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14113   if (!Recips.isEnabled(RecipOp))
14114     return SDValue();
14115
14116   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14117   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14118 }
14119
14120 /// If we have at least two divisions that use the same divisor, convert to
14121 /// multplication by a reciprocal. This may need to be adjusted for a given
14122 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14123 /// This is because we still need one division to calculate the reciprocal and
14124 /// then we need two multiplies by that reciprocal as replacements for the
14125 /// original divisions.
14126 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14127   return 2;
14128 }
14129
14130 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14131 /// if it's possible.
14132 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14133                                      SDLoc dl, SelectionDAG &DAG) const {
14134   SDValue Op0 = And.getOperand(0);
14135   SDValue Op1 = And.getOperand(1);
14136   if (Op0.getOpcode() == ISD::TRUNCATE)
14137     Op0 = Op0.getOperand(0);
14138   if (Op1.getOpcode() == ISD::TRUNCATE)
14139     Op1 = Op1.getOperand(0);
14140
14141   SDValue LHS, RHS;
14142   if (Op1.getOpcode() == ISD::SHL)
14143     std::swap(Op0, Op1);
14144   if (Op0.getOpcode() == ISD::SHL) {
14145     if (isOneConstant(Op0.getOperand(0))) {
14146         // If we looked past a truncate, check that it's only truncating away
14147         // known zeros.
14148         unsigned BitWidth = Op0.getValueSizeInBits();
14149         unsigned AndBitWidth = And.getValueSizeInBits();
14150         if (BitWidth > AndBitWidth) {
14151           APInt Zeros, Ones;
14152           DAG.computeKnownBits(Op0, Zeros, Ones);
14153           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14154             return SDValue();
14155         }
14156         LHS = Op1;
14157         RHS = Op0.getOperand(1);
14158       }
14159   } else if (Op1.getOpcode() == ISD::Constant) {
14160     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14161     uint64_t AndRHSVal = AndRHS->getZExtValue();
14162     SDValue AndLHS = Op0;
14163
14164     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14165       LHS = AndLHS.getOperand(0);
14166       RHS = AndLHS.getOperand(1);
14167     }
14168
14169     // Use BT if the immediate can't be encoded in a TEST instruction.
14170     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14171       LHS = AndLHS;
14172       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14173     }
14174   }
14175
14176   if (LHS.getNode()) {
14177     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14178     // instruction.  Since the shift amount is in-range-or-undefined, we know
14179     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14180     // the encoding for the i16 version is larger than the i32 version.
14181     // Also promote i16 to i32 for performance / code size reason.
14182     if (LHS.getValueType() == MVT::i8 ||
14183         LHS.getValueType() == MVT::i16)
14184       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14185
14186     // If the operand types disagree, extend the shift amount to match.  Since
14187     // BT ignores high bits (like shifts) we can use anyextend.
14188     if (LHS.getValueType() != RHS.getValueType())
14189       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14190
14191     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14192     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14193     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14194                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14195   }
14196
14197   return SDValue();
14198 }
14199
14200 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14201 /// mask CMPs.
14202 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14203                               SDValue &Op1) {
14204   unsigned SSECC;
14205   bool Swap = false;
14206
14207   // SSE Condition code mapping:
14208   //  0 - EQ
14209   //  1 - LT
14210   //  2 - LE
14211   //  3 - UNORD
14212   //  4 - NEQ
14213   //  5 - NLT
14214   //  6 - NLE
14215   //  7 - ORD
14216   switch (SetCCOpcode) {
14217   default: llvm_unreachable("Unexpected SETCC condition");
14218   case ISD::SETOEQ:
14219   case ISD::SETEQ:  SSECC = 0; break;
14220   case ISD::SETOGT:
14221   case ISD::SETGT:  Swap = true; // Fallthrough
14222   case ISD::SETLT:
14223   case ISD::SETOLT: SSECC = 1; break;
14224   case ISD::SETOGE:
14225   case ISD::SETGE:  Swap = true; // Fallthrough
14226   case ISD::SETLE:
14227   case ISD::SETOLE: SSECC = 2; break;
14228   case ISD::SETUO:  SSECC = 3; break;
14229   case ISD::SETUNE:
14230   case ISD::SETNE:  SSECC = 4; break;
14231   case ISD::SETULE: Swap = true; // Fallthrough
14232   case ISD::SETUGE: SSECC = 5; break;
14233   case ISD::SETULT: Swap = true; // Fallthrough
14234   case ISD::SETUGT: SSECC = 6; break;
14235   case ISD::SETO:   SSECC = 7; break;
14236   case ISD::SETUEQ:
14237   case ISD::SETONE: SSECC = 8; break;
14238   }
14239   if (Swap)
14240     std::swap(Op0, Op1);
14241
14242   return SSECC;
14243 }
14244
14245 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14246 // ones, and then concatenate the result back.
14247 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14248   MVT VT = Op.getSimpleValueType();
14249
14250   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14251          "Unsupported value type for operation");
14252
14253   unsigned NumElems = VT.getVectorNumElements();
14254   SDLoc dl(Op);
14255   SDValue CC = Op.getOperand(2);
14256
14257   // Extract the LHS vectors
14258   SDValue LHS = Op.getOperand(0);
14259   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14260   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14261
14262   // Extract the RHS vectors
14263   SDValue RHS = Op.getOperand(1);
14264   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14265   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14266
14267   // Issue the operation on the smaller types and concatenate the result back
14268   MVT EltVT = VT.getVectorElementType();
14269   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14270   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14271                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14272                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14273 }
14274
14275 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14276   SDValue Op0 = Op.getOperand(0);
14277   SDValue Op1 = Op.getOperand(1);
14278   SDValue CC = Op.getOperand(2);
14279   MVT VT = Op.getSimpleValueType();
14280   SDLoc dl(Op);
14281
14282   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14283          "Unexpected type for boolean compare operation");
14284   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14285   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14286                                DAG.getConstant(-1, dl, VT));
14287   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14288                                DAG.getConstant(-1, dl, VT));
14289   switch (SetCCOpcode) {
14290   default: llvm_unreachable("Unexpected SETCC condition");
14291   case ISD::SETEQ:
14292     // (x == y) -> ~(x ^ y)
14293     return DAG.getNode(ISD::XOR, dl, VT,
14294                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14295                        DAG.getConstant(-1, dl, VT));
14296   case ISD::SETNE:
14297     // (x != y) -> (x ^ y)
14298     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14299   case ISD::SETUGT:
14300   case ISD::SETGT:
14301     // (x > y) -> (x & ~y)
14302     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14303   case ISD::SETULT:
14304   case ISD::SETLT:
14305     // (x < y) -> (~x & y)
14306     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14307   case ISD::SETULE:
14308   case ISD::SETLE:
14309     // (x <= y) -> (~x | y)
14310     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14311   case ISD::SETUGE:
14312   case ISD::SETGE:
14313     // (x >=y) -> (x | ~y)
14314     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14315   }
14316 }
14317
14318 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14319                                      const X86Subtarget *Subtarget) {
14320   SDValue Op0 = Op.getOperand(0);
14321   SDValue Op1 = Op.getOperand(1);
14322   SDValue CC = Op.getOperand(2);
14323   MVT VT = Op.getSimpleValueType();
14324   SDLoc dl(Op);
14325
14326   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14327          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14328          "Cannot set masked compare for this operation");
14329
14330   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14331   unsigned  Opc = 0;
14332   bool Unsigned = false;
14333   bool Swap = false;
14334   unsigned SSECC;
14335   switch (SetCCOpcode) {
14336   default: llvm_unreachable("Unexpected SETCC condition");
14337   case ISD::SETNE:  SSECC = 4; break;
14338   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14339   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14340   case ISD::SETLT:  Swap = true; //fall-through
14341   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14342   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14343   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14344   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14345   case ISD::SETULE: Unsigned = true; //fall-through
14346   case ISD::SETLE:  SSECC = 2; break;
14347   }
14348
14349   if (Swap)
14350     std::swap(Op0, Op1);
14351   if (Opc)
14352     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14353   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14354   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14355                      DAG.getConstant(SSECC, dl, MVT::i8));
14356 }
14357
14358 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14359 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14360 /// return an empty value.
14361 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14362 {
14363   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14364   if (!BV)
14365     return SDValue();
14366
14367   MVT VT = Op1.getSimpleValueType();
14368   MVT EVT = VT.getVectorElementType();
14369   unsigned n = VT.getVectorNumElements();
14370   SmallVector<SDValue, 8> ULTOp1;
14371
14372   for (unsigned i = 0; i < n; ++i) {
14373     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14374     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14375       return SDValue();
14376
14377     // Avoid underflow.
14378     APInt Val = Elt->getAPIntValue();
14379     if (Val == 0)
14380       return SDValue();
14381
14382     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14383   }
14384
14385   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14386 }
14387
14388 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14389                            SelectionDAG &DAG) {
14390   SDValue Op0 = Op.getOperand(0);
14391   SDValue Op1 = Op.getOperand(1);
14392   SDValue CC = Op.getOperand(2);
14393   MVT VT = Op.getSimpleValueType();
14394   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14395   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14396   SDLoc dl(Op);
14397
14398   if (isFP) {
14399 #ifndef NDEBUG
14400     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14401     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14402 #endif
14403
14404     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14405     unsigned Opc = X86ISD::CMPP;
14406     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14407       assert(VT.getVectorNumElements() <= 16);
14408       Opc = X86ISD::CMPM;
14409     }
14410     // In the two special cases we can't handle, emit two comparisons.
14411     if (SSECC == 8) {
14412       unsigned CC0, CC1;
14413       unsigned CombineOpc;
14414       if (SetCCOpcode == ISD::SETUEQ) {
14415         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14416       } else {
14417         assert(SetCCOpcode == ISD::SETONE);
14418         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14419       }
14420
14421       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14422                                  DAG.getConstant(CC0, dl, MVT::i8));
14423       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14424                                  DAG.getConstant(CC1, dl, MVT::i8));
14425       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14426     }
14427     // Handle all other FP comparisons here.
14428     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14429                        DAG.getConstant(SSECC, dl, MVT::i8));
14430   }
14431
14432   MVT VTOp0 = Op0.getSimpleValueType();
14433   assert(VTOp0 == Op1.getSimpleValueType() &&
14434          "Expected operands with same type!");
14435   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14436          "Invalid number of packed elements for source and destination!");
14437
14438   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14439     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14440     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14441     // legalizer firstly checks if the first operand in input to the setcc has
14442     // a legal type. If so, then it promotes the return type to that same type.
14443     // Otherwise, the return type is promoted to the 'next legal type' which,
14444     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14445     //
14446     // We reach this code only if the following two conditions are met:
14447     // 1. Both return type and operand type have been promoted to wider types
14448     //    by the type legalizer.
14449     // 2. The original operand type has been promoted to a 256-bit vector.
14450     //
14451     // Note that condition 2. only applies for AVX targets.
14452     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14453     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14454   }
14455
14456   // The non-AVX512 code below works under the assumption that source and
14457   // destination types are the same.
14458   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14459          "Value types for source and destination must be the same!");
14460
14461   // Break 256-bit integer vector compare into smaller ones.
14462   if (VT.is256BitVector() && !Subtarget->hasInt256())
14463     return Lower256IntVSETCC(Op, DAG);
14464
14465   MVT OpVT = Op1.getSimpleValueType();
14466   if (OpVT.getVectorElementType() == MVT::i1)
14467     return LowerBoolVSETCC_AVX512(Op, DAG);
14468
14469   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14470   if (Subtarget->hasAVX512()) {
14471     if (Op1.getSimpleValueType().is512BitVector() ||
14472         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14473         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14474       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14475
14476     // In AVX-512 architecture setcc returns mask with i1 elements,
14477     // But there is no compare instruction for i8 and i16 elements in KNL.
14478     // We are not talking about 512-bit operands in this case, these
14479     // types are illegal.
14480     if (MaskResult &&
14481         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14482          OpVT.getVectorElementType().getSizeInBits() >= 8))
14483       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14484                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14485   }
14486
14487   // Lower using XOP integer comparisons.
14488   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14489        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14490     // Translate compare code to XOP PCOM compare mode.
14491     unsigned CmpMode = 0;
14492     switch (SetCCOpcode) {
14493     default: llvm_unreachable("Unexpected SETCC condition");
14494     case ISD::SETULT:
14495     case ISD::SETLT: CmpMode = 0x00; break;
14496     case ISD::SETULE:
14497     case ISD::SETLE: CmpMode = 0x01; break;
14498     case ISD::SETUGT:
14499     case ISD::SETGT: CmpMode = 0x02; break;
14500     case ISD::SETUGE:
14501     case ISD::SETGE: CmpMode = 0x03; break;
14502     case ISD::SETEQ: CmpMode = 0x04; break;
14503     case ISD::SETNE: CmpMode = 0x05; break;
14504     }
14505
14506     // Are we comparing unsigned or signed integers?
14507     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14508       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14509
14510     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14511                        DAG.getConstant(CmpMode, dl, MVT::i8));
14512   }
14513
14514   // We are handling one of the integer comparisons here.  Since SSE only has
14515   // GT and EQ comparisons for integer, swapping operands and multiple
14516   // operations may be required for some comparisons.
14517   unsigned Opc;
14518   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14519   bool Subus = false;
14520
14521   switch (SetCCOpcode) {
14522   default: llvm_unreachable("Unexpected SETCC condition");
14523   case ISD::SETNE:  Invert = true;
14524   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14525   case ISD::SETLT:  Swap = true;
14526   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14527   case ISD::SETGE:  Swap = true;
14528   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14529                     Invert = true; break;
14530   case ISD::SETULT: Swap = true;
14531   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14532                     FlipSigns = true; break;
14533   case ISD::SETUGE: Swap = true;
14534   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14535                     FlipSigns = true; Invert = true; break;
14536   }
14537
14538   // Special case: Use min/max operations for SETULE/SETUGE
14539   MVT VET = VT.getVectorElementType();
14540   bool hasMinMax =
14541        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14542     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14543
14544   if (hasMinMax) {
14545     switch (SetCCOpcode) {
14546     default: break;
14547     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14548     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14549     }
14550
14551     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14552   }
14553
14554   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14555   if (!MinMax && hasSubus) {
14556     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14557     // Op0 u<= Op1:
14558     //   t = psubus Op0, Op1
14559     //   pcmpeq t, <0..0>
14560     switch (SetCCOpcode) {
14561     default: break;
14562     case ISD::SETULT: {
14563       // If the comparison is against a constant we can turn this into a
14564       // setule.  With psubus, setule does not require a swap.  This is
14565       // beneficial because the constant in the register is no longer
14566       // destructed as the destination so it can be hoisted out of a loop.
14567       // Only do this pre-AVX since vpcmp* is no longer destructive.
14568       if (Subtarget->hasAVX())
14569         break;
14570       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14571       if (ULEOp1.getNode()) {
14572         Op1 = ULEOp1;
14573         Subus = true; Invert = false; Swap = false;
14574       }
14575       break;
14576     }
14577     // Psubus is better than flip-sign because it requires no inversion.
14578     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14579     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14580     }
14581
14582     if (Subus) {
14583       Opc = X86ISD::SUBUS;
14584       FlipSigns = false;
14585     }
14586   }
14587
14588   if (Swap)
14589     std::swap(Op0, Op1);
14590
14591   // Check that the operation in question is available (most are plain SSE2,
14592   // but PCMPGTQ and PCMPEQQ have different requirements).
14593   if (VT == MVT::v2i64) {
14594     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14595       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14596
14597       // First cast everything to the right type.
14598       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14599       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14600
14601       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14602       // bits of the inputs before performing those operations. The lower
14603       // compare is always unsigned.
14604       SDValue SB;
14605       if (FlipSigns) {
14606         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14607       } else {
14608         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14609         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14610         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14611                          Sign, Zero, Sign, Zero);
14612       }
14613       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14614       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14615
14616       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14617       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14618       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14619
14620       // Create masks for only the low parts/high parts of the 64 bit integers.
14621       static const int MaskHi[] = { 1, 1, 3, 3 };
14622       static const int MaskLo[] = { 0, 0, 2, 2 };
14623       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14624       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14625       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14626
14627       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14628       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14629
14630       if (Invert)
14631         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14632
14633       return DAG.getBitcast(VT, Result);
14634     }
14635
14636     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14637       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14638       // pcmpeqd + pshufd + pand.
14639       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14640
14641       // First cast everything to the right type.
14642       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14643       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14644
14645       // Do the compare.
14646       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14647
14648       // Make sure the lower and upper halves are both all-ones.
14649       static const int Mask[] = { 1, 0, 3, 2 };
14650       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14651       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14652
14653       if (Invert)
14654         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14655
14656       return DAG.getBitcast(VT, Result);
14657     }
14658   }
14659
14660   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14661   // bits of the inputs before performing those operations.
14662   if (FlipSigns) {
14663     MVT EltVT = VT.getVectorElementType();
14664     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14665                                  VT);
14666     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14667     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14668   }
14669
14670   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14671
14672   // If the logical-not of the result is required, perform that now.
14673   if (Invert)
14674     Result = DAG.getNOT(dl, Result, VT);
14675
14676   if (MinMax)
14677     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14678
14679   if (Subus)
14680     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14681                          getZeroVector(VT, Subtarget, DAG, dl));
14682
14683   return Result;
14684 }
14685
14686 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14687
14688   MVT VT = Op.getSimpleValueType();
14689
14690   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14691
14692   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14693          && "SetCC type must be 8-bit or 1-bit integer");
14694   SDValue Op0 = Op.getOperand(0);
14695   SDValue Op1 = Op.getOperand(1);
14696   SDLoc dl(Op);
14697   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14698
14699   // Optimize to BT if possible.
14700   // Lower (X & (1 << N)) == 0 to BT(X, N).
14701   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14702   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14703   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14704       isNullConstant(Op1) &&
14705       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14706     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14707       if (VT == MVT::i1)
14708         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14709       return NewSetCC;
14710     }
14711   }
14712
14713   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14714   // these.
14715   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14716       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14717
14718     // If the input is a setcc, then reuse the input setcc or use a new one with
14719     // the inverted condition.
14720     if (Op0.getOpcode() == X86ISD::SETCC) {
14721       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14722       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14723       if (!Invert)
14724         return Op0;
14725
14726       CCode = X86::GetOppositeBranchCondition(CCode);
14727       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14728                                   DAG.getConstant(CCode, dl, MVT::i8),
14729                                   Op0.getOperand(1));
14730       if (VT == MVT::i1)
14731         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14732       return SetCC;
14733     }
14734   }
14735   if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14736       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14737
14738     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14739     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14740   }
14741
14742   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14743   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14744   if (X86CC == X86::COND_INVALID)
14745     return SDValue();
14746
14747   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14748   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14749   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14750                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14751   if (VT == MVT::i1)
14752     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14753   return SetCC;
14754 }
14755
14756 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14757   SDValue LHS = Op.getOperand(0);
14758   SDValue RHS = Op.getOperand(1);
14759   SDValue Carry = Op.getOperand(2);
14760   SDValue Cond = Op.getOperand(3);
14761   SDLoc DL(Op);
14762
14763   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14764   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14765
14766   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14767   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14768   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14769   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14770                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14771 }
14772
14773 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14774 static bool isX86LogicalCmp(SDValue Op) {
14775   unsigned Opc = Op.getNode()->getOpcode();
14776   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14777       Opc == X86ISD::SAHF)
14778     return true;
14779   if (Op.getResNo() == 1 &&
14780       (Opc == X86ISD::ADD ||
14781        Opc == X86ISD::SUB ||
14782        Opc == X86ISD::ADC ||
14783        Opc == X86ISD::SBB ||
14784        Opc == X86ISD::SMUL ||
14785        Opc == X86ISD::UMUL ||
14786        Opc == X86ISD::INC ||
14787        Opc == X86ISD::DEC ||
14788        Opc == X86ISD::OR ||
14789        Opc == X86ISD::XOR ||
14790        Opc == X86ISD::AND))
14791     return true;
14792
14793   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14794     return true;
14795
14796   return false;
14797 }
14798
14799 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14800   if (V.getOpcode() != ISD::TRUNCATE)
14801     return false;
14802
14803   SDValue VOp0 = V.getOperand(0);
14804   unsigned InBits = VOp0.getValueSizeInBits();
14805   unsigned Bits = V.getValueSizeInBits();
14806   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14807 }
14808
14809 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14810   bool addTest = true;
14811   SDValue Cond  = Op.getOperand(0);
14812   SDValue Op1 = Op.getOperand(1);
14813   SDValue Op2 = Op.getOperand(2);
14814   SDLoc DL(Op);
14815   MVT VT = Op1.getSimpleValueType();
14816   SDValue CC;
14817
14818   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14819   // are available or VBLENDV if AVX is available.
14820   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14821   if (Cond.getOpcode() == ISD::SETCC &&
14822       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14823        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14824       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14825     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14826     int SSECC = translateX86FSETCC(
14827         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14828
14829     if (SSECC != 8) {
14830       if (Subtarget->hasAVX512()) {
14831         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14832                                   DAG.getConstant(SSECC, DL, MVT::i8));
14833         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14834       }
14835
14836       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14837                                 DAG.getConstant(SSECC, DL, MVT::i8));
14838
14839       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14840       // of 3 logic instructions for size savings and potentially speed.
14841       // Unfortunately, there is no scalar form of VBLENDV.
14842
14843       // If either operand is a constant, don't try this. We can expect to
14844       // optimize away at least one of the logic instructions later in that
14845       // case, so that sequence would be faster than a variable blend.
14846
14847       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14848       // uses XMM0 as the selection register. That may need just as many
14849       // instructions as the AND/ANDN/OR sequence due to register moves, so
14850       // don't bother.
14851
14852       if (Subtarget->hasAVX() &&
14853           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14854
14855         // Convert to vectors, do a VSELECT, and convert back to scalar.
14856         // All of the conversions should be optimized away.
14857
14858         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14859         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14860         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14861         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14862
14863         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14864         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14865
14866         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14867
14868         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14869                            VSel, DAG.getIntPtrConstant(0, DL));
14870       }
14871       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14872       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14873       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14874     }
14875   }
14876
14877   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
14878     SDValue Op1Scalar;
14879     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14880       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14881     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14882       Op1Scalar = Op1.getOperand(0);
14883     SDValue Op2Scalar;
14884     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14885       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14886     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14887       Op2Scalar = Op2.getOperand(0);
14888     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14889       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14890                                       Op1Scalar.getValueType(),
14891                                       Cond, Op1Scalar, Op2Scalar);
14892       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14893         return DAG.getBitcast(VT, newSelect);
14894       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14895       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14896                          DAG.getIntPtrConstant(0, DL));
14897     }
14898   }
14899
14900   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14901     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14902     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14903                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14904     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14905                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14906     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14907                                     Cond, Op1, Op2);
14908     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14909   }
14910
14911   if (Cond.getOpcode() == ISD::SETCC) {
14912     SDValue NewCond = LowerSETCC(Cond, DAG);
14913     if (NewCond.getNode())
14914       Cond = NewCond;
14915   }
14916
14917   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14918   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14919   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14920   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14921   if (Cond.getOpcode() == X86ISD::SETCC &&
14922       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14923       isNullConstant(Cond.getOperand(1).getOperand(1))) {
14924     SDValue Cmp = Cond.getOperand(1);
14925
14926     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14927
14928     if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
14929         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14930       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
14931
14932       SDValue CmpOp0 = Cmp.getOperand(0);
14933       // Apply further optimizations for special cases
14934       // (select (x != 0), -1, 0) -> neg & sbb
14935       // (select (x == 0), 0, -1) -> neg & sbb
14936       if (isNullConstant(Y) &&
14937             (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
14938           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14939           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14940                                     DAG.getConstant(0, DL,
14941                                                     CmpOp0.getValueType()),
14942                                     CmpOp0);
14943           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14944                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14945                                     SDValue(Neg.getNode(), 1));
14946           return Res;
14947         }
14948
14949       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14950                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14951       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14952
14953       SDValue Res =   // Res = 0 or -1.
14954         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14955                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14956
14957       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
14958         Res = DAG.getNOT(DL, Res, Res.getValueType());
14959
14960       if (!isNullConstant(Op2))
14961         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14962       return Res;
14963     }
14964   }
14965
14966   // Look past (and (setcc_carry (cmp ...)), 1).
14967   if (Cond.getOpcode() == ISD::AND &&
14968       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
14969       isOneConstant(Cond.getOperand(1)))
14970     Cond = Cond.getOperand(0);
14971
14972   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14973   // setting operand in place of the X86ISD::SETCC.
14974   unsigned CondOpcode = Cond.getOpcode();
14975   if (CondOpcode == X86ISD::SETCC ||
14976       CondOpcode == X86ISD::SETCC_CARRY) {
14977     CC = Cond.getOperand(0);
14978
14979     SDValue Cmp = Cond.getOperand(1);
14980     unsigned Opc = Cmp.getOpcode();
14981     MVT VT = Op.getSimpleValueType();
14982
14983     bool IllegalFPCMov = false;
14984     if (VT.isFloatingPoint() && !VT.isVector() &&
14985         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14986       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14987
14988     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14989         Opc == X86ISD::BT) { // FIXME
14990       Cond = Cmp;
14991       addTest = false;
14992     }
14993   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14994              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14995              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14996               Cond.getOperand(0).getValueType() != MVT::i8)) {
14997     SDValue LHS = Cond.getOperand(0);
14998     SDValue RHS = Cond.getOperand(1);
14999     unsigned X86Opcode;
15000     unsigned X86Cond;
15001     SDVTList VTs;
15002     switch (CondOpcode) {
15003     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15004     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15005     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15006     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15007     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15008     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15009     default: llvm_unreachable("unexpected overflowing operator");
15010     }
15011     if (CondOpcode == ISD::UMULO)
15012       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15013                           MVT::i32);
15014     else
15015       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15016
15017     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15018
15019     if (CondOpcode == ISD::UMULO)
15020       Cond = X86Op.getValue(2);
15021     else
15022       Cond = X86Op.getValue(1);
15023
15024     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15025     addTest = false;
15026   }
15027
15028   if (addTest) {
15029     // Look past the truncate if the high bits are known zero.
15030     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15031       Cond = Cond.getOperand(0);
15032
15033     // We know the result of AND is compared against zero. Try to match
15034     // it to BT.
15035     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15036       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15037         CC = NewSetCC.getOperand(0);
15038         Cond = NewSetCC.getOperand(1);
15039         addTest = false;
15040       }
15041     }
15042   }
15043
15044   if (addTest) {
15045     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15046     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15047   }
15048
15049   // a <  b ? -1 :  0 -> RES = ~setcc_carry
15050   // a <  b ?  0 : -1 -> RES = setcc_carry
15051   // a >= b ? -1 :  0 -> RES = setcc_carry
15052   // a >= b ?  0 : -1 -> RES = ~setcc_carry
15053   if (Cond.getOpcode() == X86ISD::SUB) {
15054     Cond = ConvertCmpIfNecessary(Cond, DAG);
15055     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15056
15057     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15058         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15059         (isNullConstant(Op1) || isNullConstant(Op2))) {
15060       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15061                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15062                                 Cond);
15063       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15064         return DAG.getNOT(DL, Res, Res.getValueType());
15065       return Res;
15066     }
15067   }
15068
15069   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15070   // widen the cmov and push the truncate through. This avoids introducing a new
15071   // branch during isel and doesn't add any extensions.
15072   if (Op.getValueType() == MVT::i8 &&
15073       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15074     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15075     if (T1.getValueType() == T2.getValueType() &&
15076         // Blacklist CopyFromReg to avoid partial register stalls.
15077         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15078       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15079       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15080       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15081     }
15082   }
15083
15084   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15085   // condition is true.
15086   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15087   SDValue Ops[] = { Op2, Op1, CC, Cond };
15088   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15089 }
15090
15091 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15092                                        const X86Subtarget *Subtarget,
15093                                        SelectionDAG &DAG) {
15094   MVT VT = Op->getSimpleValueType(0);
15095   SDValue In = Op->getOperand(0);
15096   MVT InVT = In.getSimpleValueType();
15097   MVT VTElt = VT.getVectorElementType();
15098   MVT InVTElt = InVT.getVectorElementType();
15099   SDLoc dl(Op);
15100
15101   // SKX processor
15102   if ((InVTElt == MVT::i1) &&
15103       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15104         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15105
15106        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15107         VTElt.getSizeInBits() <= 16)) ||
15108
15109        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15110         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15111
15112        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15113         VTElt.getSizeInBits() >= 32))))
15114     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15115
15116   unsigned int NumElts = VT.getVectorNumElements();
15117
15118   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15119     return SDValue();
15120
15121   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15122     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15123       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15124     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15125   }
15126
15127   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15128   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15129   SDValue NegOne =
15130    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15131                    ExtVT);
15132   SDValue Zero =
15133    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15134
15135   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15136   if (VT.is512BitVector())
15137     return V;
15138   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15139 }
15140
15141 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15142                                              const X86Subtarget *Subtarget,
15143                                              SelectionDAG &DAG) {
15144   SDValue In = Op->getOperand(0);
15145   MVT VT = Op->getSimpleValueType(0);
15146   MVT InVT = In.getSimpleValueType();
15147   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15148
15149   MVT InSVT = InVT.getVectorElementType();
15150   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15151
15152   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15153     return SDValue();
15154   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15155     return SDValue();
15156
15157   SDLoc dl(Op);
15158
15159   // SSE41 targets can use the pmovsx* instructions directly.
15160   if (Subtarget->hasSSE41())
15161     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15162
15163   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15164   SDValue Curr = In;
15165   MVT CurrVT = InVT;
15166
15167   // As SRAI is only available on i16/i32 types, we expand only up to i32
15168   // and handle i64 separately.
15169   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15170     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15171     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15172     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15173     Curr = DAG.getBitcast(CurrVT, Curr);
15174   }
15175
15176   SDValue SignExt = Curr;
15177   if (CurrVT != InVT) {
15178     unsigned SignExtShift =
15179         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15180     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15181                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15182   }
15183
15184   if (CurrVT == VT)
15185     return SignExt;
15186
15187   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15188     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15189                                DAG.getConstant(31, dl, MVT::i8));
15190     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15191     return DAG.getBitcast(VT, Ext);
15192   }
15193
15194   return SDValue();
15195 }
15196
15197 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15198                                 SelectionDAG &DAG) {
15199   MVT VT = Op->getSimpleValueType(0);
15200   SDValue In = Op->getOperand(0);
15201   MVT InVT = In.getSimpleValueType();
15202   SDLoc dl(Op);
15203
15204   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15205     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15206
15207   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15208       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15209       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15210     return SDValue();
15211
15212   if (Subtarget->hasInt256())
15213     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15214
15215   // Optimize vectors in AVX mode
15216   // Sign extend  v8i16 to v8i32 and
15217   //              v4i32 to v4i64
15218   //
15219   // Divide input vector into two parts
15220   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15221   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15222   // concat the vectors to original VT
15223
15224   unsigned NumElems = InVT.getVectorNumElements();
15225   SDValue Undef = DAG.getUNDEF(InVT);
15226
15227   SmallVector<int,8> ShufMask1(NumElems, -1);
15228   for (unsigned i = 0; i != NumElems/2; ++i)
15229     ShufMask1[i] = i;
15230
15231   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15232
15233   SmallVector<int,8> ShufMask2(NumElems, -1);
15234   for (unsigned i = 0; i != NumElems/2; ++i)
15235     ShufMask2[i] = i + NumElems/2;
15236
15237   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15238
15239   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15240                                 VT.getVectorNumElements()/2);
15241
15242   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15243   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15244
15245   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15246 }
15247
15248 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15249 // may emit an illegal shuffle but the expansion is still better than scalar
15250 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15251 // we'll emit a shuffle and a arithmetic shift.
15252 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15253 // TODO: It is possible to support ZExt by zeroing the undef values during
15254 // the shuffle phase or after the shuffle.
15255 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15256                                  SelectionDAG &DAG) {
15257   MVT RegVT = Op.getSimpleValueType();
15258   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15259   assert(RegVT.isInteger() &&
15260          "We only custom lower integer vector sext loads.");
15261
15262   // Nothing useful we can do without SSE2 shuffles.
15263   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15264
15265   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15266   SDLoc dl(Ld);
15267   EVT MemVT = Ld->getMemoryVT();
15268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15269   unsigned RegSz = RegVT.getSizeInBits();
15270
15271   ISD::LoadExtType Ext = Ld->getExtensionType();
15272
15273   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15274          && "Only anyext and sext are currently implemented.");
15275   assert(MemVT != RegVT && "Cannot extend to the same type");
15276   assert(MemVT.isVector() && "Must load a vector from memory");
15277
15278   unsigned NumElems = RegVT.getVectorNumElements();
15279   unsigned MemSz = MemVT.getSizeInBits();
15280   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15281
15282   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15283     // The only way in which we have a legal 256-bit vector result but not the
15284     // integer 256-bit operations needed to directly lower a sextload is if we
15285     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15286     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15287     // correctly legalized. We do this late to allow the canonical form of
15288     // sextload to persist throughout the rest of the DAG combiner -- it wants
15289     // to fold together any extensions it can, and so will fuse a sign_extend
15290     // of an sextload into a sextload targeting a wider value.
15291     SDValue Load;
15292     if (MemSz == 128) {
15293       // Just switch this to a normal load.
15294       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15295                                        "it must be a legal 128-bit vector "
15296                                        "type!");
15297       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15298                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15299                   Ld->isInvariant(), Ld->getAlignment());
15300     } else {
15301       assert(MemSz < 128 &&
15302              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15303       // Do an sext load to a 128-bit vector type. We want to use the same
15304       // number of elements, but elements half as wide. This will end up being
15305       // recursively lowered by this routine, but will succeed as we definitely
15306       // have all the necessary features if we're using AVX1.
15307       EVT HalfEltVT =
15308           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15309       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15310       Load =
15311           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15312                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15313                          Ld->isNonTemporal(), Ld->isInvariant(),
15314                          Ld->getAlignment());
15315     }
15316
15317     // Replace chain users with the new chain.
15318     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15319     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15320
15321     // Finally, do a normal sign-extend to the desired register.
15322     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15323   }
15324
15325   // All sizes must be a power of two.
15326   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15327          "Non-power-of-two elements are not custom lowered!");
15328
15329   // Attempt to load the original value using scalar loads.
15330   // Find the largest scalar type that divides the total loaded size.
15331   MVT SclrLoadTy = MVT::i8;
15332   for (MVT Tp : MVT::integer_valuetypes()) {
15333     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15334       SclrLoadTy = Tp;
15335     }
15336   }
15337
15338   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15339   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15340       (64 <= MemSz))
15341     SclrLoadTy = MVT::f64;
15342
15343   // Calculate the number of scalar loads that we need to perform
15344   // in order to load our vector from memory.
15345   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15346
15347   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15348          "Can only lower sext loads with a single scalar load!");
15349
15350   unsigned loadRegZize = RegSz;
15351   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15352     loadRegZize = 128;
15353
15354   // Represent our vector as a sequence of elements which are the
15355   // largest scalar that we can load.
15356   EVT LoadUnitVecVT = EVT::getVectorVT(
15357       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15358
15359   // Represent the data using the same element type that is stored in
15360   // memory. In practice, we ''widen'' MemVT.
15361   EVT WideVecVT =
15362       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15363                        loadRegZize / MemVT.getScalarSizeInBits());
15364
15365   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15366          "Invalid vector type");
15367
15368   // We can't shuffle using an illegal type.
15369   assert(TLI.isTypeLegal(WideVecVT) &&
15370          "We only lower types that form legal widened vector types");
15371
15372   SmallVector<SDValue, 8> Chains;
15373   SDValue Ptr = Ld->getBasePtr();
15374   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15375                                       TLI.getPointerTy(DAG.getDataLayout()));
15376   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15377
15378   for (unsigned i = 0; i < NumLoads; ++i) {
15379     // Perform a single load.
15380     SDValue ScalarLoad =
15381         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15382                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15383                     Ld->getAlignment());
15384     Chains.push_back(ScalarLoad.getValue(1));
15385     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15386     // another round of DAGCombining.
15387     if (i == 0)
15388       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15389     else
15390       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15391                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15392
15393     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15394   }
15395
15396   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15397
15398   // Bitcast the loaded value to a vector of the original element type, in
15399   // the size of the target vector type.
15400   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15401   unsigned SizeRatio = RegSz / MemSz;
15402
15403   if (Ext == ISD::SEXTLOAD) {
15404     // If we have SSE4.1, we can directly emit a VSEXT node.
15405     if (Subtarget->hasSSE41()) {
15406       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15407       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15408       return Sext;
15409     }
15410
15411     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15412     // lanes.
15413     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15414            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15415
15416     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15417     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15418     return Shuff;
15419   }
15420
15421   // Redistribute the loaded elements into the different locations.
15422   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15423   for (unsigned i = 0; i != NumElems; ++i)
15424     ShuffleVec[i * SizeRatio] = i;
15425
15426   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15427                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15428
15429   // Bitcast to the requested type.
15430   Shuff = DAG.getBitcast(RegVT, Shuff);
15431   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15432   return Shuff;
15433 }
15434
15435 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15436 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15437 // from the AND / OR.
15438 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15439   Opc = Op.getOpcode();
15440   if (Opc != ISD::OR && Opc != ISD::AND)
15441     return false;
15442   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15443           Op.getOperand(0).hasOneUse() &&
15444           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15445           Op.getOperand(1).hasOneUse());
15446 }
15447
15448 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15449 // 1 and that the SETCC node has a single use.
15450 static bool isXor1OfSetCC(SDValue Op) {
15451   if (Op.getOpcode() != ISD::XOR)
15452     return false;
15453   if (isOneConstant(Op.getOperand(1)))
15454     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15455            Op.getOperand(0).hasOneUse();
15456   return false;
15457 }
15458
15459 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15460   bool addTest = true;
15461   SDValue Chain = Op.getOperand(0);
15462   SDValue Cond  = Op.getOperand(1);
15463   SDValue Dest  = Op.getOperand(2);
15464   SDLoc dl(Op);
15465   SDValue CC;
15466   bool Inverted = false;
15467
15468   if (Cond.getOpcode() == ISD::SETCC) {
15469     // Check for setcc([su]{add,sub,mul}o == 0).
15470     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15471         isNullConstant(Cond.getOperand(1)) &&
15472         Cond.getOperand(0).getResNo() == 1 &&
15473         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15474          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15475          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15476          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15477          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15478          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15479       Inverted = true;
15480       Cond = Cond.getOperand(0);
15481     } else {
15482       SDValue NewCond = LowerSETCC(Cond, DAG);
15483       if (NewCond.getNode())
15484         Cond = NewCond;
15485     }
15486   }
15487 #if 0
15488   // FIXME: LowerXALUO doesn't handle these!!
15489   else if (Cond.getOpcode() == X86ISD::ADD  ||
15490            Cond.getOpcode() == X86ISD::SUB  ||
15491            Cond.getOpcode() == X86ISD::SMUL ||
15492            Cond.getOpcode() == X86ISD::UMUL)
15493     Cond = LowerXALUO(Cond, DAG);
15494 #endif
15495
15496   // Look pass (and (setcc_carry (cmp ...)), 1).
15497   if (Cond.getOpcode() == ISD::AND &&
15498       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15499       isOneConstant(Cond.getOperand(1)))
15500     Cond = Cond.getOperand(0);
15501
15502   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15503   // setting operand in place of the X86ISD::SETCC.
15504   unsigned CondOpcode = Cond.getOpcode();
15505   if (CondOpcode == X86ISD::SETCC ||
15506       CondOpcode == X86ISD::SETCC_CARRY) {
15507     CC = Cond.getOperand(0);
15508
15509     SDValue Cmp = Cond.getOperand(1);
15510     unsigned Opc = Cmp.getOpcode();
15511     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15512     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15513       Cond = Cmp;
15514       addTest = false;
15515     } else {
15516       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15517       default: break;
15518       case X86::COND_O:
15519       case X86::COND_B:
15520         // These can only come from an arithmetic instruction with overflow,
15521         // e.g. SADDO, UADDO.
15522         Cond = Cond.getNode()->getOperand(1);
15523         addTest = false;
15524         break;
15525       }
15526     }
15527   }
15528   CondOpcode = Cond.getOpcode();
15529   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15530       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15531       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15532        Cond.getOperand(0).getValueType() != MVT::i8)) {
15533     SDValue LHS = Cond.getOperand(0);
15534     SDValue RHS = Cond.getOperand(1);
15535     unsigned X86Opcode;
15536     unsigned X86Cond;
15537     SDVTList VTs;
15538     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15539     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15540     // X86ISD::INC).
15541     switch (CondOpcode) {
15542     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15543     case ISD::SADDO:
15544       if (isOneConstant(RHS)) {
15545           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15546           break;
15547         }
15548       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15549     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15550     case ISD::SSUBO:
15551       if (isOneConstant(RHS)) {
15552           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15553           break;
15554         }
15555       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15556     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15557     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15558     default: llvm_unreachable("unexpected overflowing operator");
15559     }
15560     if (Inverted)
15561       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15562     if (CondOpcode == ISD::UMULO)
15563       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15564                           MVT::i32);
15565     else
15566       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15567
15568     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15569
15570     if (CondOpcode == ISD::UMULO)
15571       Cond = X86Op.getValue(2);
15572     else
15573       Cond = X86Op.getValue(1);
15574
15575     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15576     addTest = false;
15577   } else {
15578     unsigned CondOpc;
15579     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15580       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15581       if (CondOpc == ISD::OR) {
15582         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15583         // two branches instead of an explicit OR instruction with a
15584         // separate test.
15585         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15586             isX86LogicalCmp(Cmp)) {
15587           CC = Cond.getOperand(0).getOperand(0);
15588           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15589                               Chain, Dest, CC, Cmp);
15590           CC = Cond.getOperand(1).getOperand(0);
15591           Cond = Cmp;
15592           addTest = false;
15593         }
15594       } else { // ISD::AND
15595         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15596         // two branches instead of an explicit AND instruction with a
15597         // separate test. However, we only do this if this block doesn't
15598         // have a fall-through edge, because this requires an explicit
15599         // jmp when the condition is false.
15600         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15601             isX86LogicalCmp(Cmp) &&
15602             Op.getNode()->hasOneUse()) {
15603           X86::CondCode CCode =
15604             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15605           CCode = X86::GetOppositeBranchCondition(CCode);
15606           CC = DAG.getConstant(CCode, dl, MVT::i8);
15607           SDNode *User = *Op.getNode()->use_begin();
15608           // Look for an unconditional branch following this conditional branch.
15609           // We need this because we need to reverse the successors in order
15610           // to implement FCMP_OEQ.
15611           if (User->getOpcode() == ISD::BR) {
15612             SDValue FalseBB = User->getOperand(1);
15613             SDNode *NewBR =
15614               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15615             assert(NewBR == User);
15616             (void)NewBR;
15617             Dest = FalseBB;
15618
15619             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15620                                 Chain, Dest, CC, Cmp);
15621             X86::CondCode CCode =
15622               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15623             CCode = X86::GetOppositeBranchCondition(CCode);
15624             CC = DAG.getConstant(CCode, dl, MVT::i8);
15625             Cond = Cmp;
15626             addTest = false;
15627           }
15628         }
15629       }
15630     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15631       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15632       // It should be transformed during dag combiner except when the condition
15633       // is set by a arithmetics with overflow node.
15634       X86::CondCode CCode =
15635         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15636       CCode = X86::GetOppositeBranchCondition(CCode);
15637       CC = DAG.getConstant(CCode, dl, MVT::i8);
15638       Cond = Cond.getOperand(0).getOperand(1);
15639       addTest = false;
15640     } else if (Cond.getOpcode() == ISD::SETCC &&
15641                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15642       // For FCMP_OEQ, we can emit
15643       // two branches instead of an explicit AND instruction with a
15644       // separate test. However, we only do this if this block doesn't
15645       // have a fall-through edge, because this requires an explicit
15646       // jmp when the condition is false.
15647       if (Op.getNode()->hasOneUse()) {
15648         SDNode *User = *Op.getNode()->use_begin();
15649         // Look for an unconditional branch following this conditional branch.
15650         // We need this because we need to reverse the successors in order
15651         // to implement FCMP_OEQ.
15652         if (User->getOpcode() == ISD::BR) {
15653           SDValue FalseBB = User->getOperand(1);
15654           SDNode *NewBR =
15655             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15656           assert(NewBR == User);
15657           (void)NewBR;
15658           Dest = FalseBB;
15659
15660           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15661                                     Cond.getOperand(0), Cond.getOperand(1));
15662           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15663           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15664           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15665                               Chain, Dest, CC, Cmp);
15666           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15667           Cond = Cmp;
15668           addTest = false;
15669         }
15670       }
15671     } else if (Cond.getOpcode() == ISD::SETCC &&
15672                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15673       // For FCMP_UNE, we can emit
15674       // two branches instead of an explicit AND instruction with a
15675       // separate test. However, we only do this if this block doesn't
15676       // have a fall-through edge, because this requires an explicit
15677       // jmp when the condition is false.
15678       if (Op.getNode()->hasOneUse()) {
15679         SDNode *User = *Op.getNode()->use_begin();
15680         // Look for an unconditional branch following this conditional branch.
15681         // We need this because we need to reverse the successors in order
15682         // to implement FCMP_UNE.
15683         if (User->getOpcode() == ISD::BR) {
15684           SDValue FalseBB = User->getOperand(1);
15685           SDNode *NewBR =
15686             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15687           assert(NewBR == User);
15688           (void)NewBR;
15689
15690           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15691                                     Cond.getOperand(0), Cond.getOperand(1));
15692           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15693           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15694           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15695                               Chain, Dest, CC, Cmp);
15696           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15697           Cond = Cmp;
15698           addTest = false;
15699           Dest = FalseBB;
15700         }
15701       }
15702     }
15703   }
15704
15705   if (addTest) {
15706     // Look pass the truncate if the high bits are known zero.
15707     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15708         Cond = Cond.getOperand(0);
15709
15710     // We know the result of AND is compared against zero. Try to match
15711     // it to BT.
15712     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15713       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15714         CC = NewSetCC.getOperand(0);
15715         Cond = NewSetCC.getOperand(1);
15716         addTest = false;
15717       }
15718     }
15719   }
15720
15721   if (addTest) {
15722     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15723     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15724     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15725   }
15726   Cond = ConvertCmpIfNecessary(Cond, DAG);
15727   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15728                      Chain, Dest, CC, Cond);
15729 }
15730
15731 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15732 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15733 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15734 // that the guard pages used by the OS virtual memory manager are allocated in
15735 // correct sequence.
15736 SDValue
15737 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15738                                            SelectionDAG &DAG) const {
15739   MachineFunction &MF = DAG.getMachineFunction();
15740   bool SplitStack = MF.shouldSplitStack();
15741   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15742                SplitStack;
15743   SDLoc dl(Op);
15744
15745   // Get the inputs.
15746   SDNode *Node = Op.getNode();
15747   SDValue Chain = Op.getOperand(0);
15748   SDValue Size  = Op.getOperand(1);
15749   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15750   EVT VT = Node->getValueType(0);
15751
15752   // Chain the dynamic stack allocation so that it doesn't modify the stack
15753   // pointer when other instructions are using the stack.
15754   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15755
15756   bool Is64Bit = Subtarget->is64Bit();
15757   MVT SPTy = getPointerTy(DAG.getDataLayout());
15758
15759   SDValue Result;
15760   if (!Lower) {
15761     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15762     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15763     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15764                     " not tell us which reg is the stack pointer!");
15765     EVT VT = Node->getValueType(0);
15766     SDValue Tmp3 = Node->getOperand(2);
15767
15768     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15769     Chain = SP.getValue(1);
15770     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15771     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15772     unsigned StackAlign = TFI.getStackAlignment();
15773     Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15774     if (Align > StackAlign)
15775       Result = DAG.getNode(ISD::AND, dl, VT, Result,
15776                          DAG.getConstant(-(uint64_t)Align, dl, VT));
15777     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15778   } else if (SplitStack) {
15779     MachineRegisterInfo &MRI = MF.getRegInfo();
15780
15781     if (Is64Bit) {
15782       // The 64 bit implementation of segmented stacks needs to clobber both r10
15783       // r11. This makes it impossible to use it along with nested parameters.
15784       const Function *F = MF.getFunction();
15785
15786       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15787            I != E; ++I)
15788         if (I->hasNestAttr())
15789           report_fatal_error("Cannot use segmented stacks with functions that "
15790                              "have nested arguments.");
15791     }
15792
15793     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15794     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15795     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15796     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15797                                 DAG.getRegister(Vreg, SPTy));
15798   } else {
15799     SDValue Flag;
15800     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15801
15802     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15803     Flag = Chain.getValue(1);
15804     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15805
15806     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15807
15808     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15809     unsigned SPReg = RegInfo->getStackRegister();
15810     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15811     Chain = SP.getValue(1);
15812
15813     if (Align) {
15814       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15815                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15816       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15817     }
15818
15819     Result = SP;
15820   }
15821
15822   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15823                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
15824
15825   SDValue Ops[2] = {Result, Chain};
15826   return DAG.getMergeValues(Ops, dl);
15827 }
15828
15829 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15830   MachineFunction &MF = DAG.getMachineFunction();
15831   auto PtrVT = getPointerTy(MF.getDataLayout());
15832   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15833
15834   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15835   SDLoc DL(Op);
15836
15837   if (!Subtarget->is64Bit() ||
15838       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15839     // vastart just stores the address of the VarArgsFrameIndex slot into the
15840     // memory location argument.
15841     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15842     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15843                         MachinePointerInfo(SV), false, false, 0);
15844   }
15845
15846   // __va_list_tag:
15847   //   gp_offset         (0 - 6 * 8)
15848   //   fp_offset         (48 - 48 + 8 * 16)
15849   //   overflow_arg_area (point to parameters coming in memory).
15850   //   reg_save_area
15851   SmallVector<SDValue, 8> MemOps;
15852   SDValue FIN = Op.getOperand(1);
15853   // Store gp_offset
15854   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15855                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15856                                                DL, MVT::i32),
15857                                FIN, MachinePointerInfo(SV), false, false, 0);
15858   MemOps.push_back(Store);
15859
15860   // Store fp_offset
15861   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15862   Store = DAG.getStore(Op.getOperand(0), DL,
15863                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15864                                        MVT::i32),
15865                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15866   MemOps.push_back(Store);
15867
15868   // Store ptr to overflow_arg_area
15869   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15870   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15871   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15872                        MachinePointerInfo(SV, 8),
15873                        false, false, 0);
15874   MemOps.push_back(Store);
15875
15876   // Store ptr to reg_save_area.
15877   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15878       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15879   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15880   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15881       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15882   MemOps.push_back(Store);
15883   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15884 }
15885
15886 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15887   assert(Subtarget->is64Bit() &&
15888          "LowerVAARG only handles 64-bit va_arg!");
15889   assert(Op.getNode()->getNumOperands() == 4);
15890
15891   MachineFunction &MF = DAG.getMachineFunction();
15892   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15893     // The Win64 ABI uses char* instead of a structure.
15894     return DAG.expandVAArg(Op.getNode());
15895
15896   SDValue Chain = Op.getOperand(0);
15897   SDValue SrcPtr = Op.getOperand(1);
15898   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15899   unsigned Align = Op.getConstantOperandVal(3);
15900   SDLoc dl(Op);
15901
15902   EVT ArgVT = Op.getNode()->getValueType(0);
15903   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15904   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15905   uint8_t ArgMode;
15906
15907   // Decide which area this value should be read from.
15908   // TODO: Implement the AMD64 ABI in its entirety. This simple
15909   // selection mechanism works only for the basic types.
15910   if (ArgVT == MVT::f80) {
15911     llvm_unreachable("va_arg for f80 not yet implemented");
15912   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15913     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15914   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15915     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15916   } else {
15917     llvm_unreachable("Unhandled argument type in LowerVAARG");
15918   }
15919
15920   if (ArgMode == 2) {
15921     // Sanity Check: Make sure using fp_offset makes sense.
15922     assert(!Subtarget->useSoftFloat() &&
15923            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15924            Subtarget->hasSSE1());
15925   }
15926
15927   // Insert VAARG_64 node into the DAG
15928   // VAARG_64 returns two values: Variable Argument Address, Chain
15929   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15930                        DAG.getConstant(ArgMode, dl, MVT::i8),
15931                        DAG.getConstant(Align, dl, MVT::i32)};
15932   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15933   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15934                                           VTs, InstOps, MVT::i64,
15935                                           MachinePointerInfo(SV),
15936                                           /*Align=*/0,
15937                                           /*Volatile=*/false,
15938                                           /*ReadMem=*/true,
15939                                           /*WriteMem=*/true);
15940   Chain = VAARG.getValue(1);
15941
15942   // Load the next argument and return it
15943   return DAG.getLoad(ArgVT, dl,
15944                      Chain,
15945                      VAARG,
15946                      MachinePointerInfo(),
15947                      false, false, false, 0);
15948 }
15949
15950 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15951                            SelectionDAG &DAG) {
15952   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15953   // where a va_list is still an i8*.
15954   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15955   if (Subtarget->isCallingConvWin64(
15956         DAG.getMachineFunction().getFunction()->getCallingConv()))
15957     // Probably a Win64 va_copy.
15958     return DAG.expandVACopy(Op.getNode());
15959
15960   SDValue Chain = Op.getOperand(0);
15961   SDValue DstPtr = Op.getOperand(1);
15962   SDValue SrcPtr = Op.getOperand(2);
15963   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15964   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15965   SDLoc DL(Op);
15966
15967   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15968                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15969                        false, false,
15970                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15971 }
15972
15973 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15974 // amount is a constant. Takes immediate version of shift as input.
15975 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15976                                           SDValue SrcOp, uint64_t ShiftAmt,
15977                                           SelectionDAG &DAG) {
15978   MVT ElementType = VT.getVectorElementType();
15979
15980   // Fold this packed shift into its first operand if ShiftAmt is 0.
15981   if (ShiftAmt == 0)
15982     return SrcOp;
15983
15984   // Check for ShiftAmt >= element width
15985   if (ShiftAmt >= ElementType.getSizeInBits()) {
15986     if (Opc == X86ISD::VSRAI)
15987       ShiftAmt = ElementType.getSizeInBits() - 1;
15988     else
15989       return DAG.getConstant(0, dl, VT);
15990   }
15991
15992   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15993          && "Unknown target vector shift-by-constant node");
15994
15995   // Fold this packed vector shift into a build vector if SrcOp is a
15996   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15997   if (VT == SrcOp.getSimpleValueType() &&
15998       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15999     SmallVector<SDValue, 8> Elts;
16000     unsigned NumElts = SrcOp->getNumOperands();
16001     ConstantSDNode *ND;
16002
16003     switch(Opc) {
16004     default: llvm_unreachable(nullptr);
16005     case X86ISD::VSHLI:
16006       for (unsigned i=0; i!=NumElts; ++i) {
16007         SDValue CurrentOp = SrcOp->getOperand(i);
16008         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16009           Elts.push_back(CurrentOp);
16010           continue;
16011         }
16012         ND = cast<ConstantSDNode>(CurrentOp);
16013         const APInt &C = ND->getAPIntValue();
16014         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16015       }
16016       break;
16017     case X86ISD::VSRLI:
16018       for (unsigned i=0; i!=NumElts; ++i) {
16019         SDValue CurrentOp = SrcOp->getOperand(i);
16020         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16021           Elts.push_back(CurrentOp);
16022           continue;
16023         }
16024         ND = cast<ConstantSDNode>(CurrentOp);
16025         const APInt &C = ND->getAPIntValue();
16026         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16027       }
16028       break;
16029     case X86ISD::VSRAI:
16030       for (unsigned i=0; i!=NumElts; ++i) {
16031         SDValue CurrentOp = SrcOp->getOperand(i);
16032         if (CurrentOp->getOpcode() == ISD::UNDEF) {
16033           Elts.push_back(CurrentOp);
16034           continue;
16035         }
16036         ND = cast<ConstantSDNode>(CurrentOp);
16037         const APInt &C = ND->getAPIntValue();
16038         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16039       }
16040       break;
16041     }
16042
16043     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16044   }
16045
16046   return DAG.getNode(Opc, dl, VT, SrcOp,
16047                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
16048 }
16049
16050 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16051 // may or may not be a constant. Takes immediate version of shift as input.
16052 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16053                                    SDValue SrcOp, SDValue ShAmt,
16054                                    SelectionDAG &DAG) {
16055   MVT SVT = ShAmt.getSimpleValueType();
16056   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16057
16058   // Catch shift-by-constant.
16059   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16060     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16061                                       CShAmt->getZExtValue(), DAG);
16062
16063   // Change opcode to non-immediate version
16064   switch (Opc) {
16065     default: llvm_unreachable("Unknown target vector shift node");
16066     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16067     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16068     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16069   }
16070
16071   const X86Subtarget &Subtarget =
16072       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16073   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16074       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16075     // Let the shuffle legalizer expand this shift amount node.
16076     SDValue Op0 = ShAmt.getOperand(0);
16077     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16078     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16079   } else {
16080     // Need to build a vector containing shift amount.
16081     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16082     SmallVector<SDValue, 4> ShOps;
16083     ShOps.push_back(ShAmt);
16084     if (SVT == MVT::i32) {
16085       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16086       ShOps.push_back(DAG.getUNDEF(SVT));
16087     }
16088     ShOps.push_back(DAG.getUNDEF(SVT));
16089
16090     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16091     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16092   }
16093
16094   // The return type has to be a 128-bit type with the same element
16095   // type as the input type.
16096   MVT EltVT = VT.getVectorElementType();
16097   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16098
16099   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16100   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16101 }
16102
16103 /// \brief Return Mask with the necessary casting or extending
16104 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16105 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16106                            const X86Subtarget *Subtarget,
16107                            SelectionDAG &DAG, SDLoc dl) {
16108
16109   if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16110     // Mask should be extended
16111     Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16112                        MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16113   }
16114
16115   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16116     if (MaskVT == MVT::v64i1) {
16117       assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16118       // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16119       SDValue Lo, Hi;
16120       Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16121                           DAG.getConstant(0, dl, MVT::i32));
16122       Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16123                           DAG.getConstant(1, dl, MVT::i32));
16124
16125       Lo = DAG.getBitcast(MVT::v32i1, Lo);
16126       Hi = DAG.getBitcast(MVT::v32i1, Hi);
16127
16128       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16129     } else {
16130       // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16131       // and bitcast.
16132       MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16133       return DAG.getBitcast(MaskVT,
16134                             DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16135     }
16136
16137   } else {
16138     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16139                                      Mask.getSimpleValueType().getSizeInBits());
16140     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16141     // are extracted by EXTRACT_SUBVECTOR.
16142     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16143                        DAG.getBitcast(BitcastVT, Mask),
16144                        DAG.getIntPtrConstant(0, dl));
16145   }
16146 }
16147
16148 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16149 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16150 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16151 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16152                   SDValue PreservedSrc,
16153                   const X86Subtarget *Subtarget,
16154                   SelectionDAG &DAG) {
16155   MVT VT = Op.getSimpleValueType();
16156   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16157   unsigned OpcodeSelect = ISD::VSELECT;
16158   SDLoc dl(Op);
16159
16160   if (isAllOnesConstant(Mask))
16161     return Op;
16162
16163   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16164
16165   switch (Op.getOpcode()) {
16166   default: break;
16167   case X86ISD::PCMPEQM:
16168   case X86ISD::PCMPGTM:
16169   case X86ISD::CMPM:
16170   case X86ISD::CMPMU:
16171     return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16172   case X86ISD::VFPCLASS:
16173     case X86ISD::VFPCLASSS:
16174     return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16175   case X86ISD::VTRUNC:
16176   case X86ISD::VTRUNCS:
16177   case X86ISD::VTRUNCUS:
16178     // We can't use ISD::VSELECT here because it is not always "Legal"
16179     // for the destination type. For example vpmovqb require only AVX512
16180     // and vselect that can operate on byte element type require BWI
16181     OpcodeSelect = X86ISD::SELECT;
16182     break;
16183   }
16184   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16185     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16186   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16187 }
16188
16189 /// \brief Creates an SDNode for a predicated scalar operation.
16190 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16191 /// The mask is coming as MVT::i8 and it should be truncated
16192 /// to MVT::i1 while lowering masking intrinsics.
16193 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16194 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16195 /// for a scalar instruction.
16196 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16197                                     SDValue PreservedSrc,
16198                                     const X86Subtarget *Subtarget,
16199                                     SelectionDAG &DAG) {
16200   if (isAllOnesConstant(Mask))
16201     return Op;
16202
16203   MVT VT = Op.getSimpleValueType();
16204   SDLoc dl(Op);
16205   // The mask should be of type MVT::i1
16206   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16207
16208   if (Op.getOpcode() == X86ISD::FSETCC)
16209     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16210   if (Op.getOpcode() == X86ISD::VFPCLASS ||
16211       Op.getOpcode() == X86ISD::VFPCLASSS)
16212     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16213
16214   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16215     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16216   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16217 }
16218
16219 static int getSEHRegistrationNodeSize(const Function *Fn) {
16220   if (!Fn->hasPersonalityFn())
16221     report_fatal_error(
16222         "querying registration node size for function without personality");
16223   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16224   // WinEHStatePass for the full struct definition.
16225   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16226   case EHPersonality::MSVC_X86SEH: return 24;
16227   case EHPersonality::MSVC_CXX: return 16;
16228   default: break;
16229   }
16230   report_fatal_error(
16231       "can only recover FP for 32-bit MSVC EH personality functions");
16232 }
16233
16234 /// When the MSVC runtime transfers control to us, either to an outlined
16235 /// function or when returning to a parent frame after catching an exception, we
16236 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16237 /// Here's the math:
16238 ///   RegNodeBase = EntryEBP - RegNodeSize
16239 ///   ParentFP = RegNodeBase - ParentFrameOffset
16240 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16241 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16242 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16243                                    SDValue EntryEBP) {
16244   MachineFunction &MF = DAG.getMachineFunction();
16245   SDLoc dl;
16246
16247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16248   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16249
16250   // It's possible that the parent function no longer has a personality function
16251   // if the exceptional code was optimized away, in which case we just return
16252   // the incoming EBP.
16253   if (!Fn->hasPersonalityFn())
16254     return EntryEBP;
16255
16256   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16257   // registration, or the .set_setframe offset.
16258   MCSymbol *OffsetSym =
16259       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16260           GlobalValue::getRealLinkageName(Fn->getName()));
16261   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16262   SDValue ParentFrameOffset =
16263       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16264
16265   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16266   // prologue to RBP in the parent function.
16267   const X86Subtarget &Subtarget =
16268       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16269   if (Subtarget.is64Bit())
16270     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16271
16272   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16273   // RegNodeBase = EntryEBP - RegNodeSize
16274   // ParentFP = RegNodeBase - ParentFrameOffset
16275   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16276                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16277   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16278 }
16279
16280 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16281                                        SelectionDAG &DAG) {
16282   SDLoc dl(Op);
16283   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16284   MVT VT = Op.getSimpleValueType();
16285   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16286   if (IntrData) {
16287     switch(IntrData->Type) {
16288     case INTR_TYPE_1OP:
16289       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16290     case INTR_TYPE_2OP:
16291       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16292         Op.getOperand(2));
16293     case INTR_TYPE_2OP_IMM8:
16294       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16295                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16296     case INTR_TYPE_3OP:
16297       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16298         Op.getOperand(2), Op.getOperand(3));
16299     case INTR_TYPE_4OP:
16300       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16301         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16302     case INTR_TYPE_1OP_MASK_RM: {
16303       SDValue Src = Op.getOperand(1);
16304       SDValue PassThru = Op.getOperand(2);
16305       SDValue Mask = Op.getOperand(3);
16306       SDValue RoundingMode;
16307       // We allways add rounding mode to the Node.
16308       // If the rounding mode is not specified, we add the
16309       // "current direction" mode.
16310       if (Op.getNumOperands() == 4)
16311         RoundingMode =
16312           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16313       else
16314         RoundingMode = Op.getOperand(4);
16315       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16316       if (IntrWithRoundingModeOpcode != 0)
16317         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16318             X86::STATIC_ROUNDING::CUR_DIRECTION)
16319           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16320                                       dl, Op.getValueType(), Src, RoundingMode),
16321                                       Mask, PassThru, Subtarget, DAG);
16322       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16323                                               RoundingMode),
16324                                   Mask, PassThru, Subtarget, DAG);
16325     }
16326     case INTR_TYPE_1OP_MASK: {
16327       SDValue Src = Op.getOperand(1);
16328       SDValue PassThru = Op.getOperand(2);
16329       SDValue Mask = Op.getOperand(3);
16330       // We add rounding mode to the Node when
16331       //   - RM Opcode is specified and
16332       //   - RM is not "current direction".
16333       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16334       if (IntrWithRoundingModeOpcode != 0) {
16335         SDValue Rnd = Op.getOperand(4);
16336         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16337         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16338           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16339                                       dl, Op.getValueType(),
16340                                       Src, Rnd),
16341                                       Mask, PassThru, Subtarget, DAG);
16342         }
16343       }
16344       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16345                                   Mask, PassThru, Subtarget, DAG);
16346     }
16347     case INTR_TYPE_SCALAR_MASK: {
16348       SDValue Src1 = Op.getOperand(1);
16349       SDValue Src2 = Op.getOperand(2);
16350       SDValue passThru = Op.getOperand(3);
16351       SDValue Mask = Op.getOperand(4);
16352       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16353                                   Mask, passThru, Subtarget, DAG);
16354     }
16355     case INTR_TYPE_SCALAR_MASK_RM: {
16356       SDValue Src1 = Op.getOperand(1);
16357       SDValue Src2 = Op.getOperand(2);
16358       SDValue Src0 = Op.getOperand(3);
16359       SDValue Mask = Op.getOperand(4);
16360       // There are 2 kinds of intrinsics in this group:
16361       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16362       // (2) With rounding mode and sae - 7 operands.
16363       if (Op.getNumOperands() == 6) {
16364         SDValue Sae  = Op.getOperand(5);
16365         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16366         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16367                                                 Sae),
16368                                     Mask, Src0, Subtarget, DAG);
16369       }
16370       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16371       SDValue RoundingMode  = Op.getOperand(5);
16372       SDValue Sae  = Op.getOperand(6);
16373       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16374                                               RoundingMode, Sae),
16375                                   Mask, Src0, Subtarget, DAG);
16376     }
16377     case INTR_TYPE_2OP_MASK:
16378     case INTR_TYPE_2OP_IMM8_MASK: {
16379       SDValue Src1 = Op.getOperand(1);
16380       SDValue Src2 = Op.getOperand(2);
16381       SDValue PassThru = Op.getOperand(3);
16382       SDValue Mask = Op.getOperand(4);
16383
16384       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16385         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16386
16387       // We specify 2 possible opcodes for intrinsics with rounding modes.
16388       // First, we check if the intrinsic may have non-default rounding mode,
16389       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16390       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16391       if (IntrWithRoundingModeOpcode != 0) {
16392         SDValue Rnd = Op.getOperand(5);
16393         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16394         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16395           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16396                                       dl, Op.getValueType(),
16397                                       Src1, Src2, Rnd),
16398                                       Mask, PassThru, Subtarget, DAG);
16399         }
16400       }
16401       // TODO: Intrinsics should have fast-math-flags to propagate.
16402       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16403                                   Mask, PassThru, Subtarget, DAG);
16404     }
16405     case INTR_TYPE_2OP_MASK_RM: {
16406       SDValue Src1 = Op.getOperand(1);
16407       SDValue Src2 = Op.getOperand(2);
16408       SDValue PassThru = Op.getOperand(3);
16409       SDValue Mask = Op.getOperand(4);
16410       // We specify 2 possible modes for intrinsics, with/without rounding
16411       // modes.
16412       // First, we check if the intrinsic have rounding mode (6 operands),
16413       // if not, we set rounding mode to "current".
16414       SDValue Rnd;
16415       if (Op.getNumOperands() == 6)
16416         Rnd = Op.getOperand(5);
16417       else
16418         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16419       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16420                                               Src1, Src2, Rnd),
16421                                   Mask, PassThru, Subtarget, DAG);
16422     }
16423     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16424       SDValue Src1 = Op.getOperand(1);
16425       SDValue Src2 = Op.getOperand(2);
16426       SDValue Src3 = Op.getOperand(3);
16427       SDValue PassThru = Op.getOperand(4);
16428       SDValue Mask = Op.getOperand(5);
16429       SDValue Sae  = Op.getOperand(6);
16430
16431       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16432                                               Src2, Src3, Sae),
16433                                   Mask, PassThru, Subtarget, DAG);
16434     }
16435     case INTR_TYPE_3OP_MASK_RM: {
16436       SDValue Src1 = Op.getOperand(1);
16437       SDValue Src2 = Op.getOperand(2);
16438       SDValue Imm = Op.getOperand(3);
16439       SDValue PassThru = Op.getOperand(4);
16440       SDValue Mask = Op.getOperand(5);
16441       // We specify 2 possible modes for intrinsics, with/without rounding
16442       // modes.
16443       // First, we check if the intrinsic have rounding mode (7 operands),
16444       // if not, we set rounding mode to "current".
16445       SDValue Rnd;
16446       if (Op.getNumOperands() == 7)
16447         Rnd = Op.getOperand(6);
16448       else
16449         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16450       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16451         Src1, Src2, Imm, Rnd),
16452         Mask, PassThru, Subtarget, DAG);
16453     }
16454     case INTR_TYPE_3OP_IMM8_MASK:
16455     case INTR_TYPE_3OP_MASK:
16456     case INSERT_SUBVEC: {
16457       SDValue Src1 = Op.getOperand(1);
16458       SDValue Src2 = Op.getOperand(2);
16459       SDValue Src3 = Op.getOperand(3);
16460       SDValue PassThru = Op.getOperand(4);
16461       SDValue Mask = Op.getOperand(5);
16462
16463       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16464         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16465       else if (IntrData->Type == INSERT_SUBVEC) {
16466         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16467         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16468         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16469         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16470         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16471       }
16472
16473       // We specify 2 possible opcodes for intrinsics with rounding modes.
16474       // First, we check if the intrinsic may have non-default rounding mode,
16475       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16476       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16477       if (IntrWithRoundingModeOpcode != 0) {
16478         SDValue Rnd = Op.getOperand(6);
16479         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16480         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16481           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16482                                       dl, Op.getValueType(),
16483                                       Src1, Src2, Src3, Rnd),
16484                                       Mask, PassThru, Subtarget, DAG);
16485         }
16486       }
16487       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16488                                               Src1, Src2, Src3),
16489                                   Mask, PassThru, Subtarget, DAG);
16490     }
16491     case VPERM_3OP_MASKZ:
16492     case VPERM_3OP_MASK:{
16493       // Src2 is the PassThru
16494       SDValue Src1 = Op.getOperand(1);
16495       SDValue Src2 = Op.getOperand(2);
16496       SDValue Src3 = Op.getOperand(3);
16497       SDValue Mask = Op.getOperand(4);
16498       MVT VT = Op.getSimpleValueType();
16499       SDValue PassThru = SDValue();
16500
16501       // set PassThru element
16502       if (IntrData->Type == VPERM_3OP_MASKZ)
16503         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16504       else
16505         PassThru = DAG.getBitcast(VT, Src2);
16506
16507       // Swap Src1 and Src2 in the node creation
16508       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16509                                               dl, Op.getValueType(),
16510                                               Src2, Src1, Src3),
16511                                   Mask, PassThru, Subtarget, DAG);
16512     }
16513     case FMA_OP_MASK3:
16514     case FMA_OP_MASKZ:
16515     case FMA_OP_MASK: {
16516       SDValue Src1 = Op.getOperand(1);
16517       SDValue Src2 = Op.getOperand(2);
16518       SDValue Src3 = Op.getOperand(3);
16519       SDValue Mask = Op.getOperand(4);
16520       MVT VT = Op.getSimpleValueType();
16521       SDValue PassThru = SDValue();
16522
16523       // set PassThru element
16524       if (IntrData->Type == FMA_OP_MASKZ)
16525         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16526       else if (IntrData->Type == FMA_OP_MASK3)
16527         PassThru = Src3;
16528       else
16529         PassThru = Src1;
16530
16531       // We specify 2 possible opcodes for intrinsics with rounding modes.
16532       // First, we check if the intrinsic may have non-default rounding mode,
16533       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16534       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16535       if (IntrWithRoundingModeOpcode != 0) {
16536         SDValue Rnd = Op.getOperand(5);
16537         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16538             X86::STATIC_ROUNDING::CUR_DIRECTION)
16539           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16540                                                   dl, Op.getValueType(),
16541                                                   Src1, Src2, Src3, Rnd),
16542                                       Mask, PassThru, Subtarget, DAG);
16543       }
16544       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16545                                               dl, Op.getValueType(),
16546                                               Src1, Src2, Src3),
16547                                   Mask, PassThru, Subtarget, DAG);
16548     }
16549     case TERLOG_OP_MASK:
16550     case TERLOG_OP_MASKZ: {
16551       SDValue Src1 = Op.getOperand(1);
16552       SDValue Src2 = Op.getOperand(2);
16553       SDValue Src3 = Op.getOperand(3);
16554       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16555       SDValue Mask = Op.getOperand(5);
16556       MVT VT = Op.getSimpleValueType();
16557       SDValue PassThru = Src1;
16558       // Set PassThru element.
16559       if (IntrData->Type == TERLOG_OP_MASKZ)
16560         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16561
16562       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16563                                               Src1, Src2, Src3, Src4),
16564                                   Mask, PassThru, Subtarget, DAG);
16565     }
16566     case FPCLASS: {
16567       // FPclass intrinsics with mask
16568        SDValue Src1 = Op.getOperand(1);
16569        MVT VT = Src1.getSimpleValueType();
16570        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16571        SDValue Imm = Op.getOperand(2);
16572        SDValue Mask = Op.getOperand(3);
16573        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16574                                      Mask.getSimpleValueType().getSizeInBits());
16575        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16576        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16577                                                  DAG.getTargetConstant(0, dl, MaskVT),
16578                                                  Subtarget, DAG);
16579        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16580                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16581                                  DAG.getIntPtrConstant(0, dl));
16582        return DAG.getBitcast(Op.getValueType(), Res);
16583     }
16584     case FPCLASSS: {
16585       SDValue Src1 = Op.getOperand(1);
16586       SDValue Imm = Op.getOperand(2);
16587       SDValue Mask = Op.getOperand(3);
16588       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16589       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16590         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16591       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16592     }
16593     case CMP_MASK:
16594     case CMP_MASK_CC: {
16595       // Comparison intrinsics with masks.
16596       // Example of transformation:
16597       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16598       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16599       // (i8 (bitcast
16600       //   (v8i1 (insert_subvector undef,
16601       //           (v2i1 (and (PCMPEQM %a, %b),
16602       //                      (extract_subvector
16603       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16604       MVT VT = Op.getOperand(1).getSimpleValueType();
16605       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16606       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16607       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16608                                        Mask.getSimpleValueType().getSizeInBits());
16609       SDValue Cmp;
16610       if (IntrData->Type == CMP_MASK_CC) {
16611         SDValue CC = Op.getOperand(3);
16612         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16613         // We specify 2 possible opcodes for intrinsics with rounding modes.
16614         // First, we check if the intrinsic may have non-default rounding mode,
16615         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16616         if (IntrData->Opc1 != 0) {
16617           SDValue Rnd = Op.getOperand(5);
16618           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16619               X86::STATIC_ROUNDING::CUR_DIRECTION)
16620             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16621                               Op.getOperand(2), CC, Rnd);
16622         }
16623         //default rounding mode
16624         if(!Cmp.getNode())
16625             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16626                               Op.getOperand(2), CC);
16627
16628       } else {
16629         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16630         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16631                           Op.getOperand(2));
16632       }
16633       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16634                                              DAG.getTargetConstant(0, dl,
16635                                                                    MaskVT),
16636                                              Subtarget, DAG);
16637       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16638                                 DAG.getUNDEF(BitcastVT), CmpMask,
16639                                 DAG.getIntPtrConstant(0, dl));
16640       return DAG.getBitcast(Op.getValueType(), Res);
16641     }
16642     case CMP_MASK_SCALAR_CC: {
16643       SDValue Src1 = Op.getOperand(1);
16644       SDValue Src2 = Op.getOperand(2);
16645       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16646       SDValue Mask = Op.getOperand(4);
16647
16648       SDValue Cmp;
16649       if (IntrData->Opc1 != 0) {
16650         SDValue Rnd = Op.getOperand(5);
16651         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16652             X86::STATIC_ROUNDING::CUR_DIRECTION)
16653           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16654       }
16655       //default rounding mode
16656       if(!Cmp.getNode())
16657         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16658
16659       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16660                                              DAG.getTargetConstant(0, dl,
16661                                                                    MVT::i1),
16662                                              Subtarget, DAG);
16663
16664       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16665                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16666                          DAG.getValueType(MVT::i1));
16667     }
16668     case COMI: { // Comparison intrinsics
16669       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16670       SDValue LHS = Op.getOperand(1);
16671       SDValue RHS = Op.getOperand(2);
16672       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16673       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16674       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16675       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16676                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16677       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16678     }
16679     case COMI_RM: { // Comparison intrinsics with Sae
16680       SDValue LHS = Op.getOperand(1);
16681       SDValue RHS = Op.getOperand(2);
16682       SDValue CC = Op.getOperand(3);
16683       SDValue Sae = Op.getOperand(4);
16684       auto ComiType = TranslateX86ConstCondToX86CC(CC);
16685       // choose between ordered and unordered (comi/ucomi)
16686       unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16687       SDValue Cond;
16688       if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16689                                            X86::STATIC_ROUNDING::CUR_DIRECTION)
16690         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16691       else
16692         Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16693       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16694         DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16695       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16696     }
16697     case VSHIFT:
16698       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16699                                  Op.getOperand(1), Op.getOperand(2), DAG);
16700     case VSHIFT_MASK:
16701       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16702                                                       Op.getSimpleValueType(),
16703                                                       Op.getOperand(1),
16704                                                       Op.getOperand(2), DAG),
16705                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16706                                   DAG);
16707     case COMPRESS_EXPAND_IN_REG: {
16708       SDValue Mask = Op.getOperand(3);
16709       SDValue DataToCompress = Op.getOperand(1);
16710       SDValue PassThru = Op.getOperand(2);
16711       if (isAllOnesConstant(Mask)) // return data as is
16712         return Op.getOperand(1);
16713
16714       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16715                                               DataToCompress),
16716                                   Mask, PassThru, Subtarget, DAG);
16717     }
16718     case BROADCASTM: {
16719       SDValue Mask = Op.getOperand(1);
16720       MVT MaskVT = MVT::getVectorVT(MVT::i1, Mask.getSimpleValueType().getSizeInBits());
16721       Mask = DAG.getBitcast(MaskVT, Mask);
16722       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16723     }
16724     case BLEND: {
16725       SDValue Mask = Op.getOperand(3);
16726       MVT VT = Op.getSimpleValueType();
16727       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16728       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16729       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16730                          Op.getOperand(2));
16731     }
16732     case KUNPCK: {
16733       MVT VT = Op.getSimpleValueType();
16734       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16735
16736       SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16737       SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16738       // Arguments should be swapped.
16739       SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16740                                 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16741                                 Src2, Src1);
16742       return DAG.getBitcast(VT, Res);
16743     }
16744     default:
16745       break;
16746     }
16747   }
16748
16749   switch (IntNo) {
16750   default: return SDValue();    // Don't custom lower most intrinsics.
16751
16752   case Intrinsic::x86_avx2_permd:
16753   case Intrinsic::x86_avx2_permps:
16754     // Operands intentionally swapped. Mask is last operand to intrinsic,
16755     // but second operand for node/instruction.
16756     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16757                        Op.getOperand(2), Op.getOperand(1));
16758
16759   // ptest and testp intrinsics. The intrinsic these come from are designed to
16760   // return an integer value, not just an instruction so lower it to the ptest
16761   // or testp pattern and a setcc for the result.
16762   case Intrinsic::x86_sse41_ptestz:
16763   case Intrinsic::x86_sse41_ptestc:
16764   case Intrinsic::x86_sse41_ptestnzc:
16765   case Intrinsic::x86_avx_ptestz_256:
16766   case Intrinsic::x86_avx_ptestc_256:
16767   case Intrinsic::x86_avx_ptestnzc_256:
16768   case Intrinsic::x86_avx_vtestz_ps:
16769   case Intrinsic::x86_avx_vtestc_ps:
16770   case Intrinsic::x86_avx_vtestnzc_ps:
16771   case Intrinsic::x86_avx_vtestz_pd:
16772   case Intrinsic::x86_avx_vtestc_pd:
16773   case Intrinsic::x86_avx_vtestnzc_pd:
16774   case Intrinsic::x86_avx_vtestz_ps_256:
16775   case Intrinsic::x86_avx_vtestc_ps_256:
16776   case Intrinsic::x86_avx_vtestnzc_ps_256:
16777   case Intrinsic::x86_avx_vtestz_pd_256:
16778   case Intrinsic::x86_avx_vtestc_pd_256:
16779   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16780     bool IsTestPacked = false;
16781     unsigned X86CC;
16782     switch (IntNo) {
16783     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16784     case Intrinsic::x86_avx_vtestz_ps:
16785     case Intrinsic::x86_avx_vtestz_pd:
16786     case Intrinsic::x86_avx_vtestz_ps_256:
16787     case Intrinsic::x86_avx_vtestz_pd_256:
16788       IsTestPacked = true; // Fallthrough
16789     case Intrinsic::x86_sse41_ptestz:
16790     case Intrinsic::x86_avx_ptestz_256:
16791       // ZF = 1
16792       X86CC = X86::COND_E;
16793       break;
16794     case Intrinsic::x86_avx_vtestc_ps:
16795     case Intrinsic::x86_avx_vtestc_pd:
16796     case Intrinsic::x86_avx_vtestc_ps_256:
16797     case Intrinsic::x86_avx_vtestc_pd_256:
16798       IsTestPacked = true; // Fallthrough
16799     case Intrinsic::x86_sse41_ptestc:
16800     case Intrinsic::x86_avx_ptestc_256:
16801       // CF = 1
16802       X86CC = X86::COND_B;
16803       break;
16804     case Intrinsic::x86_avx_vtestnzc_ps:
16805     case Intrinsic::x86_avx_vtestnzc_pd:
16806     case Intrinsic::x86_avx_vtestnzc_ps_256:
16807     case Intrinsic::x86_avx_vtestnzc_pd_256:
16808       IsTestPacked = true; // Fallthrough
16809     case Intrinsic::x86_sse41_ptestnzc:
16810     case Intrinsic::x86_avx_ptestnzc_256:
16811       // ZF and CF = 0
16812       X86CC = X86::COND_A;
16813       break;
16814     }
16815
16816     SDValue LHS = Op.getOperand(1);
16817     SDValue RHS = Op.getOperand(2);
16818     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16819     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16820     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16821     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16822     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16823   }
16824   case Intrinsic::x86_avx512_kortestz_w:
16825   case Intrinsic::x86_avx512_kortestc_w: {
16826     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16827     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16828     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16829     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16830     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16831     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16832     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16833   }
16834
16835   case Intrinsic::x86_sse42_pcmpistria128:
16836   case Intrinsic::x86_sse42_pcmpestria128:
16837   case Intrinsic::x86_sse42_pcmpistric128:
16838   case Intrinsic::x86_sse42_pcmpestric128:
16839   case Intrinsic::x86_sse42_pcmpistrio128:
16840   case Intrinsic::x86_sse42_pcmpestrio128:
16841   case Intrinsic::x86_sse42_pcmpistris128:
16842   case Intrinsic::x86_sse42_pcmpestris128:
16843   case Intrinsic::x86_sse42_pcmpistriz128:
16844   case Intrinsic::x86_sse42_pcmpestriz128: {
16845     unsigned Opcode;
16846     unsigned X86CC;
16847     switch (IntNo) {
16848     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16849     case Intrinsic::x86_sse42_pcmpistria128:
16850       Opcode = X86ISD::PCMPISTRI;
16851       X86CC = X86::COND_A;
16852       break;
16853     case Intrinsic::x86_sse42_pcmpestria128:
16854       Opcode = X86ISD::PCMPESTRI;
16855       X86CC = X86::COND_A;
16856       break;
16857     case Intrinsic::x86_sse42_pcmpistric128:
16858       Opcode = X86ISD::PCMPISTRI;
16859       X86CC = X86::COND_B;
16860       break;
16861     case Intrinsic::x86_sse42_pcmpestric128:
16862       Opcode = X86ISD::PCMPESTRI;
16863       X86CC = X86::COND_B;
16864       break;
16865     case Intrinsic::x86_sse42_pcmpistrio128:
16866       Opcode = X86ISD::PCMPISTRI;
16867       X86CC = X86::COND_O;
16868       break;
16869     case Intrinsic::x86_sse42_pcmpestrio128:
16870       Opcode = X86ISD::PCMPESTRI;
16871       X86CC = X86::COND_O;
16872       break;
16873     case Intrinsic::x86_sse42_pcmpistris128:
16874       Opcode = X86ISD::PCMPISTRI;
16875       X86CC = X86::COND_S;
16876       break;
16877     case Intrinsic::x86_sse42_pcmpestris128:
16878       Opcode = X86ISD::PCMPESTRI;
16879       X86CC = X86::COND_S;
16880       break;
16881     case Intrinsic::x86_sse42_pcmpistriz128:
16882       Opcode = X86ISD::PCMPISTRI;
16883       X86CC = X86::COND_E;
16884       break;
16885     case Intrinsic::x86_sse42_pcmpestriz128:
16886       Opcode = X86ISD::PCMPESTRI;
16887       X86CC = X86::COND_E;
16888       break;
16889     }
16890     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16891     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16892     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16893     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16894                                 DAG.getConstant(X86CC, dl, MVT::i8),
16895                                 SDValue(PCMP.getNode(), 1));
16896     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16897   }
16898
16899   case Intrinsic::x86_sse42_pcmpistri128:
16900   case Intrinsic::x86_sse42_pcmpestri128: {
16901     unsigned Opcode;
16902     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16903       Opcode = X86ISD::PCMPISTRI;
16904     else
16905       Opcode = X86ISD::PCMPESTRI;
16906
16907     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16908     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16909     return DAG.getNode(Opcode, dl, VTs, NewOps);
16910   }
16911
16912   case Intrinsic::x86_seh_lsda: {
16913     // Compute the symbol for the LSDA. We know it'll get emitted later.
16914     MachineFunction &MF = DAG.getMachineFunction();
16915     SDValue Op1 = Op.getOperand(1);
16916     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16917     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16918         GlobalValue::getRealLinkageName(Fn->getName()));
16919
16920     // Generate a simple absolute symbol reference. This intrinsic is only
16921     // supported on 32-bit Windows, which isn't PIC.
16922     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16923     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16924   }
16925
16926   case Intrinsic::x86_seh_recoverfp: {
16927     SDValue FnOp = Op.getOperand(1);
16928     SDValue IncomingFPOp = Op.getOperand(2);
16929     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16930     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16931     if (!Fn)
16932       report_fatal_error(
16933           "llvm.x86.seh.recoverfp must take a function as the first argument");
16934     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16935   }
16936
16937   case Intrinsic::localaddress: {
16938     // Returns one of the stack, base, or frame pointer registers, depending on
16939     // which is used to reference local variables.
16940     MachineFunction &MF = DAG.getMachineFunction();
16941     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16942     unsigned Reg;
16943     if (RegInfo->hasBasePointer(MF))
16944       Reg = RegInfo->getBaseRegister();
16945     else // This function handles the SP or FP case.
16946       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16947     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16948   }
16949   }
16950 }
16951
16952 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16953                               SDValue Src, SDValue Mask, SDValue Base,
16954                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16955                               const X86Subtarget * Subtarget) {
16956   SDLoc dl(Op);
16957   auto *C = cast<ConstantSDNode>(ScaleOp);
16958   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16959   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16960                              Index.getSimpleValueType().getVectorNumElements());
16961   SDValue MaskInReg;
16962   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16963   if (MaskC)
16964     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16965   else {
16966     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16967                                      Mask.getSimpleValueType().getSizeInBits());
16968
16969     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16970     // are extracted by EXTRACT_SUBVECTOR.
16971     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16972                             DAG.getBitcast(BitcastVT, Mask),
16973                             DAG.getIntPtrConstant(0, dl));
16974   }
16975   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16976   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16977   SDValue Segment = DAG.getRegister(0, MVT::i32);
16978   if (Src.getOpcode() == ISD::UNDEF)
16979     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
16980   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16981   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16982   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16983   return DAG.getMergeValues(RetOps, dl);
16984 }
16985
16986 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16987                                SDValue Src, SDValue Mask, SDValue Base,
16988                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16989   SDLoc dl(Op);
16990   auto *C = cast<ConstantSDNode>(ScaleOp);
16991   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16992   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16993   SDValue Segment = DAG.getRegister(0, MVT::i32);
16994   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16995                              Index.getSimpleValueType().getVectorNumElements());
16996   SDValue MaskInReg;
16997   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16998   if (MaskC)
16999     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17000   else {
17001     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17002                                      Mask.getSimpleValueType().getSizeInBits());
17003
17004     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17005     // are extracted by EXTRACT_SUBVECTOR.
17006     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17007                             DAG.getBitcast(BitcastVT, Mask),
17008                             DAG.getIntPtrConstant(0, dl));
17009   }
17010   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17011   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17012   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17013   return SDValue(Res, 1);
17014 }
17015
17016 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17017                                SDValue Mask, SDValue Base, SDValue Index,
17018                                SDValue ScaleOp, SDValue Chain) {
17019   SDLoc dl(Op);
17020   auto *C = cast<ConstantSDNode>(ScaleOp);
17021   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17022   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17023   SDValue Segment = DAG.getRegister(0, MVT::i32);
17024   MVT MaskVT =
17025     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17026   SDValue MaskInReg;
17027   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17028   if (MaskC)
17029     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17030   else
17031     MaskInReg = DAG.getBitcast(MaskVT, Mask);
17032   //SDVTList VTs = DAG.getVTList(MVT::Other);
17033   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17034   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17035   return SDValue(Res, 0);
17036 }
17037
17038 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17039 // read performance monitor counters (x86_rdpmc).
17040 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17041                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17042                               SmallVectorImpl<SDValue> &Results) {
17043   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17044   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17045   SDValue LO, HI;
17046
17047   // The ECX register is used to select the index of the performance counter
17048   // to read.
17049   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17050                                    N->getOperand(2));
17051   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17052
17053   // Reads the content of a 64-bit performance counter and returns it in the
17054   // registers EDX:EAX.
17055   if (Subtarget->is64Bit()) {
17056     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17057     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17058                             LO.getValue(2));
17059   } else {
17060     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17061     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17062                             LO.getValue(2));
17063   }
17064   Chain = HI.getValue(1);
17065
17066   if (Subtarget->is64Bit()) {
17067     // The EAX register is loaded with the low-order 32 bits. The EDX register
17068     // is loaded with the supported high-order bits of the counter.
17069     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17070                               DAG.getConstant(32, DL, MVT::i8));
17071     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17072     Results.push_back(Chain);
17073     return;
17074   }
17075
17076   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17077   SDValue Ops[] = { LO, HI };
17078   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17079   Results.push_back(Pair);
17080   Results.push_back(Chain);
17081 }
17082
17083 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17084 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17085 // also used to custom lower READCYCLECOUNTER nodes.
17086 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17087                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
17088                               SmallVectorImpl<SDValue> &Results) {
17089   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17090   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17091   SDValue LO, HI;
17092
17093   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17094   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17095   // and the EAX register is loaded with the low-order 32 bits.
17096   if (Subtarget->is64Bit()) {
17097     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17098     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17099                             LO.getValue(2));
17100   } else {
17101     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17102     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17103                             LO.getValue(2));
17104   }
17105   SDValue Chain = HI.getValue(1);
17106
17107   if (Opcode == X86ISD::RDTSCP_DAG) {
17108     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17109
17110     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17111     // the ECX register. Add 'ecx' explicitly to the chain.
17112     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17113                                      HI.getValue(2));
17114     // Explicitly store the content of ECX at the location passed in input
17115     // to the 'rdtscp' intrinsic.
17116     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17117                          MachinePointerInfo(), false, false, 0);
17118   }
17119
17120   if (Subtarget->is64Bit()) {
17121     // The EDX register is loaded with the high-order 32 bits of the MSR, and
17122     // the EAX register is loaded with the low-order 32 bits.
17123     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17124                               DAG.getConstant(32, DL, MVT::i8));
17125     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17126     Results.push_back(Chain);
17127     return;
17128   }
17129
17130   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17131   SDValue Ops[] = { LO, HI };
17132   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17133   Results.push_back(Pair);
17134   Results.push_back(Chain);
17135 }
17136
17137 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17138                                      SelectionDAG &DAG) {
17139   SmallVector<SDValue, 2> Results;
17140   SDLoc DL(Op);
17141   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17142                           Results);
17143   return DAG.getMergeValues(Results, DL);
17144 }
17145
17146 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17147   MachineFunction &MF = DAG.getMachineFunction();
17148   SDValue Chain = Op.getOperand(0);
17149   SDValue RegNode = Op.getOperand(2);
17150   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17151   if (!EHInfo)
17152     report_fatal_error("EH registrations only live in functions using WinEH");
17153
17154   // Cast the operand to an alloca, and remember the frame index.
17155   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17156   if (!FINode)
17157     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17158   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17159
17160   // Return the chain operand without making any DAG nodes.
17161   return Chain;
17162 }
17163
17164 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17165 /// return truncate Store/MaskedStore Node
17166 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17167                                                SelectionDAG &DAG,
17168                                                MVT ElementType) {
17169   SDLoc dl(Op);
17170   SDValue Mask = Op.getOperand(4);
17171   SDValue DataToTruncate = Op.getOperand(3);
17172   SDValue Addr = Op.getOperand(2);
17173   SDValue Chain = Op.getOperand(0);
17174
17175   MVT VT  = DataToTruncate.getSimpleValueType();
17176   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17177
17178   if (isAllOnesConstant(Mask)) // return just a truncate store
17179     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17180                              MachinePointerInfo(), SVT, false, false,
17181                              SVT.getScalarSizeInBits()/8);
17182
17183   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17184   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17185                                    Mask.getSimpleValueType().getSizeInBits());
17186   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17187   // are extracted by EXTRACT_SUBVECTOR.
17188   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17189                               DAG.getBitcast(BitcastVT, Mask),
17190                               DAG.getIntPtrConstant(0, dl));
17191
17192   MachineMemOperand *MMO = DAG.getMachineFunction().
17193     getMachineMemOperand(MachinePointerInfo(),
17194                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17195                          SVT.getScalarSizeInBits()/8);
17196
17197   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17198                             VMask, SVT, MMO, true);
17199 }
17200
17201 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17202                                       SelectionDAG &DAG) {
17203   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17204
17205   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17206   if (!IntrData) {
17207     if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17208       return MarkEHRegistrationNode(Op, DAG);
17209     return SDValue();
17210   }
17211
17212   SDLoc dl(Op);
17213   switch(IntrData->Type) {
17214   default: llvm_unreachable("Unknown Intrinsic Type");
17215   case RDSEED:
17216   case RDRAND: {
17217     // Emit the node with the right value type.
17218     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17219     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17220
17221     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17222     // Otherwise return the value from Rand, which is always 0, casted to i32.
17223     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17224                       DAG.getConstant(1, dl, Op->getValueType(1)),
17225                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17226                       SDValue(Result.getNode(), 1) };
17227     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17228                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17229                                   Ops);
17230
17231     // Return { result, isValid, chain }.
17232     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17233                        SDValue(Result.getNode(), 2));
17234   }
17235   case GATHER: {
17236   //gather(v1, mask, index, base, scale);
17237     SDValue Chain = Op.getOperand(0);
17238     SDValue Src   = Op.getOperand(2);
17239     SDValue Base  = Op.getOperand(3);
17240     SDValue Index = Op.getOperand(4);
17241     SDValue Mask  = Op.getOperand(5);
17242     SDValue Scale = Op.getOperand(6);
17243     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17244                          Chain, Subtarget);
17245   }
17246   case SCATTER: {
17247   //scatter(base, mask, index, v1, scale);
17248     SDValue Chain = Op.getOperand(0);
17249     SDValue Base  = Op.getOperand(2);
17250     SDValue Mask  = Op.getOperand(3);
17251     SDValue Index = Op.getOperand(4);
17252     SDValue Src   = Op.getOperand(5);
17253     SDValue Scale = Op.getOperand(6);
17254     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17255                           Scale, Chain);
17256   }
17257   case PREFETCH: {
17258     SDValue Hint = Op.getOperand(6);
17259     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17260     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17261     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17262     SDValue Chain = Op.getOperand(0);
17263     SDValue Mask  = Op.getOperand(2);
17264     SDValue Index = Op.getOperand(3);
17265     SDValue Base  = Op.getOperand(4);
17266     SDValue Scale = Op.getOperand(5);
17267     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17268   }
17269   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17270   case RDTSC: {
17271     SmallVector<SDValue, 2> Results;
17272     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17273                             Results);
17274     return DAG.getMergeValues(Results, dl);
17275   }
17276   // Read Performance Monitoring Counters.
17277   case RDPMC: {
17278     SmallVector<SDValue, 2> Results;
17279     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17280     return DAG.getMergeValues(Results, dl);
17281   }
17282   // XTEST intrinsics.
17283   case XTEST: {
17284     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17285     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17286     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17287                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17288                                 InTrans);
17289     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17290     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17291                        Ret, SDValue(InTrans.getNode(), 1));
17292   }
17293   // ADC/ADCX/SBB
17294   case ADX: {
17295     SmallVector<SDValue, 2> Results;
17296     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17297     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17298     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17299                                 DAG.getConstant(-1, dl, MVT::i8));
17300     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17301                               Op.getOperand(4), GenCF.getValue(1));
17302     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17303                                  Op.getOperand(5), MachinePointerInfo(),
17304                                  false, false, 0);
17305     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17306                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17307                                 Res.getValue(1));
17308     Results.push_back(SetCC);
17309     Results.push_back(Store);
17310     return DAG.getMergeValues(Results, dl);
17311   }
17312   case COMPRESS_TO_MEM: {
17313     SDLoc dl(Op);
17314     SDValue Mask = Op.getOperand(4);
17315     SDValue DataToCompress = Op.getOperand(3);
17316     SDValue Addr = Op.getOperand(2);
17317     SDValue Chain = Op.getOperand(0);
17318
17319     MVT VT = DataToCompress.getSimpleValueType();
17320     if (isAllOnesConstant(Mask)) // return just a store
17321       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17322                           MachinePointerInfo(), false, false,
17323                           VT.getScalarSizeInBits()/8);
17324
17325     SDValue Compressed =
17326       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17327                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17328     return DAG.getStore(Chain, dl, Compressed, Addr,
17329                         MachinePointerInfo(), false, false,
17330                         VT.getScalarSizeInBits()/8);
17331   }
17332   case TRUNCATE_TO_MEM_VI8:
17333     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17334   case TRUNCATE_TO_MEM_VI16:
17335     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17336   case TRUNCATE_TO_MEM_VI32:
17337     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17338   case EXPAND_FROM_MEM: {
17339     SDLoc dl(Op);
17340     SDValue Mask = Op.getOperand(4);
17341     SDValue PassThru = Op.getOperand(3);
17342     SDValue Addr = Op.getOperand(2);
17343     SDValue Chain = Op.getOperand(0);
17344     MVT VT = Op.getSimpleValueType();
17345
17346     if (isAllOnesConstant(Mask)) // return just a load
17347       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17348                          false, VT.getScalarSizeInBits()/8);
17349
17350     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17351                                        false, false, false,
17352                                        VT.getScalarSizeInBits()/8);
17353
17354     SDValue Results[] = {
17355       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17356                            Mask, PassThru, Subtarget, DAG), Chain};
17357     return DAG.getMergeValues(Results, dl);
17358   }
17359   }
17360 }
17361
17362 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17363                                            SelectionDAG &DAG) const {
17364   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17365   MFI->setReturnAddressIsTaken(true);
17366
17367   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17368     return SDValue();
17369
17370   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17371   SDLoc dl(Op);
17372   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17373
17374   if (Depth > 0) {
17375     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17376     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17377     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17378     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17379                        DAG.getNode(ISD::ADD, dl, PtrVT,
17380                                    FrameAddr, Offset),
17381                        MachinePointerInfo(), false, false, false, 0);
17382   }
17383
17384   // Just load the return address.
17385   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17386   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17387                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17388 }
17389
17390 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17391   MachineFunction &MF = DAG.getMachineFunction();
17392   MachineFrameInfo *MFI = MF.getFrameInfo();
17393   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17394   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17395   EVT VT = Op.getValueType();
17396
17397   MFI->setFrameAddressIsTaken(true);
17398
17399   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17400     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17401     // is not possible to crawl up the stack without looking at the unwind codes
17402     // simultaneously.
17403     int FrameAddrIndex = FuncInfo->getFAIndex();
17404     if (!FrameAddrIndex) {
17405       // Set up a frame object for the return address.
17406       unsigned SlotSize = RegInfo->getSlotSize();
17407       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17408           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17409       FuncInfo->setFAIndex(FrameAddrIndex);
17410     }
17411     return DAG.getFrameIndex(FrameAddrIndex, VT);
17412   }
17413
17414   unsigned FrameReg =
17415       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17416   SDLoc dl(Op);  // FIXME probably not meaningful
17417   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17418   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17419           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17420          "Invalid Frame Register!");
17421   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17422   while (Depth--)
17423     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17424                             MachinePointerInfo(),
17425                             false, false, false, 0);
17426   return FrameAddr;
17427 }
17428
17429 // FIXME? Maybe this could be a TableGen attribute on some registers and
17430 // this table could be generated automatically from RegInfo.
17431 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17432                                               SelectionDAG &DAG) const {
17433   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17434   const MachineFunction &MF = DAG.getMachineFunction();
17435
17436   unsigned Reg = StringSwitch<unsigned>(RegName)
17437                        .Case("esp", X86::ESP)
17438                        .Case("rsp", X86::RSP)
17439                        .Case("ebp", X86::EBP)
17440                        .Case("rbp", X86::RBP)
17441                        .Default(0);
17442
17443   if (Reg == X86::EBP || Reg == X86::RBP) {
17444     if (!TFI.hasFP(MF))
17445       report_fatal_error("register " + StringRef(RegName) +
17446                          " is allocatable: function has no frame pointer");
17447 #ifndef NDEBUG
17448     else {
17449       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17450       unsigned FrameReg =
17451           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17452       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17453              "Invalid Frame Register!");
17454     }
17455 #endif
17456   }
17457
17458   if (Reg)
17459     return Reg;
17460
17461   report_fatal_error("Invalid register name global variable");
17462 }
17463
17464 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17465                                                      SelectionDAG &DAG) const {
17466   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17467   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17468 }
17469
17470 unsigned X86TargetLowering::getExceptionPointerRegister(
17471     const Constant *PersonalityFn) const {
17472   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17473     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17474
17475   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17476 }
17477
17478 unsigned X86TargetLowering::getExceptionSelectorRegister(
17479     const Constant *PersonalityFn) const {
17480   // Funclet personalities don't use selectors (the runtime does the selection).
17481   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17482   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17483 }
17484
17485 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17486   SDValue Chain     = Op.getOperand(0);
17487   SDValue Offset    = Op.getOperand(1);
17488   SDValue Handler   = Op.getOperand(2);
17489   SDLoc dl      (Op);
17490
17491   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17492   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17493   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17494   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17495           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17496          "Invalid Frame Register!");
17497   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17498   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17499
17500   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17501                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17502                                                        dl));
17503   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17504   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17505                        false, false, 0);
17506   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17507
17508   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17509                      DAG.getRegister(StoreAddrReg, PtrVT));
17510 }
17511
17512 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17513                                                SelectionDAG &DAG) const {
17514   SDLoc DL(Op);
17515   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17516                      DAG.getVTList(MVT::i32, MVT::Other),
17517                      Op.getOperand(0), Op.getOperand(1));
17518 }
17519
17520 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17521                                                 SelectionDAG &DAG) const {
17522   SDLoc DL(Op);
17523   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17524                      Op.getOperand(0), Op.getOperand(1));
17525 }
17526
17527 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17528   return Op.getOperand(0);
17529 }
17530
17531 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17532                                                 SelectionDAG &DAG) const {
17533   SDValue Root = Op.getOperand(0);
17534   SDValue Trmp = Op.getOperand(1); // trampoline
17535   SDValue FPtr = Op.getOperand(2); // nested function
17536   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17537   SDLoc dl (Op);
17538
17539   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17540   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17541
17542   if (Subtarget->is64Bit()) {
17543     SDValue OutChains[6];
17544
17545     // Large code-model.
17546     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17547     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17548
17549     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17550     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17551
17552     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17553
17554     // Load the pointer to the nested function into R11.
17555     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17556     SDValue Addr = Trmp;
17557     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17558                                 Addr, MachinePointerInfo(TrmpAddr),
17559                                 false, false, 0);
17560
17561     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17562                        DAG.getConstant(2, dl, MVT::i64));
17563     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17564                                 MachinePointerInfo(TrmpAddr, 2),
17565                                 false, false, 2);
17566
17567     // Load the 'nest' parameter value into R10.
17568     // R10 is specified in X86CallingConv.td
17569     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17570     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17571                        DAG.getConstant(10, dl, MVT::i64));
17572     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17573                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17574                                 false, false, 0);
17575
17576     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17577                        DAG.getConstant(12, dl, MVT::i64));
17578     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17579                                 MachinePointerInfo(TrmpAddr, 12),
17580                                 false, false, 2);
17581
17582     // Jump to the nested function.
17583     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17584     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17585                        DAG.getConstant(20, dl, MVT::i64));
17586     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17587                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17588                                 false, false, 0);
17589
17590     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17591     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17592                        DAG.getConstant(22, dl, MVT::i64));
17593     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17594                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17595                                 false, false, 0);
17596
17597     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17598   } else {
17599     const Function *Func =
17600       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17601     CallingConv::ID CC = Func->getCallingConv();
17602     unsigned NestReg;
17603
17604     switch (CC) {
17605     default:
17606       llvm_unreachable("Unsupported calling convention");
17607     case CallingConv::C:
17608     case CallingConv::X86_StdCall: {
17609       // Pass 'nest' parameter in ECX.
17610       // Must be kept in sync with X86CallingConv.td
17611       NestReg = X86::ECX;
17612
17613       // Check that ECX wasn't needed by an 'inreg' parameter.
17614       FunctionType *FTy = Func->getFunctionType();
17615       const AttributeSet &Attrs = Func->getAttributes();
17616
17617       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17618         unsigned InRegCount = 0;
17619         unsigned Idx = 1;
17620
17621         for (FunctionType::param_iterator I = FTy->param_begin(),
17622              E = FTy->param_end(); I != E; ++I, ++Idx)
17623           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17624             auto &DL = DAG.getDataLayout();
17625             // FIXME: should only count parameters that are lowered to integers.
17626             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17627           }
17628
17629         if (InRegCount > 2) {
17630           report_fatal_error("Nest register in use - reduce number of inreg"
17631                              " parameters!");
17632         }
17633       }
17634       break;
17635     }
17636     case CallingConv::X86_FastCall:
17637     case CallingConv::X86_ThisCall:
17638     case CallingConv::Fast:
17639       // Pass 'nest' parameter in EAX.
17640       // Must be kept in sync with X86CallingConv.td
17641       NestReg = X86::EAX;
17642       break;
17643     }
17644
17645     SDValue OutChains[4];
17646     SDValue Addr, Disp;
17647
17648     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17649                        DAG.getConstant(10, dl, MVT::i32));
17650     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17651
17652     // This is storing the opcode for MOV32ri.
17653     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17654     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17655     OutChains[0] = DAG.getStore(Root, dl,
17656                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17657                                 Trmp, MachinePointerInfo(TrmpAddr),
17658                                 false, false, 0);
17659
17660     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17661                        DAG.getConstant(1, dl, MVT::i32));
17662     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17663                                 MachinePointerInfo(TrmpAddr, 1),
17664                                 false, false, 1);
17665
17666     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17667     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17668                        DAG.getConstant(5, dl, MVT::i32));
17669     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17670                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17671                                 false, false, 1);
17672
17673     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17674                        DAG.getConstant(6, dl, MVT::i32));
17675     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17676                                 MachinePointerInfo(TrmpAddr, 6),
17677                                 false, false, 1);
17678
17679     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17680   }
17681 }
17682
17683 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17684                                             SelectionDAG &DAG) const {
17685   /*
17686    The rounding mode is in bits 11:10 of FPSR, and has the following
17687    settings:
17688      00 Round to nearest
17689      01 Round to -inf
17690      10 Round to +inf
17691      11 Round to 0
17692
17693   FLT_ROUNDS, on the other hand, expects the following:
17694     -1 Undefined
17695      0 Round to 0
17696      1 Round to nearest
17697      2 Round to +inf
17698      3 Round to -inf
17699
17700   To perform the conversion, we do:
17701     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17702   */
17703
17704   MachineFunction &MF = DAG.getMachineFunction();
17705   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17706   unsigned StackAlignment = TFI.getStackAlignment();
17707   MVT VT = Op.getSimpleValueType();
17708   SDLoc DL(Op);
17709
17710   // Save FP Control Word to stack slot
17711   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17712   SDValue StackSlot =
17713       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17714
17715   MachineMemOperand *MMO =
17716       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17717                               MachineMemOperand::MOStore, 2, 2);
17718
17719   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17720   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17721                                           DAG.getVTList(MVT::Other),
17722                                           Ops, MVT::i16, MMO);
17723
17724   // Load FP Control Word from stack slot
17725   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17726                             MachinePointerInfo(), false, false, false, 0);
17727
17728   // Transform as necessary
17729   SDValue CWD1 =
17730     DAG.getNode(ISD::SRL, DL, MVT::i16,
17731                 DAG.getNode(ISD::AND, DL, MVT::i16,
17732                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17733                 DAG.getConstant(11, DL, MVT::i8));
17734   SDValue CWD2 =
17735     DAG.getNode(ISD::SRL, DL, MVT::i16,
17736                 DAG.getNode(ISD::AND, DL, MVT::i16,
17737                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17738                 DAG.getConstant(9, DL, MVT::i8));
17739
17740   SDValue RetVal =
17741     DAG.getNode(ISD::AND, DL, MVT::i16,
17742                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17743                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17744                             DAG.getConstant(1, DL, MVT::i16)),
17745                 DAG.getConstant(3, DL, MVT::i16));
17746
17747   return DAG.getNode((VT.getSizeInBits() < 16 ?
17748                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17749 }
17750
17751 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17752 //
17753 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17754 //    to 512-bit vector.
17755 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17756 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17757 //    split the vector, perform operation on it's Lo a Hi part and
17758 //    concatenate the results.
17759 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17760   SDLoc dl(Op);
17761   MVT VT = Op.getSimpleValueType();
17762   MVT EltVT = VT.getVectorElementType();
17763   unsigned NumElems = VT.getVectorNumElements();
17764
17765   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17766     // Extend to 512 bit vector.
17767     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17768               "Unsupported value type for operation");
17769
17770     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17771     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17772                                  DAG.getUNDEF(NewVT),
17773                                  Op.getOperand(0),
17774                                  DAG.getIntPtrConstant(0, dl));
17775     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17776
17777     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17778                        DAG.getIntPtrConstant(0, dl));
17779   }
17780
17781   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17782           "Unsupported element type");
17783
17784   if (16 < NumElems) {
17785     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17786     SDValue Lo, Hi;
17787     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17788     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17789
17790     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17791     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17792
17793     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17794   }
17795
17796   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17797
17798   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17799           "Unsupported value type for operation");
17800
17801   // Use native supported vector instruction vplzcntd.
17802   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17803   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17804   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17805   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17806
17807   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17808 }
17809
17810 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17811                          SelectionDAG &DAG) {
17812   MVT VT = Op.getSimpleValueType();
17813   MVT OpVT = VT;
17814   unsigned NumBits = VT.getSizeInBits();
17815   SDLoc dl(Op);
17816
17817   if (VT.isVector() && Subtarget->hasAVX512())
17818     return LowerVectorCTLZ_AVX512(Op, DAG);
17819
17820   Op = Op.getOperand(0);
17821   if (VT == MVT::i8) {
17822     // Zero extend to i32 since there is not an i8 bsr.
17823     OpVT = MVT::i32;
17824     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17825   }
17826
17827   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17828   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17829   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17830
17831   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17832   SDValue Ops[] = {
17833     Op,
17834     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17835     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17836     Op.getValue(1)
17837   };
17838   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17839
17840   // Finally xor with NumBits-1.
17841   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17842                    DAG.getConstant(NumBits - 1, dl, OpVT));
17843
17844   if (VT == MVT::i8)
17845     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17846   return Op;
17847 }
17848
17849 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17850                                     SelectionDAG &DAG) {
17851   MVT VT = Op.getSimpleValueType();
17852   EVT OpVT = VT;
17853   unsigned NumBits = VT.getSizeInBits();
17854   SDLoc dl(Op);
17855
17856   if (VT.isVector() && Subtarget->hasAVX512())
17857     return LowerVectorCTLZ_AVX512(Op, DAG);
17858
17859   Op = Op.getOperand(0);
17860   if (VT == MVT::i8) {
17861     // Zero extend to i32 since there is not an i8 bsr.
17862     OpVT = MVT::i32;
17863     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17864   }
17865
17866   // Issue a bsr (scan bits in reverse).
17867   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17868   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17869
17870   // And xor with NumBits-1.
17871   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17872                    DAG.getConstant(NumBits - 1, dl, OpVT));
17873
17874   if (VT == MVT::i8)
17875     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17876   return Op;
17877 }
17878
17879 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17880   MVT VT = Op.getSimpleValueType();
17881   unsigned NumBits = VT.getScalarSizeInBits();
17882   SDLoc dl(Op);
17883
17884   if (VT.isVector()) {
17885     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17886
17887     SDValue N0 = Op.getOperand(0);
17888     SDValue Zero = DAG.getConstant(0, dl, VT);
17889
17890     // lsb(x) = (x & -x)
17891     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17892                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17893
17894     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17895     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17896         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17897       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17898       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17899                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17900     }
17901
17902     // cttz(x) = ctpop(lsb - 1)
17903     SDValue One = DAG.getConstant(1, dl, VT);
17904     return DAG.getNode(ISD::CTPOP, dl, VT,
17905                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17906   }
17907
17908   assert(Op.getOpcode() == ISD::CTTZ &&
17909          "Only scalar CTTZ requires custom lowering");
17910
17911   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17912   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17913   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17914
17915   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17916   SDValue Ops[] = {
17917     Op,
17918     DAG.getConstant(NumBits, dl, VT),
17919     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17920     Op.getValue(1)
17921   };
17922   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17923 }
17924
17925 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17926 // ones, and then concatenate the result back.
17927 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17928   MVT VT = Op.getSimpleValueType();
17929
17930   assert(VT.is256BitVector() && VT.isInteger() &&
17931          "Unsupported value type for operation");
17932
17933   unsigned NumElems = VT.getVectorNumElements();
17934   SDLoc dl(Op);
17935
17936   // Extract the LHS vectors
17937   SDValue LHS = Op.getOperand(0);
17938   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17939   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17940
17941   // Extract the RHS vectors
17942   SDValue RHS = Op.getOperand(1);
17943   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17944   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17945
17946   MVT EltVT = VT.getVectorElementType();
17947   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17948
17949   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17950                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17951                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17952 }
17953
17954 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17955   if (Op.getValueType() == MVT::i1)
17956     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17957                        Op.getOperand(0), Op.getOperand(1));
17958   assert(Op.getSimpleValueType().is256BitVector() &&
17959          Op.getSimpleValueType().isInteger() &&
17960          "Only handle AVX 256-bit vector integer operation");
17961   return Lower256IntArith(Op, DAG);
17962 }
17963
17964 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17965   if (Op.getValueType() == MVT::i1)
17966     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17967                        Op.getOperand(0), Op.getOperand(1));
17968   assert(Op.getSimpleValueType().is256BitVector() &&
17969          Op.getSimpleValueType().isInteger() &&
17970          "Only handle AVX 256-bit vector integer operation");
17971   return Lower256IntArith(Op, DAG);
17972 }
17973
17974 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17975   assert(Op.getSimpleValueType().is256BitVector() &&
17976          Op.getSimpleValueType().isInteger() &&
17977          "Only handle AVX 256-bit vector integer operation");
17978   return Lower256IntArith(Op, DAG);
17979 }
17980
17981 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17982                         SelectionDAG &DAG) {
17983   SDLoc dl(Op);
17984   MVT VT = Op.getSimpleValueType();
17985
17986   if (VT == MVT::i1)
17987     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17988
17989   // Decompose 256-bit ops into smaller 128-bit ops.
17990   if (VT.is256BitVector() && !Subtarget->hasInt256())
17991     return Lower256IntArith(Op, DAG);
17992
17993   SDValue A = Op.getOperand(0);
17994   SDValue B = Op.getOperand(1);
17995
17996   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17997   // pairs, multiply and truncate.
17998   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17999     if (Subtarget->hasInt256()) {
18000       if (VT == MVT::v32i8) {
18001         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18002         SDValue Lo = DAG.getIntPtrConstant(0, dl);
18003         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18004         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18005         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18006         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18007         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18008         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18009                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18010                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18011       }
18012
18013       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18014       return DAG.getNode(
18015           ISD::TRUNCATE, dl, VT,
18016           DAG.getNode(ISD::MUL, dl, ExVT,
18017                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18018                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18019     }
18020
18021     assert(VT == MVT::v16i8 &&
18022            "Pre-AVX2 support only supports v16i8 multiplication");
18023     MVT ExVT = MVT::v8i16;
18024
18025     // Extract the lo parts and sign extend to i16
18026     SDValue ALo, BLo;
18027     if (Subtarget->hasSSE41()) {
18028       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18029       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18030     } else {
18031       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18032                               -1, 4, -1, 5, -1, 6, -1, 7};
18033       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18034       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18035       ALo = DAG.getBitcast(ExVT, ALo);
18036       BLo = DAG.getBitcast(ExVT, BLo);
18037       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18038       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18039     }
18040
18041     // Extract the hi parts and sign extend to i16
18042     SDValue AHi, BHi;
18043     if (Subtarget->hasSSE41()) {
18044       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
18045                               -1, -1, -1, -1, -1, -1, -1, -1};
18046       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18047       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18048       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18049       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18050     } else {
18051       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
18052                               -1, 12, -1, 13, -1, 14, -1, 15};
18053       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18054       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18055       AHi = DAG.getBitcast(ExVT, AHi);
18056       BHi = DAG.getBitcast(ExVT, BHi);
18057       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18058       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18059     }
18060
18061     // Multiply, mask the lower 8bits of the lo/hi results and pack
18062     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18063     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18064     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18065     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18066     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18067   }
18068
18069   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18070   if (VT == MVT::v4i32) {
18071     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18072            "Should not custom lower when pmuldq is available!");
18073
18074     // Extract the odd parts.
18075     static const int UnpackMask[] = { 1, -1, 3, -1 };
18076     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18077     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18078
18079     // Multiply the even parts.
18080     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18081     // Now multiply odd parts.
18082     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18083
18084     Evens = DAG.getBitcast(VT, Evens);
18085     Odds = DAG.getBitcast(VT, Odds);
18086
18087     // Merge the two vectors back together with a shuffle. This expands into 2
18088     // shuffles.
18089     static const int ShufMask[] = { 0, 4, 2, 6 };
18090     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18091   }
18092
18093   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18094          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18095
18096   //  Ahi = psrlqi(a, 32);
18097   //  Bhi = psrlqi(b, 32);
18098   //
18099   //  AloBlo = pmuludq(a, b);
18100   //  AloBhi = pmuludq(a, Bhi);
18101   //  AhiBlo = pmuludq(Ahi, b);
18102
18103   //  AloBhi = psllqi(AloBhi, 32);
18104   //  AhiBlo = psllqi(AhiBlo, 32);
18105   //  return AloBlo + AloBhi + AhiBlo;
18106
18107   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18108   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18109
18110   SDValue AhiBlo = Ahi;
18111   SDValue AloBhi = Bhi;
18112   // Bit cast to 32-bit vectors for MULUDQ
18113   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18114                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18115   A = DAG.getBitcast(MulVT, A);
18116   B = DAG.getBitcast(MulVT, B);
18117   Ahi = DAG.getBitcast(MulVT, Ahi);
18118   Bhi = DAG.getBitcast(MulVT, Bhi);
18119
18120   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18121   // After shifting right const values the result may be all-zero.
18122   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18123     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18124     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18125   }
18126   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18127     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18128     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18129   }
18130
18131   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18132   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18133 }
18134
18135 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18136   assert(Subtarget->isTargetWin64() && "Unexpected target");
18137   EVT VT = Op.getValueType();
18138   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18139          "Unexpected return type for lowering");
18140
18141   RTLIB::Libcall LC;
18142   bool isSigned;
18143   switch (Op->getOpcode()) {
18144   default: llvm_unreachable("Unexpected request for libcall!");
18145   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18146   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18147   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18148   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18149   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18150   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18151   }
18152
18153   SDLoc dl(Op);
18154   SDValue InChain = DAG.getEntryNode();
18155
18156   TargetLowering::ArgListTy Args;
18157   TargetLowering::ArgListEntry Entry;
18158   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18159     EVT ArgVT = Op->getOperand(i).getValueType();
18160     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18161            "Unexpected argument type for lowering");
18162     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18163     Entry.Node = StackPtr;
18164     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18165                            false, false, 16);
18166     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18167     Entry.Ty = PointerType::get(ArgTy,0);
18168     Entry.isSExt = false;
18169     Entry.isZExt = false;
18170     Args.push_back(Entry);
18171   }
18172
18173   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18174                                          getPointerTy(DAG.getDataLayout()));
18175
18176   TargetLowering::CallLoweringInfo CLI(DAG);
18177   CLI.setDebugLoc(dl).setChain(InChain)
18178     .setCallee(getLibcallCallingConv(LC),
18179                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18180                Callee, std::move(Args), 0)
18181     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18182
18183   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18184   return DAG.getBitcast(VT, CallInfo.first);
18185 }
18186
18187 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18188                              SelectionDAG &DAG) {
18189   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18190   MVT VT = Op0.getSimpleValueType();
18191   SDLoc dl(Op);
18192
18193   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18194          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18195
18196   // PMULxD operations multiply each even value (starting at 0) of LHS with
18197   // the related value of RHS and produce a widen result.
18198   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18199   // => <2 x i64> <ae|cg>
18200   //
18201   // In other word, to have all the results, we need to perform two PMULxD:
18202   // 1. one with the even values.
18203   // 2. one with the odd values.
18204   // To achieve #2, with need to place the odd values at an even position.
18205   //
18206   // Place the odd value at an even position (basically, shift all values 1
18207   // step to the left):
18208   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18209   // <a|b|c|d> => <b|undef|d|undef>
18210   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18211   // <e|f|g|h> => <f|undef|h|undef>
18212   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18213
18214   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18215   // ints.
18216   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18217   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18218   unsigned Opcode =
18219       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18220   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18221   // => <2 x i64> <ae|cg>
18222   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18223   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18224   // => <2 x i64> <bf|dh>
18225   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18226
18227   // Shuffle it back into the right order.
18228   SDValue Highs, Lows;
18229   if (VT == MVT::v8i32) {
18230     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18231     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18232     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18233     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18234   } else {
18235     const int HighMask[] = {1, 5, 3, 7};
18236     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18237     const int LowMask[] = {0, 4, 2, 6};
18238     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18239   }
18240
18241   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18242   // unsigned multiply.
18243   if (IsSigned && !Subtarget->hasSSE41()) {
18244     SDValue ShAmt = DAG.getConstant(
18245         31, dl,
18246         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18247     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18248                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18249     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18250                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18251
18252     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18253     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18254   }
18255
18256   // The first result of MUL_LOHI is actually the low value, followed by the
18257   // high value.
18258   SDValue Ops[] = {Lows, Highs};
18259   return DAG.getMergeValues(Ops, dl);
18260 }
18261
18262 // Return true if the required (according to Opcode) shift-imm form is natively
18263 // supported by the Subtarget
18264 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18265                                         unsigned Opcode) {
18266   if (VT.getScalarSizeInBits() < 16)
18267     return false;
18268
18269   if (VT.is512BitVector() &&
18270       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18271     return true;
18272
18273   bool LShift = VT.is128BitVector() ||
18274     (VT.is256BitVector() && Subtarget->hasInt256());
18275
18276   bool AShift = LShift && (Subtarget->hasVLX() ||
18277     (VT != MVT::v2i64 && VT != MVT::v4i64));
18278   return (Opcode == ISD::SRA) ? AShift : LShift;
18279 }
18280
18281 // The shift amount is a variable, but it is the same for all vector lanes.
18282 // These instructions are defined together with shift-immediate.
18283 static
18284 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18285                                       unsigned Opcode) {
18286   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18287 }
18288
18289 // Return true if the required (according to Opcode) variable-shift form is
18290 // natively supported by the Subtarget
18291 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18292                                     unsigned Opcode) {
18293
18294   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18295     return false;
18296
18297   // vXi16 supported only on AVX-512, BWI
18298   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18299     return false;
18300
18301   if (VT.is512BitVector() || Subtarget->hasVLX())
18302     return true;
18303
18304   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18305   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18306   return (Opcode == ISD::SRA) ? AShift : LShift;
18307 }
18308
18309 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18310                                          const X86Subtarget *Subtarget) {
18311   MVT VT = Op.getSimpleValueType();
18312   SDLoc dl(Op);
18313   SDValue R = Op.getOperand(0);
18314   SDValue Amt = Op.getOperand(1);
18315
18316   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18317     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18318
18319   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18320     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18321     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18322     SDValue Ex = DAG.getBitcast(ExVT, R);
18323
18324     if (ShiftAmt >= 32) {
18325       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18326       SDValue Upper =
18327           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18328       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18329                                                  ShiftAmt - 32, DAG);
18330       if (VT == MVT::v2i64)
18331         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18332       if (VT == MVT::v4i64)
18333         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18334                                   {9, 1, 11, 3, 13, 5, 15, 7});
18335     } else {
18336       // SRA upper i32, SHL whole i64 and select lower i32.
18337       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18338                                                  ShiftAmt, DAG);
18339       SDValue Lower =
18340           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18341       Lower = DAG.getBitcast(ExVT, Lower);
18342       if (VT == MVT::v2i64)
18343         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18344       if (VT == MVT::v4i64)
18345         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18346                                   {8, 1, 10, 3, 12, 5, 14, 7});
18347     }
18348     return DAG.getBitcast(VT, Ex);
18349   };
18350
18351   // Optimize shl/srl/sra with constant shift amount.
18352   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18353     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18354       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18355
18356       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18357         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18358
18359       // i64 SRA needs to be performed as partial shifts.
18360       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18361           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18362         return ArithmeticShiftRight64(ShiftAmt);
18363
18364       if (VT == MVT::v16i8 ||
18365           (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18366           VT == MVT::v64i8) {
18367         unsigned NumElts = VT.getVectorNumElements();
18368         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18369
18370         // Simple i8 add case
18371         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18372           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18373
18374         // ashr(R, 7)  === cmp_slt(R, 0)
18375         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18376           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18377           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18378         }
18379
18380         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18381         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18382           return SDValue();
18383
18384         if (Op.getOpcode() == ISD::SHL) {
18385           // Make a large shift.
18386           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18387                                                    R, ShiftAmt, DAG);
18388           SHL = DAG.getBitcast(VT, SHL);
18389           // Zero out the rightmost bits.
18390           return DAG.getNode(ISD::AND, dl, VT, SHL,
18391                              DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18392         }
18393         if (Op.getOpcode() == ISD::SRL) {
18394           // Make a large shift.
18395           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18396                                                    R, ShiftAmt, DAG);
18397           SRL = DAG.getBitcast(VT, SRL);
18398           // Zero out the leftmost bits.
18399           return DAG.getNode(ISD::AND, dl, VT, SRL,
18400                              DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18401         }
18402         if (Op.getOpcode() == ISD::SRA) {
18403           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18404           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18405
18406           SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18407           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18408           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18409           return Res;
18410         }
18411         llvm_unreachable("Unknown shift opcode.");
18412       }
18413     }
18414   }
18415
18416   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18417   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18418       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18419
18420     // Peek through any splat that was introduced for i64 shift vectorization.
18421     int SplatIndex = -1;
18422     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18423       if (SVN->isSplat()) {
18424         SplatIndex = SVN->getSplatIndex();
18425         Amt = Amt.getOperand(0);
18426         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18427                "Splat shuffle referencing second operand");
18428       }
18429
18430     if (Amt.getOpcode() != ISD::BITCAST ||
18431         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18432       return SDValue();
18433
18434     Amt = Amt.getOperand(0);
18435     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18436                      VT.getVectorNumElements();
18437     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18438     uint64_t ShiftAmt = 0;
18439     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18440     for (unsigned i = 0; i != Ratio; ++i) {
18441       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18442       if (!C)
18443         return SDValue();
18444       // 6 == Log2(64)
18445       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18446     }
18447
18448     // Check remaining shift amounts (if not a splat).
18449     if (SplatIndex < 0) {
18450       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18451         uint64_t ShAmt = 0;
18452         for (unsigned j = 0; j != Ratio; ++j) {
18453           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18454           if (!C)
18455             return SDValue();
18456           // 6 == Log2(64)
18457           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18458         }
18459         if (ShAmt != ShiftAmt)
18460           return SDValue();
18461       }
18462     }
18463
18464     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18465       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18466
18467     if (Op.getOpcode() == ISD::SRA)
18468       return ArithmeticShiftRight64(ShiftAmt);
18469   }
18470
18471   return SDValue();
18472 }
18473
18474 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18475                                         const X86Subtarget* Subtarget) {
18476   MVT VT = Op.getSimpleValueType();
18477   SDLoc dl(Op);
18478   SDValue R = Op.getOperand(0);
18479   SDValue Amt = Op.getOperand(1);
18480
18481   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18482     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18483
18484   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18485     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18486
18487   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18488     SDValue BaseShAmt;
18489     MVT EltVT = VT.getVectorElementType();
18490
18491     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18492       // Check if this build_vector node is doing a splat.
18493       // If so, then set BaseShAmt equal to the splat value.
18494       BaseShAmt = BV->getSplatValue();
18495       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18496         BaseShAmt = SDValue();
18497     } else {
18498       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18499         Amt = Amt.getOperand(0);
18500
18501       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18502       if (SVN && SVN->isSplat()) {
18503         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18504         SDValue InVec = Amt.getOperand(0);
18505         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18506           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18507                  "Unexpected shuffle index found!");
18508           BaseShAmt = InVec.getOperand(SplatIdx);
18509         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18510            if (ConstantSDNode *C =
18511                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18512              if (C->getZExtValue() == SplatIdx)
18513                BaseShAmt = InVec.getOperand(1);
18514            }
18515         }
18516
18517         if (!BaseShAmt)
18518           // Avoid introducing an extract element from a shuffle.
18519           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18520                                   DAG.getIntPtrConstant(SplatIdx, dl));
18521       }
18522     }
18523
18524     if (BaseShAmt.getNode()) {
18525       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18526       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18527         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18528       else if (EltVT.bitsLT(MVT::i32))
18529         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18530
18531       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18532     }
18533   }
18534
18535   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18536   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18537       Amt.getOpcode() == ISD::BITCAST &&
18538       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18539     Amt = Amt.getOperand(0);
18540     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18541                      VT.getVectorNumElements();
18542     std::vector<SDValue> Vals(Ratio);
18543     for (unsigned i = 0; i != Ratio; ++i)
18544       Vals[i] = Amt.getOperand(i);
18545     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18546       for (unsigned j = 0; j != Ratio; ++j)
18547         if (Vals[j] != Amt.getOperand(i + j))
18548           return SDValue();
18549     }
18550
18551     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18552       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18553   }
18554   return SDValue();
18555 }
18556
18557 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18558                           SelectionDAG &DAG) {
18559   MVT VT = Op.getSimpleValueType();
18560   SDLoc dl(Op);
18561   SDValue R = Op.getOperand(0);
18562   SDValue Amt = Op.getOperand(1);
18563
18564   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18565   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18566
18567   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18568     return V;
18569
18570   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18571     return V;
18572
18573   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18574     return Op;
18575
18576   // XOP has 128-bit variable logical/arithmetic shifts.
18577   // +ve/-ve Amt = shift left/right.
18578   if (Subtarget->hasXOP() &&
18579       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18580        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18581     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18582       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18583       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18584     }
18585     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18586       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18587     if (Op.getOpcode() == ISD::SRA)
18588       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18589   }
18590
18591   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18592   // shifts per-lane and then shuffle the partial results back together.
18593   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18594     // Splat the shift amounts so the scalar shifts above will catch it.
18595     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18596     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18597     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18598     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18599     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18600   }
18601
18602   // i64 vector arithmetic shift can be emulated with the transform:
18603   // M = lshr(SIGN_BIT, Amt)
18604   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18605   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18606       Op.getOpcode() == ISD::SRA) {
18607     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18608     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18609     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18610     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18611     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18612     return R;
18613   }
18614
18615   // If possible, lower this packed shift into a vector multiply instead of
18616   // expanding it into a sequence of scalar shifts.
18617   // Do this only if the vector shift count is a constant build_vector.
18618   if (Op.getOpcode() == ISD::SHL &&
18619       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18620        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18621       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18622     SmallVector<SDValue, 8> Elts;
18623     MVT SVT = VT.getVectorElementType();
18624     unsigned SVTBits = SVT.getSizeInBits();
18625     APInt One(SVTBits, 1);
18626     unsigned NumElems = VT.getVectorNumElements();
18627
18628     for (unsigned i=0; i !=NumElems; ++i) {
18629       SDValue Op = Amt->getOperand(i);
18630       if (Op->getOpcode() == ISD::UNDEF) {
18631         Elts.push_back(Op);
18632         continue;
18633       }
18634
18635       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18636       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18637       uint64_t ShAmt = C.getZExtValue();
18638       if (ShAmt >= SVTBits) {
18639         Elts.push_back(DAG.getUNDEF(SVT));
18640         continue;
18641       }
18642       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18643     }
18644     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18645     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18646   }
18647
18648   // Lower SHL with variable shift amount.
18649   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18650     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18651
18652     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18653                      DAG.getConstant(0x3f800000U, dl, VT));
18654     Op = DAG.getBitcast(MVT::v4f32, Op);
18655     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18656     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18657   }
18658
18659   // If possible, lower this shift as a sequence of two shifts by
18660   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18661   // Example:
18662   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18663   //
18664   // Could be rewritten as:
18665   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18666   //
18667   // The advantage is that the two shifts from the example would be
18668   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18669   // the vector shift into four scalar shifts plus four pairs of vector
18670   // insert/extract.
18671   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18672       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18673     unsigned TargetOpcode = X86ISD::MOVSS;
18674     bool CanBeSimplified;
18675     // The splat value for the first packed shift (the 'X' from the example).
18676     SDValue Amt1 = Amt->getOperand(0);
18677     // The splat value for the second packed shift (the 'Y' from the example).
18678     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18679                                         Amt->getOperand(2);
18680
18681     // See if it is possible to replace this node with a sequence of
18682     // two shifts followed by a MOVSS/MOVSD
18683     if (VT == MVT::v4i32) {
18684       // Check if it is legal to use a MOVSS.
18685       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18686                         Amt2 == Amt->getOperand(3);
18687       if (!CanBeSimplified) {
18688         // Otherwise, check if we can still simplify this node using a MOVSD.
18689         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18690                           Amt->getOperand(2) == Amt->getOperand(3);
18691         TargetOpcode = X86ISD::MOVSD;
18692         Amt2 = Amt->getOperand(2);
18693       }
18694     } else {
18695       // Do similar checks for the case where the machine value type
18696       // is MVT::v8i16.
18697       CanBeSimplified = Amt1 == Amt->getOperand(1);
18698       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18699         CanBeSimplified = Amt2 == Amt->getOperand(i);
18700
18701       if (!CanBeSimplified) {
18702         TargetOpcode = X86ISD::MOVSD;
18703         CanBeSimplified = true;
18704         Amt2 = Amt->getOperand(4);
18705         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18706           CanBeSimplified = Amt1 == Amt->getOperand(i);
18707         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18708           CanBeSimplified = Amt2 == Amt->getOperand(j);
18709       }
18710     }
18711
18712     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18713         isa<ConstantSDNode>(Amt2)) {
18714       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18715       MVT CastVT = MVT::v4i32;
18716       SDValue Splat1 =
18717         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18718       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18719       SDValue Splat2 =
18720         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18721       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18722       if (TargetOpcode == X86ISD::MOVSD)
18723         CastVT = MVT::v2i64;
18724       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18725       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18726       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18727                                             BitCast1, DAG);
18728       return DAG.getBitcast(VT, Result);
18729     }
18730   }
18731
18732   // v4i32 Non Uniform Shifts.
18733   // If the shift amount is constant we can shift each lane using the SSE2
18734   // immediate shifts, else we need to zero-extend each lane to the lower i64
18735   // and shift using the SSE2 variable shifts.
18736   // The separate results can then be blended together.
18737   if (VT == MVT::v4i32) {
18738     unsigned Opc = Op.getOpcode();
18739     SDValue Amt0, Amt1, Amt2, Amt3;
18740     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18741       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18742       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18743       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18744       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18745     } else {
18746       // ISD::SHL is handled above but we include it here for completeness.
18747       switch (Opc) {
18748       default:
18749         llvm_unreachable("Unknown target vector shift node");
18750       case ISD::SHL:
18751         Opc = X86ISD::VSHL;
18752         break;
18753       case ISD::SRL:
18754         Opc = X86ISD::VSRL;
18755         break;
18756       case ISD::SRA:
18757         Opc = X86ISD::VSRA;
18758         break;
18759       }
18760       // The SSE2 shifts use the lower i64 as the same shift amount for
18761       // all lanes and the upper i64 is ignored. These shuffle masks
18762       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18763       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18764       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18765       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18766       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18767       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18768     }
18769
18770     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18771     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18772     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18773     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18774     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18775     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18776     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18777   }
18778
18779   if (VT == MVT::v16i8 ||
18780       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18781     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18782     unsigned ShiftOpcode = Op->getOpcode();
18783
18784     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18785       // On SSE41 targets we make use of the fact that VSELECT lowers
18786       // to PBLENDVB which selects bytes based just on the sign bit.
18787       if (Subtarget->hasSSE41()) {
18788         V0 = DAG.getBitcast(VT, V0);
18789         V1 = DAG.getBitcast(VT, V1);
18790         Sel = DAG.getBitcast(VT, Sel);
18791         return DAG.getBitcast(SelVT,
18792                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18793       }
18794       // On pre-SSE41 targets we test for the sign bit by comparing to
18795       // zero - a negative value will set all bits of the lanes to true
18796       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18797       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18798       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18799       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18800     };
18801
18802     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18803     // We can safely do this using i16 shifts as we're only interested in
18804     // the 3 lower bits of each byte.
18805     Amt = DAG.getBitcast(ExtVT, Amt);
18806     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18807     Amt = DAG.getBitcast(VT, Amt);
18808
18809     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18810       // r = VSELECT(r, shift(r, 4), a);
18811       SDValue M =
18812           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18813       R = SignBitSelect(VT, Amt, M, R);
18814
18815       // a += a
18816       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18817
18818       // r = VSELECT(r, shift(r, 2), a);
18819       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18820       R = SignBitSelect(VT, Amt, M, R);
18821
18822       // a += a
18823       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18824
18825       // return VSELECT(r, shift(r, 1), a);
18826       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18827       R = SignBitSelect(VT, Amt, M, R);
18828       return R;
18829     }
18830
18831     if (Op->getOpcode() == ISD::SRA) {
18832       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18833       // so we can correctly sign extend. We don't care what happens to the
18834       // lower byte.
18835       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18836       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18837       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18838       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18839       ALo = DAG.getBitcast(ExtVT, ALo);
18840       AHi = DAG.getBitcast(ExtVT, AHi);
18841       RLo = DAG.getBitcast(ExtVT, RLo);
18842       RHi = DAG.getBitcast(ExtVT, RHi);
18843
18844       // r = VSELECT(r, shift(r, 4), a);
18845       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18846                                 DAG.getConstant(4, dl, ExtVT));
18847       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18848                                 DAG.getConstant(4, dl, ExtVT));
18849       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18850       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18851
18852       // a += a
18853       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18854       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18855
18856       // r = VSELECT(r, shift(r, 2), a);
18857       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18858                         DAG.getConstant(2, dl, ExtVT));
18859       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18860                         DAG.getConstant(2, dl, ExtVT));
18861       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18862       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18863
18864       // a += a
18865       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18866       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18867
18868       // r = VSELECT(r, shift(r, 1), a);
18869       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18870                         DAG.getConstant(1, dl, ExtVT));
18871       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18872                         DAG.getConstant(1, dl, ExtVT));
18873       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18874       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18875
18876       // Logical shift the result back to the lower byte, leaving a zero upper
18877       // byte
18878       // meaning that we can safely pack with PACKUSWB.
18879       RLo =
18880           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18881       RHi =
18882           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18883       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18884     }
18885   }
18886
18887   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18888   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18889   // solution better.
18890   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18891     MVT ExtVT = MVT::v8i32;
18892     unsigned ExtOpc =
18893         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18894     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18895     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18896     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18897                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18898   }
18899
18900   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18901     MVT ExtVT = MVT::v8i32;
18902     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18903     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18904     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18905     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18906     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18907     ALo = DAG.getBitcast(ExtVT, ALo);
18908     AHi = DAG.getBitcast(ExtVT, AHi);
18909     RLo = DAG.getBitcast(ExtVT, RLo);
18910     RHi = DAG.getBitcast(ExtVT, RHi);
18911     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18912     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18913     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18914     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18915     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18916   }
18917
18918   if (VT == MVT::v8i16) {
18919     unsigned ShiftOpcode = Op->getOpcode();
18920
18921     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18922       // On SSE41 targets we make use of the fact that VSELECT lowers
18923       // to PBLENDVB which selects bytes based just on the sign bit.
18924       if (Subtarget->hasSSE41()) {
18925         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18926         V0 = DAG.getBitcast(ExtVT, V0);
18927         V1 = DAG.getBitcast(ExtVT, V1);
18928         Sel = DAG.getBitcast(ExtVT, Sel);
18929         return DAG.getBitcast(
18930             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18931       }
18932       // On pre-SSE41 targets we splat the sign bit - a negative value will
18933       // set all bits of the lanes to true and VSELECT uses that in
18934       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18935       SDValue C =
18936           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18937       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18938     };
18939
18940     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18941     if (Subtarget->hasSSE41()) {
18942       // On SSE41 targets we need to replicate the shift mask in both
18943       // bytes for PBLENDVB.
18944       Amt = DAG.getNode(
18945           ISD::OR, dl, VT,
18946           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18947           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18948     } else {
18949       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18950     }
18951
18952     // r = VSELECT(r, shift(r, 8), a);
18953     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18954     R = SignBitSelect(Amt, M, R);
18955
18956     // a += a
18957     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18958
18959     // r = VSELECT(r, shift(r, 4), a);
18960     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18961     R = SignBitSelect(Amt, M, R);
18962
18963     // a += a
18964     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18965
18966     // r = VSELECT(r, shift(r, 2), a);
18967     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18968     R = SignBitSelect(Amt, M, R);
18969
18970     // a += a
18971     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18972
18973     // return VSELECT(r, shift(r, 1), a);
18974     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18975     R = SignBitSelect(Amt, M, R);
18976     return R;
18977   }
18978
18979   // Decompose 256-bit shifts into smaller 128-bit shifts.
18980   if (VT.is256BitVector()) {
18981     unsigned NumElems = VT.getVectorNumElements();
18982     MVT EltVT = VT.getVectorElementType();
18983     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18984
18985     // Extract the two vectors
18986     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18987     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18988
18989     // Recreate the shift amount vectors
18990     SDValue Amt1, Amt2;
18991     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18992       // Constant shift amount
18993       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18994       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18995       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18996
18997       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18998       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18999     } else {
19000       // Variable shift amount
19001       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19002       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19003     }
19004
19005     // Issue new vector shifts for the smaller types
19006     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19007     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19008
19009     // Concatenate the result back
19010     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19011   }
19012
19013   return SDValue();
19014 }
19015
19016 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19017                            SelectionDAG &DAG) {
19018   MVT VT = Op.getSimpleValueType();
19019   SDLoc DL(Op);
19020   SDValue R = Op.getOperand(0);
19021   SDValue Amt = Op.getOperand(1);
19022
19023   assert(VT.isVector() && "Custom lowering only for vector rotates!");
19024   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19025   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19026
19027   // XOP has 128-bit vector variable + immediate rotates.
19028   // +ve/-ve Amt = rotate left/right.
19029
19030   // Split 256-bit integers.
19031   if (VT.is256BitVector())
19032     return Lower256IntArith(Op, DAG);
19033
19034   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19035
19036   // Attempt to rotate by immediate.
19037   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19038     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19039       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19040       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19041       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19042                          DAG.getConstant(RotateAmt, DL, MVT::i8));
19043     }
19044   }
19045
19046   // Use general rotate by variable (per-element).
19047   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19048 }
19049
19050 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19051   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19052   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19053   // looks for this combo and may remove the "setcc" instruction if the "setcc"
19054   // has only one use.
19055   SDNode *N = Op.getNode();
19056   SDValue LHS = N->getOperand(0);
19057   SDValue RHS = N->getOperand(1);
19058   unsigned BaseOp = 0;
19059   unsigned Cond = 0;
19060   SDLoc DL(Op);
19061   switch (Op.getOpcode()) {
19062   default: llvm_unreachable("Unknown ovf instruction!");
19063   case ISD::SADDO:
19064     // A subtract of one will be selected as a INC. Note that INC doesn't
19065     // set CF, so we can't do this for UADDO.
19066     if (isOneConstant(RHS)) {
19067         BaseOp = X86ISD::INC;
19068         Cond = X86::COND_O;
19069         break;
19070       }
19071     BaseOp = X86ISD::ADD;
19072     Cond = X86::COND_O;
19073     break;
19074   case ISD::UADDO:
19075     BaseOp = X86ISD::ADD;
19076     Cond = X86::COND_B;
19077     break;
19078   case ISD::SSUBO:
19079     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19080     // set CF, so we can't do this for USUBO.
19081     if (isOneConstant(RHS)) {
19082         BaseOp = X86ISD::DEC;
19083         Cond = X86::COND_O;
19084         break;
19085       }
19086     BaseOp = X86ISD::SUB;
19087     Cond = X86::COND_O;
19088     break;
19089   case ISD::USUBO:
19090     BaseOp = X86ISD::SUB;
19091     Cond = X86::COND_B;
19092     break;
19093   case ISD::SMULO:
19094     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19095     Cond = X86::COND_O;
19096     break;
19097   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19098     if (N->getValueType(0) == MVT::i8) {
19099       BaseOp = X86ISD::UMUL8;
19100       Cond = X86::COND_O;
19101       break;
19102     }
19103     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19104                                  MVT::i32);
19105     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19106
19107     SDValue SetCC =
19108       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19109                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19110                   SDValue(Sum.getNode(), 2));
19111
19112     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19113   }
19114   }
19115
19116   // Also sets EFLAGS.
19117   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19118   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19119
19120   SDValue SetCC =
19121     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19122                 DAG.getConstant(Cond, DL, MVT::i32),
19123                 SDValue(Sum.getNode(), 1));
19124
19125   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19126 }
19127
19128 /// Returns true if the operand type is exactly twice the native width, and
19129 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19130 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19131 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19132 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19133   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19134
19135   if (OpWidth == 64)
19136     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19137   else if (OpWidth == 128)
19138     return Subtarget->hasCmpxchg16b();
19139   else
19140     return false;
19141 }
19142
19143 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19144   return needsCmpXchgNb(SI->getValueOperand()->getType());
19145 }
19146
19147 // Note: this turns large loads into lock cmpxchg8b/16b.
19148 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19149 TargetLowering::AtomicExpansionKind
19150 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19151   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19152   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19153                                                : AtomicExpansionKind::None;
19154 }
19155
19156 TargetLowering::AtomicExpansionKind
19157 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19158   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19159   Type *MemType = AI->getType();
19160
19161   // If the operand is too big, we must see if cmpxchg8/16b is available
19162   // and default to library calls otherwise.
19163   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19164     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19165                                    : AtomicExpansionKind::None;
19166   }
19167
19168   AtomicRMWInst::BinOp Op = AI->getOperation();
19169   switch (Op) {
19170   default:
19171     llvm_unreachable("Unknown atomic operation");
19172   case AtomicRMWInst::Xchg:
19173   case AtomicRMWInst::Add:
19174   case AtomicRMWInst::Sub:
19175     // It's better to use xadd, xsub or xchg for these in all cases.
19176     return AtomicExpansionKind::None;
19177   case AtomicRMWInst::Or:
19178   case AtomicRMWInst::And:
19179   case AtomicRMWInst::Xor:
19180     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19181     // prefix to a normal instruction for these operations.
19182     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19183                             : AtomicExpansionKind::None;
19184   case AtomicRMWInst::Nand:
19185   case AtomicRMWInst::Max:
19186   case AtomicRMWInst::Min:
19187   case AtomicRMWInst::UMax:
19188   case AtomicRMWInst::UMin:
19189     // These always require a non-trivial set of data operations on x86. We must
19190     // use a cmpxchg loop.
19191     return AtomicExpansionKind::CmpXChg;
19192   }
19193 }
19194
19195 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19196   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19197   // no-sse2). There isn't any reason to disable it if the target processor
19198   // supports it.
19199   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19200 }
19201
19202 LoadInst *
19203 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19204   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19205   Type *MemType = AI->getType();
19206   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19207   // there is no benefit in turning such RMWs into loads, and it is actually
19208   // harmful as it introduces a mfence.
19209   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19210     return nullptr;
19211
19212   auto Builder = IRBuilder<>(AI);
19213   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19214   auto SynchScope = AI->getSynchScope();
19215   // We must restrict the ordering to avoid generating loads with Release or
19216   // ReleaseAcquire orderings.
19217   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19218   auto Ptr = AI->getPointerOperand();
19219
19220   // Before the load we need a fence. Here is an example lifted from
19221   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19222   // is required:
19223   // Thread 0:
19224   //   x.store(1, relaxed);
19225   //   r1 = y.fetch_add(0, release);
19226   // Thread 1:
19227   //   y.fetch_add(42, acquire);
19228   //   r2 = x.load(relaxed);
19229   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19230   // lowered to just a load without a fence. A mfence flushes the store buffer,
19231   // making the optimization clearly correct.
19232   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19233   // otherwise, we might be able to be more aggressive on relaxed idempotent
19234   // rmw. In practice, they do not look useful, so we don't try to be
19235   // especially clever.
19236   if (SynchScope == SingleThread)
19237     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19238     // the IR level, so we must wrap it in an intrinsic.
19239     return nullptr;
19240
19241   if (!hasMFENCE(*Subtarget))
19242     // FIXME: it might make sense to use a locked operation here but on a
19243     // different cache-line to prevent cache-line bouncing. In practice it
19244     // is probably a small win, and x86 processors without mfence are rare
19245     // enough that we do not bother.
19246     return nullptr;
19247
19248   Function *MFence =
19249       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19250   Builder.CreateCall(MFence, {});
19251
19252   // Finally we can emit the atomic load.
19253   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19254           AI->getType()->getPrimitiveSizeInBits());
19255   Loaded->setAtomic(Order, SynchScope);
19256   AI->replaceAllUsesWith(Loaded);
19257   AI->eraseFromParent();
19258   return Loaded;
19259 }
19260
19261 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19262                                  SelectionDAG &DAG) {
19263   SDLoc dl(Op);
19264   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19265     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19266   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19267     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19268
19269   // The only fence that needs an instruction is a sequentially-consistent
19270   // cross-thread fence.
19271   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19272     if (hasMFENCE(*Subtarget))
19273       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19274
19275     SDValue Chain = Op.getOperand(0);
19276     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19277     SDValue Ops[] = {
19278       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19279       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19280       DAG.getRegister(0, MVT::i32),            // Index
19281       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19282       DAG.getRegister(0, MVT::i32),            // Segment.
19283       Zero,
19284       Chain
19285     };
19286     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19287     return SDValue(Res, 0);
19288   }
19289
19290   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19291   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19292 }
19293
19294 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19295                              SelectionDAG &DAG) {
19296   MVT T = Op.getSimpleValueType();
19297   SDLoc DL(Op);
19298   unsigned Reg = 0;
19299   unsigned size = 0;
19300   switch(T.SimpleTy) {
19301   default: llvm_unreachable("Invalid value type!");
19302   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19303   case MVT::i16: Reg = X86::AX;  size = 2; break;
19304   case MVT::i32: Reg = X86::EAX; size = 4; break;
19305   case MVT::i64:
19306     assert(Subtarget->is64Bit() && "Node not type legal!");
19307     Reg = X86::RAX; size = 8;
19308     break;
19309   }
19310   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19311                                   Op.getOperand(2), SDValue());
19312   SDValue Ops[] = { cpIn.getValue(0),
19313                     Op.getOperand(1),
19314                     Op.getOperand(3),
19315                     DAG.getTargetConstant(size, DL, MVT::i8),
19316                     cpIn.getValue(1) };
19317   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19318   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19319   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19320                                            Ops, T, MMO);
19321
19322   SDValue cpOut =
19323     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19324   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19325                                       MVT::i32, cpOut.getValue(2));
19326   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19327                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19328                                 EFLAGS);
19329
19330   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19331   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19332   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19333   return SDValue();
19334 }
19335
19336 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19337                             SelectionDAG &DAG) {
19338   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19339   MVT DstVT = Op.getSimpleValueType();
19340
19341   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19342     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19343     if (DstVT != MVT::f64)
19344       // This conversion needs to be expanded.
19345       return SDValue();
19346
19347     SDValue InVec = Op->getOperand(0);
19348     SDLoc dl(Op);
19349     unsigned NumElts = SrcVT.getVectorNumElements();
19350     MVT SVT = SrcVT.getVectorElementType();
19351
19352     // Widen the vector in input in the case of MVT::v2i32.
19353     // Example: from MVT::v2i32 to MVT::v4i32.
19354     SmallVector<SDValue, 16> Elts;
19355     for (unsigned i = 0, e = NumElts; i != e; ++i)
19356       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19357                                  DAG.getIntPtrConstant(i, dl)));
19358
19359     // Explicitly mark the extra elements as Undef.
19360     Elts.append(NumElts, DAG.getUNDEF(SVT));
19361
19362     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19363     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19364     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19365     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19366                        DAG.getIntPtrConstant(0, dl));
19367   }
19368
19369   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19370          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19371   assert((DstVT == MVT::i64 ||
19372           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19373          "Unexpected custom BITCAST");
19374   // i64 <=> MMX conversions are Legal.
19375   if (SrcVT==MVT::i64 && DstVT.isVector())
19376     return Op;
19377   if (DstVT==MVT::i64 && SrcVT.isVector())
19378     return Op;
19379   // MMX <=> MMX conversions are Legal.
19380   if (SrcVT.isVector() && DstVT.isVector())
19381     return Op;
19382   // All other conversions need to be expanded.
19383   return SDValue();
19384 }
19385
19386 /// Compute the horizontal sum of bytes in V for the elements of VT.
19387 ///
19388 /// Requires V to be a byte vector and VT to be an integer vector type with
19389 /// wider elements than V's type. The width of the elements of VT determines
19390 /// how many bytes of V are summed horizontally to produce each element of the
19391 /// result.
19392 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19393                                       const X86Subtarget *Subtarget,
19394                                       SelectionDAG &DAG) {
19395   SDLoc DL(V);
19396   MVT ByteVecVT = V.getSimpleValueType();
19397   MVT EltVT = VT.getVectorElementType();
19398   int NumElts = VT.getVectorNumElements();
19399   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19400          "Expected value to have byte element type.");
19401   assert(EltVT != MVT::i8 &&
19402          "Horizontal byte sum only makes sense for wider elements!");
19403   unsigned VecSize = VT.getSizeInBits();
19404   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19405
19406   // PSADBW instruction horizontally add all bytes and leave the result in i64
19407   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19408   if (EltVT == MVT::i64) {
19409     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19410     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19411     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19412     return DAG.getBitcast(VT, V);
19413   }
19414
19415   if (EltVT == MVT::i32) {
19416     // We unpack the low half and high half into i32s interleaved with zeros so
19417     // that we can use PSADBW to horizontally sum them. The most useful part of
19418     // this is that it lines up the results of two PSADBW instructions to be
19419     // two v2i64 vectors which concatenated are the 4 population counts. We can
19420     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19421     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19422     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19423     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19424
19425     // Do the horizontal sums into two v2i64s.
19426     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19427     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19428     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19429                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19430     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19431                        DAG.getBitcast(ByteVecVT, High), Zeros);
19432
19433     // Merge them together.
19434     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19435     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19436                     DAG.getBitcast(ShortVecVT, Low),
19437                     DAG.getBitcast(ShortVecVT, High));
19438
19439     return DAG.getBitcast(VT, V);
19440   }
19441
19442   // The only element type left is i16.
19443   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19444
19445   // To obtain pop count for each i16 element starting from the pop count for
19446   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19447   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19448   // directly supported.
19449   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19450   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19451   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19452   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19453                   DAG.getBitcast(ByteVecVT, V));
19454   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19455 }
19456
19457 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19458                                         const X86Subtarget *Subtarget,
19459                                         SelectionDAG &DAG) {
19460   MVT VT = Op.getSimpleValueType();
19461   MVT EltVT = VT.getVectorElementType();
19462   unsigned VecSize = VT.getSizeInBits();
19463
19464   // Implement a lookup table in register by using an algorithm based on:
19465   // http://wm.ite.pl/articles/sse-popcount.html
19466   //
19467   // The general idea is that every lower byte nibble in the input vector is an
19468   // index into a in-register pre-computed pop count table. We then split up the
19469   // input vector in two new ones: (1) a vector with only the shifted-right
19470   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19471   // masked out higher ones) for each byte. PSHUB is used separately with both
19472   // to index the in-register table. Next, both are added and the result is a
19473   // i8 vector where each element contains the pop count for input byte.
19474   //
19475   // To obtain the pop count for elements != i8, we follow up with the same
19476   // approach and use additional tricks as described below.
19477   //
19478   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19479                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19480                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19481                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19482
19483   int NumByteElts = VecSize / 8;
19484   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19485   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19486   SmallVector<SDValue, 16> LUTVec;
19487   for (int i = 0; i < NumByteElts; ++i)
19488     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19489   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19490   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19491                                   DAG.getConstant(0x0F, DL, MVT::i8));
19492   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19493
19494   // High nibbles
19495   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19496   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19497   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19498
19499   // Low nibbles
19500   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19501
19502   // The input vector is used as the shuffle mask that index elements into the
19503   // LUT. After counting low and high nibbles, add the vector to obtain the
19504   // final pop count per i8 element.
19505   SDValue HighPopCnt =
19506       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19507   SDValue LowPopCnt =
19508       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19509   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19510
19511   if (EltVT == MVT::i8)
19512     return PopCnt;
19513
19514   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19515 }
19516
19517 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19518                                        const X86Subtarget *Subtarget,
19519                                        SelectionDAG &DAG) {
19520   MVT VT = Op.getSimpleValueType();
19521   assert(VT.is128BitVector() &&
19522          "Only 128-bit vector bitmath lowering supported.");
19523
19524   int VecSize = VT.getSizeInBits();
19525   MVT EltVT = VT.getVectorElementType();
19526   int Len = EltVT.getSizeInBits();
19527
19528   // This is the vectorized version of the "best" algorithm from
19529   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19530   // with a minor tweak to use a series of adds + shifts instead of vector
19531   // multiplications. Implemented for all integer vector types. We only use
19532   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19533   // much faster, even faster than using native popcnt instructions.
19534
19535   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19536     MVT VT = V.getSimpleValueType();
19537     SmallVector<SDValue, 32> Shifters(
19538         VT.getVectorNumElements(),
19539         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19540     return DAG.getNode(OpCode, DL, VT, V,
19541                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19542   };
19543   auto GetMask = [&](SDValue V, APInt Mask) {
19544     MVT VT = V.getSimpleValueType();
19545     SmallVector<SDValue, 32> Masks(
19546         VT.getVectorNumElements(),
19547         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19548     return DAG.getNode(ISD::AND, DL, VT, V,
19549                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19550   };
19551
19552   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19553   // x86, so set the SRL type to have elements at least i16 wide. This is
19554   // correct because all of our SRLs are followed immediately by a mask anyways
19555   // that handles any bits that sneak into the high bits of the byte elements.
19556   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19557
19558   SDValue V = Op;
19559
19560   // v = v - ((v >> 1) & 0x55555555...)
19561   SDValue Srl =
19562       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19563   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19564   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19565
19566   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19567   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19568   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19569   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19570   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19571
19572   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19573   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19574   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19575   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19576
19577   // At this point, V contains the byte-wise population count, and we are
19578   // merely doing a horizontal sum if necessary to get the wider element
19579   // counts.
19580   if (EltVT == MVT::i8)
19581     return V;
19582
19583   return LowerHorizontalByteSum(
19584       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19585       DAG);
19586 }
19587
19588 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19589                                 SelectionDAG &DAG) {
19590   MVT VT = Op.getSimpleValueType();
19591   // FIXME: Need to add AVX-512 support here!
19592   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19593          "Unknown CTPOP type to handle");
19594   SDLoc DL(Op.getNode());
19595   SDValue Op0 = Op.getOperand(0);
19596
19597   if (!Subtarget->hasSSSE3()) {
19598     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19599     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19600     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19601   }
19602
19603   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19604     unsigned NumElems = VT.getVectorNumElements();
19605
19606     // Extract each 128-bit vector, compute pop count and concat the result.
19607     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19608     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19609
19610     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19611                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19612                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19613   }
19614
19615   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19616 }
19617
19618 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19619                           SelectionDAG &DAG) {
19620   assert(Op.getSimpleValueType().isVector() &&
19621          "We only do custom lowering for vector population count.");
19622   return LowerVectorCTPOP(Op, Subtarget, DAG);
19623 }
19624
19625 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19626   SDNode *Node = Op.getNode();
19627   SDLoc dl(Node);
19628   EVT T = Node->getValueType(0);
19629   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19630                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19631   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19632                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19633                        Node->getOperand(0),
19634                        Node->getOperand(1), negOp,
19635                        cast<AtomicSDNode>(Node)->getMemOperand(),
19636                        cast<AtomicSDNode>(Node)->getOrdering(),
19637                        cast<AtomicSDNode>(Node)->getSynchScope());
19638 }
19639
19640 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19641   SDNode *Node = Op.getNode();
19642   SDLoc dl(Node);
19643   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19644
19645   // Convert seq_cst store -> xchg
19646   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19647   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19648   //        (The only way to get a 16-byte store is cmpxchg16b)
19649   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19650   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19651       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19652     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19653                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19654                                  Node->getOperand(0),
19655                                  Node->getOperand(1), Node->getOperand(2),
19656                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19657                                  cast<AtomicSDNode>(Node)->getOrdering(),
19658                                  cast<AtomicSDNode>(Node)->getSynchScope());
19659     return Swap.getValue(1);
19660   }
19661   // Other atomic stores have a simple pattern.
19662   return Op;
19663 }
19664
19665 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19666   MVT VT = Op.getNode()->getSimpleValueType(0);
19667
19668   // Let legalize expand this if it isn't a legal type yet.
19669   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19670     return SDValue();
19671
19672   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19673
19674   unsigned Opc;
19675   bool ExtraOp = false;
19676   switch (Op.getOpcode()) {
19677   default: llvm_unreachable("Invalid code");
19678   case ISD::ADDC: Opc = X86ISD::ADD; break;
19679   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19680   case ISD::SUBC: Opc = X86ISD::SUB; break;
19681   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19682   }
19683
19684   if (!ExtraOp)
19685     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19686                        Op.getOperand(1));
19687   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19688                      Op.getOperand(1), Op.getOperand(2));
19689 }
19690
19691 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19692                             SelectionDAG &DAG) {
19693   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19694
19695   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19696   // which returns the values as { float, float } (in XMM0) or
19697   // { double, double } (which is returned in XMM0, XMM1).
19698   SDLoc dl(Op);
19699   SDValue Arg = Op.getOperand(0);
19700   EVT ArgVT = Arg.getValueType();
19701   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19702
19703   TargetLowering::ArgListTy Args;
19704   TargetLowering::ArgListEntry Entry;
19705
19706   Entry.Node = Arg;
19707   Entry.Ty = ArgTy;
19708   Entry.isSExt = false;
19709   Entry.isZExt = false;
19710   Args.push_back(Entry);
19711
19712   bool isF64 = ArgVT == MVT::f64;
19713   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19714   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19715   // the results are returned via SRet in memory.
19716   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19718   SDValue Callee =
19719       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19720
19721   Type *RetTy = isF64
19722     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19723     : (Type*)VectorType::get(ArgTy, 4);
19724
19725   TargetLowering::CallLoweringInfo CLI(DAG);
19726   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19727     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19728
19729   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19730
19731   if (isF64)
19732     // Returned in xmm0 and xmm1.
19733     return CallResult.first;
19734
19735   // Returned in bits 0:31 and 32:64 xmm0.
19736   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19737                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19738   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19739                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19740   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19741   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19742 }
19743
19744 /// Widen a vector input to a vector of NVT.  The
19745 /// input vector must have the same element type as NVT.
19746 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19747                             bool FillWithZeroes = false) {
19748   // Check if InOp already has the right width.
19749   MVT InVT = InOp.getSimpleValueType();
19750   if (InVT == NVT)
19751     return InOp;
19752
19753   if (InOp.isUndef())
19754     return DAG.getUNDEF(NVT);
19755
19756   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19757          "input and widen element type must match");
19758
19759   unsigned InNumElts = InVT.getVectorNumElements();
19760   unsigned WidenNumElts = NVT.getVectorNumElements();
19761   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
19762          "Unexpected request for vector widening");
19763
19764   EVT EltVT = NVT.getVectorElementType();
19765
19766   SDLoc dl(InOp);
19767   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
19768       InOp.getNumOperands() == 2) {
19769     SDValue N1 = InOp.getOperand(1);
19770     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
19771         N1.isUndef()) {
19772       InOp = InOp.getOperand(0);
19773       InVT = InOp.getSimpleValueType();
19774       InNumElts = InVT.getVectorNumElements();
19775     }
19776   }
19777   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
19778       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
19779     SmallVector<SDValue, 16> Ops;
19780     for (unsigned i = 0; i < InNumElts; ++i)
19781       Ops.push_back(InOp.getOperand(i));
19782
19783     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
19784       DAG.getUNDEF(EltVT);
19785     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
19786       Ops.push_back(FillVal);
19787     return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
19788   }
19789   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
19790     DAG.getUNDEF(NVT);
19791   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
19792                      InOp, DAG.getIntPtrConstant(0, dl));
19793 }
19794
19795 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19796                              SelectionDAG &DAG) {
19797   assert(Subtarget->hasAVX512() &&
19798          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19799
19800   // X86 scatter kills mask register, so its type should be added to
19801   // the list of return values.
19802   // If the "scatter" has 2 return values, it is already handled.
19803   if (Op.getNode()->getNumValues() == 2)
19804     return Op;
19805
19806   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19807   SDValue Src = N->getValue();
19808   MVT VT = Src.getSimpleValueType();
19809   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19810   SDLoc dl(Op);
19811
19812   SDValue NewScatter;
19813   SDValue Index = N->getIndex();
19814   SDValue Mask = N->getMask();
19815   SDValue Chain = N->getChain();
19816   SDValue BasePtr = N->getBasePtr();
19817   MVT MemVT = N->getMemoryVT().getSimpleVT();
19818   MVT IndexVT = Index.getSimpleValueType();
19819   MVT MaskVT = Mask.getSimpleValueType();
19820
19821   if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
19822     // The v2i32 value was promoted to v2i64.
19823     // Now we "redo" the type legalizer's work and widen the original
19824     // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
19825     // with a shuffle.
19826     assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
19827            "Unexpected memory type");
19828     int ShuffleMask[] = {0, 2, -1, -1};
19829     Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
19830                                DAG.getUNDEF(MVT::v4i32), ShuffleMask);
19831     // Now we have 4 elements instead of 2.
19832     // Expand the index.
19833     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
19834     Index = ExtendToType(Index, NewIndexVT, DAG);
19835
19836     // Expand the mask with zeroes
19837     // Mask may be <2 x i64> or <2 x i1> at this moment
19838     assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
19839            "Unexpected mask type");
19840     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
19841     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
19842     VT = MVT::v4i32;
19843   }
19844
19845   unsigned NumElts = VT.getVectorNumElements();
19846   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19847       !Index.getSimpleValueType().is512BitVector()) {
19848     // AVX512F supports only 512-bit vectors. Or data or index should
19849     // be 512 bit wide. If now the both index and data are 256-bit, but
19850     // the vector contains 8 elements, we just sign-extend the index
19851     if (IndexVT == MVT::v8i32)
19852       // Just extend index
19853       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19854     else {
19855       // The minimal number of elts in scatter is 8
19856       NumElts = 8;
19857       // Index
19858       MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
19859       // Use original index here, do not modify the index twice
19860       Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
19861       if (IndexVT.getScalarType() == MVT::i32)
19862         Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19863
19864       // Mask
19865       // At this point we have promoted mask operand
19866       assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
19867       MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
19868       // Use the original mask here, do not modify the mask twice
19869       Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true); 
19870
19871       // The value that should be stored
19872       MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
19873       Src = ExtendToType(Src, NewVT, DAG);
19874     }
19875   }
19876   // If the mask is "wide" at this point - truncate it to i1 vector
19877   MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
19878   Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
19879
19880   // The mask is killed by scatter, add it to the values
19881   SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
19882   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
19883   NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
19884                                     N->getMemOperand());
19885   DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19886   return SDValue(NewScatter.getNode(), 0);
19887 }
19888
19889 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
19890                           SelectionDAG &DAG) {
19891
19892   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
19893   MVT VT = Op.getSimpleValueType();
19894   SDValue Mask = N->getMask();
19895   SDLoc dl(Op);
19896
19897   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
19898       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
19899     // This operation is legal for targets with VLX, but without
19900     // VLX the vector should be widened to 512 bit
19901     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
19902     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
19903     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
19904     SDValue Src0 = N->getSrc0();
19905     Src0 = ExtendToType(Src0, WideDataVT, DAG);
19906     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
19907     SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
19908                                         N->getBasePtr(), Mask, Src0,
19909                                         N->getMemoryVT(), N->getMemOperand(),
19910                                         N->getExtensionType());
19911
19912     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
19913                                  NewLoad.getValue(0),
19914                                  DAG.getIntPtrConstant(0, dl));
19915     SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
19916     return DAG.getMergeValues(RetOps, dl);
19917   }
19918   return Op;
19919 }
19920
19921 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
19922                            SelectionDAG &DAG) {
19923   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
19924   SDValue DataToStore = N->getValue();
19925   MVT VT = DataToStore.getSimpleValueType();
19926   SDValue Mask = N->getMask();
19927   SDLoc dl(Op);
19928
19929   if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
19930       !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
19931     // This operation is legal for targets with VLX, but without
19932     // VLX the vector should be widened to 512 bit
19933     unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
19934     MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
19935     MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
19936     DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
19937     Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
19938     return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
19939                               Mask, N->getMemoryVT(), N->getMemOperand(),
19940                               N->isTruncatingStore());
19941   }
19942   return Op;
19943 }
19944
19945 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19946                             SelectionDAG &DAG) {
19947   assert(Subtarget->hasAVX512() &&
19948          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19949
19950   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19951   SDLoc dl(Op);
19952   MVT VT = Op.getSimpleValueType();
19953   SDValue Index = N->getIndex();
19954   SDValue Mask = N->getMask();
19955   SDValue Src0 = N->getValue();
19956   MVT IndexVT = Index.getSimpleValueType();
19957   MVT MaskVT = Mask.getSimpleValueType();
19958
19959   unsigned NumElts = VT.getVectorNumElements();
19960   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19961
19962   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19963       !Index.getSimpleValueType().is512BitVector()) {
19964     // AVX512F supports only 512-bit vectors. Or data or index should
19965     // be 512 bit wide. If now the both index and data are 256-bit, but
19966     // the vector contains 8 elements, we just sign-extend the index
19967     if (NumElts == 8) {
19968       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19969       SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19970                         N->getOperand(3), Index };
19971       DAG.UpdateNodeOperands(N, Ops);
19972       return Op;
19973     }
19974
19975     // Minimal number of elements in Gather
19976     NumElts = 8;
19977     // Index
19978     MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
19979     Index = ExtendToType(Index, NewIndexVT, DAG);
19980     if (IndexVT.getScalarType() == MVT::i32)
19981       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19982
19983     // Mask
19984     MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
19985     // At this point we have promoted mask operand
19986     assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
19987     MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
19988     Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
19989     Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
19990
19991     // The pass-thru value
19992     MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
19993     Src0 = ExtendToType(Src0, NewVT, DAG);
19994
19995     SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
19996     SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
19997                                             N->getMemoryVT(), dl, Ops,
19998                                             N->getMemOperand());
19999     SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20000                                  NewGather.getValue(0),
20001                                  DAG.getIntPtrConstant(0, dl));
20002     SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20003     return DAG.getMergeValues(RetOps, dl);
20004   }
20005   return Op;
20006 }
20007
20008 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20009                                                     SelectionDAG &DAG) const {
20010   // TODO: Eventually, the lowering of these nodes should be informed by or
20011   // deferred to the GC strategy for the function in which they appear. For
20012   // now, however, they must be lowered to something. Since they are logically
20013   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20014   // require special handling for these nodes), lower them as literal NOOPs for
20015   // the time being.
20016   SmallVector<SDValue, 2> Ops;
20017
20018   Ops.push_back(Op.getOperand(0));
20019   if (Op->getGluedNode())
20020     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20021
20022   SDLoc OpDL(Op);
20023   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20024   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20025
20026   return NOOP;
20027 }
20028
20029 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20030                                                   SelectionDAG &DAG) const {
20031   // TODO: Eventually, the lowering of these nodes should be informed by or
20032   // deferred to the GC strategy for the function in which they appear. For
20033   // now, however, they must be lowered to something. Since they are logically
20034   // no-ops in the case of a null GC strategy (or a GC strategy which does not
20035   // require special handling for these nodes), lower them as literal NOOPs for
20036   // the time being.
20037   SmallVector<SDValue, 2> Ops;
20038
20039   Ops.push_back(Op.getOperand(0));
20040   if (Op->getGluedNode())
20041     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20042
20043   SDLoc OpDL(Op);
20044   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20045   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20046
20047   return NOOP;
20048 }
20049
20050 /// LowerOperation - Provide custom lowering hooks for some operations.
20051 ///
20052 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20053   switch (Op.getOpcode()) {
20054   default: llvm_unreachable("Should not custom lower this!");
20055   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20056   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20057     return LowerCMP_SWAP(Op, Subtarget, DAG);
20058   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
20059   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
20060   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
20061   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
20062   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20063   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
20064   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
20065   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20066   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
20067   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20068   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20069   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
20070   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
20071   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
20072   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
20073   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
20074   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
20075   case ISD::SHL_PARTS:
20076   case ISD::SRA_PARTS:
20077   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
20078   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
20079   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
20080   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
20081   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
20082   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20083   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
20084   case ISD::SIGN_EXTEND_VECTOR_INREG:
20085     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20086   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
20087   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
20088   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
20089   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
20090   case ISD::FABS:
20091   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
20092   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
20093   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
20094   case ISD::SETCC:              return LowerSETCC(Op, DAG);
20095   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
20096   case ISD::SELECT:             return LowerSELECT(Op, DAG);
20097   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
20098   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
20099   case ISD::VASTART:            return LowerVASTART(Op, DAG);
20100   case ISD::VAARG:              return LowerVAARG(Op, DAG);
20101   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
20102   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20103   case ISD::INTRINSIC_VOID:
20104   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20105   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
20106   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
20107   case ISD::FRAME_TO_ARGS_OFFSET:
20108                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20109   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20110   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
20111   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
20112   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
20113   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
20114   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
20115   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
20116   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
20117   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20118   case ISD::CTTZ:
20119   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
20120   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
20121   case ISD::UMUL_LOHI:
20122   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
20123   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
20124   case ISD::SRA:
20125   case ISD::SRL:
20126   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
20127   case ISD::SADDO:
20128   case ISD::UADDO:
20129   case ISD::SSUBO:
20130   case ISD::USUBO:
20131   case ISD::SMULO:
20132   case ISD::UMULO:              return LowerXALUO(Op, DAG);
20133   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20134   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
20135   case ISD::ADDC:
20136   case ISD::ADDE:
20137   case ISD::SUBC:
20138   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20139   case ISD::ADD:                return LowerADD(Op, DAG);
20140   case ISD::SUB:                return LowerSUB(Op, DAG);
20141   case ISD::SMAX:
20142   case ISD::SMIN:
20143   case ISD::UMAX:
20144   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
20145   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
20146   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
20147   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
20148   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
20149   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
20150   case ISD::GC_TRANSITION_START:
20151                                 return LowerGC_TRANSITION_START(Op, DAG);
20152   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
20153   }
20154 }
20155
20156 /// ReplaceNodeResults - Replace a node with an illegal result type
20157 /// with a new node built out of custom code.
20158 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20159                                            SmallVectorImpl<SDValue>&Results,
20160                                            SelectionDAG &DAG) const {
20161   SDLoc dl(N);
20162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20163   switch (N->getOpcode()) {
20164   default:
20165     llvm_unreachable("Do not know how to custom type legalize this operation!");
20166   case X86ISD::AVG: {
20167     // Legalize types for X86ISD::AVG by expanding vectors.
20168     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20169
20170     auto InVT = N->getValueType(0);
20171     auto InVTSize = InVT.getSizeInBits();
20172     const unsigned RegSize =
20173         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20174     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20175            "512-bit vector requires AVX512");
20176     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20177            "256-bit vector requires AVX2");
20178
20179     auto ElemVT = InVT.getVectorElementType();
20180     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20181                                   RegSize / ElemVT.getSizeInBits());
20182     assert(RegSize % InVT.getSizeInBits() == 0);
20183     unsigned NumConcat = RegSize / InVT.getSizeInBits();
20184
20185     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20186     Ops[0] = N->getOperand(0);
20187     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20188     Ops[0] = N->getOperand(1);
20189     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20190
20191     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20192     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20193                                   DAG.getIntPtrConstant(0, dl)));
20194     return;
20195   }
20196   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20197   case X86ISD::FMINC:
20198   case X86ISD::FMIN:
20199   case X86ISD::FMAXC:
20200   case X86ISD::FMAX: {
20201     EVT VT = N->getValueType(0);
20202     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20203     SDValue UNDEF = DAG.getUNDEF(VT);
20204     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20205                               N->getOperand(0), UNDEF);
20206     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20207                               N->getOperand(1), UNDEF);
20208     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20209     return;
20210   }
20211   case ISD::SIGN_EXTEND_INREG:
20212   case ISD::ADDC:
20213   case ISD::ADDE:
20214   case ISD::SUBC:
20215   case ISD::SUBE:
20216     // We don't want to expand or promote these.
20217     return;
20218   case ISD::SDIV:
20219   case ISD::UDIV:
20220   case ISD::SREM:
20221   case ISD::UREM:
20222   case ISD::SDIVREM:
20223   case ISD::UDIVREM: {
20224     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20225     Results.push_back(V);
20226     return;
20227   }
20228   case ISD::FP_TO_SINT:
20229   case ISD::FP_TO_UINT: {
20230     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20231
20232     std::pair<SDValue,SDValue> Vals =
20233         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20234     SDValue FIST = Vals.first, StackSlot = Vals.second;
20235     if (FIST.getNode()) {
20236       EVT VT = N->getValueType(0);
20237       // Return a load from the stack slot.
20238       if (StackSlot.getNode())
20239         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20240                                       MachinePointerInfo(),
20241                                       false, false, false, 0));
20242       else
20243         Results.push_back(FIST);
20244     }
20245     return;
20246   }
20247   case ISD::UINT_TO_FP: {
20248     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20249     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20250         N->getValueType(0) != MVT::v2f32)
20251       return;
20252     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20253                                  N->getOperand(0));
20254     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20255                                      MVT::f64);
20256     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20257     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20258                              DAG.getBitcast(MVT::v2i64, VBias));
20259     Or = DAG.getBitcast(MVT::v2f64, Or);
20260     // TODO: Are there any fast-math-flags to propagate here?
20261     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20262     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20263     return;
20264   }
20265   case ISD::FP_ROUND: {
20266     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20267         return;
20268     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20269     Results.push_back(V);
20270     return;
20271   }
20272   case ISD::FP_EXTEND: {
20273     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20274     // No other ValueType for FP_EXTEND should reach this point.
20275     assert(N->getValueType(0) == MVT::v2f32 &&
20276            "Do not know how to legalize this Node");
20277     return;
20278   }
20279   case ISD::INTRINSIC_W_CHAIN: {
20280     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20281     switch (IntNo) {
20282     default : llvm_unreachable("Do not know how to custom type "
20283                                "legalize this intrinsic operation!");
20284     case Intrinsic::x86_rdtsc:
20285       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20286                                      Results);
20287     case Intrinsic::x86_rdtscp:
20288       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20289                                      Results);
20290     case Intrinsic::x86_rdpmc:
20291       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20292     }
20293   }
20294   case ISD::INTRINSIC_WO_CHAIN: {
20295     if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20296       Results.push_back(V);
20297     return;
20298   }
20299   case ISD::READCYCLECOUNTER: {
20300     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20301                                    Results);
20302   }
20303   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20304     EVT T = N->getValueType(0);
20305     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20306     bool Regs64bit = T == MVT::i128;
20307     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20308     SDValue cpInL, cpInH;
20309     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20310                         DAG.getConstant(0, dl, HalfT));
20311     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20312                         DAG.getConstant(1, dl, HalfT));
20313     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20314                              Regs64bit ? X86::RAX : X86::EAX,
20315                              cpInL, SDValue());
20316     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20317                              Regs64bit ? X86::RDX : X86::EDX,
20318                              cpInH, cpInL.getValue(1));
20319     SDValue swapInL, swapInH;
20320     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20321                           DAG.getConstant(0, dl, HalfT));
20322     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20323                           DAG.getConstant(1, dl, HalfT));
20324     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20325                                Regs64bit ? X86::RBX : X86::EBX,
20326                                swapInL, cpInH.getValue(1));
20327     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20328                                Regs64bit ? X86::RCX : X86::ECX,
20329                                swapInH, swapInL.getValue(1));
20330     SDValue Ops[] = { swapInH.getValue(0),
20331                       N->getOperand(1),
20332                       swapInH.getValue(1) };
20333     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20334     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20335     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20336                                   X86ISD::LCMPXCHG8_DAG;
20337     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20338     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20339                                         Regs64bit ? X86::RAX : X86::EAX,
20340                                         HalfT, Result.getValue(1));
20341     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20342                                         Regs64bit ? X86::RDX : X86::EDX,
20343                                         HalfT, cpOutL.getValue(2));
20344     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20345
20346     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20347                                         MVT::i32, cpOutH.getValue(2));
20348     SDValue Success =
20349         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20350                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20351     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20352
20353     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20354     Results.push_back(Success);
20355     Results.push_back(EFLAGS.getValue(1));
20356     return;
20357   }
20358   case ISD::ATOMIC_SWAP:
20359   case ISD::ATOMIC_LOAD_ADD:
20360   case ISD::ATOMIC_LOAD_SUB:
20361   case ISD::ATOMIC_LOAD_AND:
20362   case ISD::ATOMIC_LOAD_OR:
20363   case ISD::ATOMIC_LOAD_XOR:
20364   case ISD::ATOMIC_LOAD_NAND:
20365   case ISD::ATOMIC_LOAD_MIN:
20366   case ISD::ATOMIC_LOAD_MAX:
20367   case ISD::ATOMIC_LOAD_UMIN:
20368   case ISD::ATOMIC_LOAD_UMAX:
20369   case ISD::ATOMIC_LOAD: {
20370     // Delegate to generic TypeLegalization. Situations we can really handle
20371     // should have already been dealt with by AtomicExpandPass.cpp.
20372     break;
20373   }
20374   case ISD::BITCAST: {
20375     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20376     EVT DstVT = N->getValueType(0);
20377     EVT SrcVT = N->getOperand(0)->getValueType(0);
20378
20379     if (SrcVT != MVT::f64 ||
20380         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20381       return;
20382
20383     unsigned NumElts = DstVT.getVectorNumElements();
20384     EVT SVT = DstVT.getVectorElementType();
20385     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20386     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20387                                    MVT::v2f64, N->getOperand(0));
20388     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20389
20390     if (ExperimentalVectorWideningLegalization) {
20391       // If we are legalizing vectors by widening, we already have the desired
20392       // legal vector type, just return it.
20393       Results.push_back(ToVecInt);
20394       return;
20395     }
20396
20397     SmallVector<SDValue, 8> Elts;
20398     for (unsigned i = 0, e = NumElts; i != e; ++i)
20399       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20400                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20401
20402     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20403   }
20404   }
20405 }
20406
20407 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20408   switch ((X86ISD::NodeType)Opcode) {
20409   case X86ISD::FIRST_NUMBER:       break;
20410   case X86ISD::BSF:                return "X86ISD::BSF";
20411   case X86ISD::BSR:                return "X86ISD::BSR";
20412   case X86ISD::SHLD:               return "X86ISD::SHLD";
20413   case X86ISD::SHRD:               return "X86ISD::SHRD";
20414   case X86ISD::FAND:               return "X86ISD::FAND";
20415   case X86ISD::FANDN:              return "X86ISD::FANDN";
20416   case X86ISD::FOR:                return "X86ISD::FOR";
20417   case X86ISD::FXOR:               return "X86ISD::FXOR";
20418   case X86ISD::FILD:               return "X86ISD::FILD";
20419   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20420   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20421   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20422   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20423   case X86ISD::FLD:                return "X86ISD::FLD";
20424   case X86ISD::FST:                return "X86ISD::FST";
20425   case X86ISD::CALL:               return "X86ISD::CALL";
20426   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20427   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20428   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20429   case X86ISD::BT:                 return "X86ISD::BT";
20430   case X86ISD::CMP:                return "X86ISD::CMP";
20431   case X86ISD::COMI:               return "X86ISD::COMI";
20432   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20433   case X86ISD::CMPM:               return "X86ISD::CMPM";
20434   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20435   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20436   case X86ISD::SETCC:              return "X86ISD::SETCC";
20437   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20438   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20439   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20440   case X86ISD::CMOV:               return "X86ISD::CMOV";
20441   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20442   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20443   case X86ISD::IRET:               return "X86ISD::IRET";
20444   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20445   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20446   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20447   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20448   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20449   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20450   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20451   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20452   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20453   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20454   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20455   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20456   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20457   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20458   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20459   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20460   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20461   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20462   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20463   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20464   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20465   case X86ISD::HADD:               return "X86ISD::HADD";
20466   case X86ISD::HSUB:               return "X86ISD::HSUB";
20467   case X86ISD::FHADD:              return "X86ISD::FHADD";
20468   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20469   case X86ISD::ABS:                return "X86ISD::ABS";
20470   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20471   case X86ISD::FMAX:               return "X86ISD::FMAX";
20472   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20473   case X86ISD::FMIN:               return "X86ISD::FMIN";
20474   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20475   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20476   case X86ISD::FMINC:              return "X86ISD::FMINC";
20477   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20478   case X86ISD::FRCP:               return "X86ISD::FRCP";
20479   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20480   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20481   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20482   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20483   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20484   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20485   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20486   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20487   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20488   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20489   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20490   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20491   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20492   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20493   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20494   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20495   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20496   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20497   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20498   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20499   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20500   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20501   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20502   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20503   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20504   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20505   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20506   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20507   case X86ISD::VSHL:               return "X86ISD::VSHL";
20508   case X86ISD::VSRL:               return "X86ISD::VSRL";
20509   case X86ISD::VSRA:               return "X86ISD::VSRA";
20510   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20511   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20512   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20513   case X86ISD::CMPP:               return "X86ISD::CMPP";
20514   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20515   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20516   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20517   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20518   case X86ISD::ADD:                return "X86ISD::ADD";
20519   case X86ISD::SUB:                return "X86ISD::SUB";
20520   case X86ISD::ADC:                return "X86ISD::ADC";
20521   case X86ISD::SBB:                return "X86ISD::SBB";
20522   case X86ISD::SMUL:               return "X86ISD::SMUL";
20523   case X86ISD::UMUL:               return "X86ISD::UMUL";
20524   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20525   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20526   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20527   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20528   case X86ISD::INC:                return "X86ISD::INC";
20529   case X86ISD::DEC:                return "X86ISD::DEC";
20530   case X86ISD::OR:                 return "X86ISD::OR";
20531   case X86ISD::XOR:                return "X86ISD::XOR";
20532   case X86ISD::AND:                return "X86ISD::AND";
20533   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20534   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20535   case X86ISD::PTEST:              return "X86ISD::PTEST";
20536   case X86ISD::TESTP:              return "X86ISD::TESTP";
20537   case X86ISD::TESTM:              return "X86ISD::TESTM";
20538   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20539   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20540   case X86ISD::KTEST:              return "X86ISD::KTEST";
20541   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20542   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20543   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20544   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20545   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20546   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20547   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20548   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20549   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20550   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20551   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20552   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20553   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20554   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20555   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20556   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20557   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20558   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20559   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20560   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20561   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20562   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20563   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20564   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20565   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20566   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20567   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20568   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20569   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20570   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20571   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20572   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20573   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20574   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20575   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20576   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20577   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20578   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20579   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20580   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20581   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20582   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20583   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20584   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20585   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20586   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20587   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20588   case X86ISD::SAHF:               return "X86ISD::SAHF";
20589   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20590   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20591   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20592   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20593   case X86ISD::VPROT:              return "X86ISD::VPROT";
20594   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20595   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20596   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20597   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20598   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20599   case X86ISD::FMADD:              return "X86ISD::FMADD";
20600   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20601   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20602   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20603   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20604   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20605   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20606   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20607   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20608   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20609   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20610   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20611   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20612   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20613   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20614   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20615   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20616   case X86ISD::XTEST:              return "X86ISD::XTEST";
20617   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20618   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20619   case X86ISD::SELECT:             return "X86ISD::SELECT";
20620   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20621   case X86ISD::RCP28:              return "X86ISD::RCP28";
20622   case X86ISD::EXP2:               return "X86ISD::EXP2";
20623   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20624   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20625   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20626   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20627   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20628   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20629   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20630   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20631   case X86ISD::ADDS:               return "X86ISD::ADDS";
20632   case X86ISD::SUBS:               return "X86ISD::SUBS";
20633   case X86ISD::AVG:                return "X86ISD::AVG";
20634   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20635   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20636   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20637   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20638   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20639   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20640   case X86ISD::VFPCLASSS:          return "X86ISD::VFPCLASSS";
20641   }
20642   return nullptr;
20643 }
20644
20645 // isLegalAddressingMode - Return true if the addressing mode represented
20646 // by AM is legal for this target, for a load/store of the specified type.
20647 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20648                                               const AddrMode &AM, Type *Ty,
20649                                               unsigned AS) const {
20650   // X86 supports extremely general addressing modes.
20651   CodeModel::Model M = getTargetMachine().getCodeModel();
20652   Reloc::Model R = getTargetMachine().getRelocationModel();
20653
20654   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20655   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20656     return false;
20657
20658   if (AM.BaseGV) {
20659     unsigned GVFlags =
20660       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20661
20662     // If a reference to this global requires an extra load, we can't fold it.
20663     if (isGlobalStubReference(GVFlags))
20664       return false;
20665
20666     // If BaseGV requires a register for the PIC base, we cannot also have a
20667     // BaseReg specified.
20668     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20669       return false;
20670
20671     // If lower 4G is not available, then we must use rip-relative addressing.
20672     if ((M != CodeModel::Small || R != Reloc::Static) &&
20673         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20674       return false;
20675   }
20676
20677   switch (AM.Scale) {
20678   case 0:
20679   case 1:
20680   case 2:
20681   case 4:
20682   case 8:
20683     // These scales always work.
20684     break;
20685   case 3:
20686   case 5:
20687   case 9:
20688     // These scales are formed with basereg+scalereg.  Only accept if there is
20689     // no basereg yet.
20690     if (AM.HasBaseReg)
20691       return false;
20692     break;
20693   default:  // Other stuff never works.
20694     return false;
20695   }
20696
20697   return true;
20698 }
20699
20700 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20701   unsigned Bits = Ty->getScalarSizeInBits();
20702
20703   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20704   // particularly cheaper than those without.
20705   if (Bits == 8)
20706     return false;
20707
20708   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20709   // variable shifts just as cheap as scalar ones.
20710   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20711     return false;
20712
20713   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20714   // fully general vector.
20715   return true;
20716 }
20717
20718 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20719   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20720     return false;
20721   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20722   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20723   return NumBits1 > NumBits2;
20724 }
20725
20726 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20727   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20728     return false;
20729
20730   if (!isTypeLegal(EVT::getEVT(Ty1)))
20731     return false;
20732
20733   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20734
20735   // Assuming the caller doesn't have a zeroext or signext return parameter,
20736   // truncation all the way down to i1 is valid.
20737   return true;
20738 }
20739
20740 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20741   return isInt<32>(Imm);
20742 }
20743
20744 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20745   // Can also use sub to handle negated immediates.
20746   return isInt<32>(Imm);
20747 }
20748
20749 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20750   if (!VT1.isInteger() || !VT2.isInteger())
20751     return false;
20752   unsigned NumBits1 = VT1.getSizeInBits();
20753   unsigned NumBits2 = VT2.getSizeInBits();
20754   return NumBits1 > NumBits2;
20755 }
20756
20757 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20758   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20759   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20760 }
20761
20762 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20763   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20764   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20765 }
20766
20767 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20768   EVT VT1 = Val.getValueType();
20769   if (isZExtFree(VT1, VT2))
20770     return true;
20771
20772   if (Val.getOpcode() != ISD::LOAD)
20773     return false;
20774
20775   if (!VT1.isSimple() || !VT1.isInteger() ||
20776       !VT2.isSimple() || !VT2.isInteger())
20777     return false;
20778
20779   switch (VT1.getSimpleVT().SimpleTy) {
20780   default: break;
20781   case MVT::i8:
20782   case MVT::i16:
20783   case MVT::i32:
20784     // X86 has 8, 16, and 32-bit zero-extending loads.
20785     return true;
20786   }
20787
20788   return false;
20789 }
20790
20791 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20792
20793 bool
20794 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20795   if (!Subtarget->hasAnyFMA())
20796     return false;
20797
20798   VT = VT.getScalarType();
20799
20800   if (!VT.isSimple())
20801     return false;
20802
20803   switch (VT.getSimpleVT().SimpleTy) {
20804   case MVT::f32:
20805   case MVT::f64:
20806     return true;
20807   default:
20808     break;
20809   }
20810
20811   return false;
20812 }
20813
20814 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20815   // i16 instructions are longer (0x66 prefix) and potentially slower.
20816   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20817 }
20818
20819 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20820 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20821 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20822 /// are assumed to be legal.
20823 bool
20824 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20825                                       EVT VT) const {
20826   if (!VT.isSimple())
20827     return false;
20828
20829   // Not for i1 vectors
20830   if (VT.getSimpleVT().getScalarType() == MVT::i1)
20831     return false;
20832
20833   // Very little shuffling can be done for 64-bit vectors right now.
20834   if (VT.getSimpleVT().getSizeInBits() == 64)
20835     return false;
20836
20837   // We only care that the types being shuffled are legal. The lowering can
20838   // handle any possible shuffle mask that results.
20839   return isTypeLegal(VT.getSimpleVT());
20840 }
20841
20842 bool
20843 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20844                                           EVT VT) const {
20845   // Just delegate to the generic legality, clear masks aren't special.
20846   return isShuffleMaskLegal(Mask, VT);
20847 }
20848
20849 //===----------------------------------------------------------------------===//
20850 //                           X86 Scheduler Hooks
20851 //===----------------------------------------------------------------------===//
20852
20853 /// Utility function to emit xbegin specifying the start of an RTM region.
20854 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20855                                      const TargetInstrInfo *TII) {
20856   DebugLoc DL = MI->getDebugLoc();
20857
20858   const BasicBlock *BB = MBB->getBasicBlock();
20859   MachineFunction::iterator I = ++MBB->getIterator();
20860
20861   // For the v = xbegin(), we generate
20862   //
20863   // thisMBB:
20864   //  xbegin sinkMBB
20865   //
20866   // mainMBB:
20867   //  eax = -1
20868   //
20869   // sinkMBB:
20870   //  v = eax
20871
20872   MachineBasicBlock *thisMBB = MBB;
20873   MachineFunction *MF = MBB->getParent();
20874   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20875   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20876   MF->insert(I, mainMBB);
20877   MF->insert(I, sinkMBB);
20878
20879   // Transfer the remainder of BB and its successor edges to sinkMBB.
20880   sinkMBB->splice(sinkMBB->begin(), MBB,
20881                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20882   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20883
20884   // thisMBB:
20885   //  xbegin sinkMBB
20886   //  # fallthrough to mainMBB
20887   //  # abortion to sinkMBB
20888   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20889   thisMBB->addSuccessor(mainMBB);
20890   thisMBB->addSuccessor(sinkMBB);
20891
20892   // mainMBB:
20893   //  EAX = -1
20894   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20895   mainMBB->addSuccessor(sinkMBB);
20896
20897   // sinkMBB:
20898   // EAX is live into the sinkMBB
20899   sinkMBB->addLiveIn(X86::EAX);
20900   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20901           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20902     .addReg(X86::EAX);
20903
20904   MI->eraseFromParent();
20905   return sinkMBB;
20906 }
20907
20908 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20909 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20910 // in the .td file.
20911 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20912                                        const TargetInstrInfo *TII) {
20913   unsigned Opc;
20914   switch (MI->getOpcode()) {
20915   default: llvm_unreachable("illegal opcode!");
20916   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20917   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20918   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20919   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20920   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20921   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20922   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20923   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20924   }
20925
20926   DebugLoc dl = MI->getDebugLoc();
20927   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20928
20929   unsigned NumArgs = MI->getNumOperands();
20930   for (unsigned i = 1; i < NumArgs; ++i) {
20931     MachineOperand &Op = MI->getOperand(i);
20932     if (!(Op.isReg() && Op.isImplicit()))
20933       MIB.addOperand(Op);
20934   }
20935   if (MI->hasOneMemOperand())
20936     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20937
20938   BuildMI(*BB, MI, dl,
20939     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20940     .addReg(X86::XMM0);
20941
20942   MI->eraseFromParent();
20943   return BB;
20944 }
20945
20946 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20947 // defs in an instruction pattern
20948 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20949                                        const TargetInstrInfo *TII) {
20950   unsigned Opc;
20951   switch (MI->getOpcode()) {
20952   default: llvm_unreachable("illegal opcode!");
20953   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20954   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20955   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20956   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20957   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20958   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20959   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20960   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20961   }
20962
20963   DebugLoc dl = MI->getDebugLoc();
20964   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20965
20966   unsigned NumArgs = MI->getNumOperands(); // remove the results
20967   for (unsigned i = 1; i < NumArgs; ++i) {
20968     MachineOperand &Op = MI->getOperand(i);
20969     if (!(Op.isReg() && Op.isImplicit()))
20970       MIB.addOperand(Op);
20971   }
20972   if (MI->hasOneMemOperand())
20973     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20974
20975   BuildMI(*BB, MI, dl,
20976     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20977     .addReg(X86::ECX);
20978
20979   MI->eraseFromParent();
20980   return BB;
20981 }
20982
20983 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20984                                       const X86Subtarget *Subtarget) {
20985   DebugLoc dl = MI->getDebugLoc();
20986   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20987   // Address into RAX/EAX, other two args into ECX, EDX.
20988   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20989   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20990   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20991   for (int i = 0; i < X86::AddrNumOperands; ++i)
20992     MIB.addOperand(MI->getOperand(i));
20993
20994   unsigned ValOps = X86::AddrNumOperands;
20995   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20996     .addReg(MI->getOperand(ValOps).getReg());
20997   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20998     .addReg(MI->getOperand(ValOps+1).getReg());
20999
21000   // The instruction doesn't actually take any operands though.
21001   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21002
21003   MI->eraseFromParent(); // The pseudo is gone now.
21004   return BB;
21005 }
21006
21007 MachineBasicBlock *
21008 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21009                                                  MachineBasicBlock *MBB) const {
21010   // Emit va_arg instruction on X86-64.
21011
21012   // Operands to this pseudo-instruction:
21013   // 0  ) Output        : destination address (reg)
21014   // 1-5) Input         : va_list address (addr, i64mem)
21015   // 6  ) ArgSize       : Size (in bytes) of vararg type
21016   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21017   // 8  ) Align         : Alignment of type
21018   // 9  ) EFLAGS (implicit-def)
21019
21020   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21021   static_assert(X86::AddrNumOperands == 5,
21022                 "VAARG_64 assumes 5 address operands");
21023
21024   unsigned DestReg = MI->getOperand(0).getReg();
21025   MachineOperand &Base = MI->getOperand(1);
21026   MachineOperand &Scale = MI->getOperand(2);
21027   MachineOperand &Index = MI->getOperand(3);
21028   MachineOperand &Disp = MI->getOperand(4);
21029   MachineOperand &Segment = MI->getOperand(5);
21030   unsigned ArgSize = MI->getOperand(6).getImm();
21031   unsigned ArgMode = MI->getOperand(7).getImm();
21032   unsigned Align = MI->getOperand(8).getImm();
21033
21034   // Memory Reference
21035   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21036   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21037   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21038
21039   // Machine Information
21040   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21041   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21042   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21043   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21044   DebugLoc DL = MI->getDebugLoc();
21045
21046   // struct va_list {
21047   //   i32   gp_offset
21048   //   i32   fp_offset
21049   //   i64   overflow_area (address)
21050   //   i64   reg_save_area (address)
21051   // }
21052   // sizeof(va_list) = 24
21053   // alignment(va_list) = 8
21054
21055   unsigned TotalNumIntRegs = 6;
21056   unsigned TotalNumXMMRegs = 8;
21057   bool UseGPOffset = (ArgMode == 1);
21058   bool UseFPOffset = (ArgMode == 2);
21059   unsigned MaxOffset = TotalNumIntRegs * 8 +
21060                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21061
21062   /* Align ArgSize to a multiple of 8 */
21063   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21064   bool NeedsAlign = (Align > 8);
21065
21066   MachineBasicBlock *thisMBB = MBB;
21067   MachineBasicBlock *overflowMBB;
21068   MachineBasicBlock *offsetMBB;
21069   MachineBasicBlock *endMBB;
21070
21071   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
21072   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
21073   unsigned OffsetReg = 0;
21074
21075   if (!UseGPOffset && !UseFPOffset) {
21076     // If we only pull from the overflow region, we don't create a branch.
21077     // We don't need to alter control flow.
21078     OffsetDestReg = 0; // unused
21079     OverflowDestReg = DestReg;
21080
21081     offsetMBB = nullptr;
21082     overflowMBB = thisMBB;
21083     endMBB = thisMBB;
21084   } else {
21085     // First emit code to check if gp_offset (or fp_offset) is below the bound.
21086     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21087     // If not, pull from overflow_area. (branch to overflowMBB)
21088     //
21089     //       thisMBB
21090     //         |     .
21091     //         |        .
21092     //     offsetMBB   overflowMBB
21093     //         |        .
21094     //         |     .
21095     //        endMBB
21096
21097     // Registers for the PHI in endMBB
21098     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21099     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21100
21101     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21102     MachineFunction *MF = MBB->getParent();
21103     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21104     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21105     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21106
21107     MachineFunction::iterator MBBIter = ++MBB->getIterator();
21108
21109     // Insert the new basic blocks
21110     MF->insert(MBBIter, offsetMBB);
21111     MF->insert(MBBIter, overflowMBB);
21112     MF->insert(MBBIter, endMBB);
21113
21114     // Transfer the remainder of MBB and its successor edges to endMBB.
21115     endMBB->splice(endMBB->begin(), thisMBB,
21116                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21117     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21118
21119     // Make offsetMBB and overflowMBB successors of thisMBB
21120     thisMBB->addSuccessor(offsetMBB);
21121     thisMBB->addSuccessor(overflowMBB);
21122
21123     // endMBB is a successor of both offsetMBB and overflowMBB
21124     offsetMBB->addSuccessor(endMBB);
21125     overflowMBB->addSuccessor(endMBB);
21126
21127     // Load the offset value into a register
21128     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21129     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21130       .addOperand(Base)
21131       .addOperand(Scale)
21132       .addOperand(Index)
21133       .addDisp(Disp, UseFPOffset ? 4 : 0)
21134       .addOperand(Segment)
21135       .setMemRefs(MMOBegin, MMOEnd);
21136
21137     // Check if there is enough room left to pull this argument.
21138     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21139       .addReg(OffsetReg)
21140       .addImm(MaxOffset + 8 - ArgSizeA8);
21141
21142     // Branch to "overflowMBB" if offset >= max
21143     // Fall through to "offsetMBB" otherwise
21144     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21145       .addMBB(overflowMBB);
21146   }
21147
21148   // In offsetMBB, emit code to use the reg_save_area.
21149   if (offsetMBB) {
21150     assert(OffsetReg != 0);
21151
21152     // Read the reg_save_area address.
21153     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21154     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21155       .addOperand(Base)
21156       .addOperand(Scale)
21157       .addOperand(Index)
21158       .addDisp(Disp, 16)
21159       .addOperand(Segment)
21160       .setMemRefs(MMOBegin, MMOEnd);
21161
21162     // Zero-extend the offset
21163     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21164       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21165         .addImm(0)
21166         .addReg(OffsetReg)
21167         .addImm(X86::sub_32bit);
21168
21169     // Add the offset to the reg_save_area to get the final address.
21170     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21171       .addReg(OffsetReg64)
21172       .addReg(RegSaveReg);
21173
21174     // Compute the offset for the next argument
21175     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21176     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21177       .addReg(OffsetReg)
21178       .addImm(UseFPOffset ? 16 : 8);
21179
21180     // Store it back into the va_list.
21181     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21182       .addOperand(Base)
21183       .addOperand(Scale)
21184       .addOperand(Index)
21185       .addDisp(Disp, UseFPOffset ? 4 : 0)
21186       .addOperand(Segment)
21187       .addReg(NextOffsetReg)
21188       .setMemRefs(MMOBegin, MMOEnd);
21189
21190     // Jump to endMBB
21191     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21192       .addMBB(endMBB);
21193   }
21194
21195   //
21196   // Emit code to use overflow area
21197   //
21198
21199   // Load the overflow_area address into a register.
21200   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21201   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21202     .addOperand(Base)
21203     .addOperand(Scale)
21204     .addOperand(Index)
21205     .addDisp(Disp, 8)
21206     .addOperand(Segment)
21207     .setMemRefs(MMOBegin, MMOEnd);
21208
21209   // If we need to align it, do so. Otherwise, just copy the address
21210   // to OverflowDestReg.
21211   if (NeedsAlign) {
21212     // Align the overflow address
21213     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21214     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21215
21216     // aligned_addr = (addr + (align-1)) & ~(align-1)
21217     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21218       .addReg(OverflowAddrReg)
21219       .addImm(Align-1);
21220
21221     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21222       .addReg(TmpReg)
21223       .addImm(~(uint64_t)(Align-1));
21224   } else {
21225     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21226       .addReg(OverflowAddrReg);
21227   }
21228
21229   // Compute the next overflow address after this argument.
21230   // (the overflow address should be kept 8-byte aligned)
21231   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21232   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21233     .addReg(OverflowDestReg)
21234     .addImm(ArgSizeA8);
21235
21236   // Store the new overflow address.
21237   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21238     .addOperand(Base)
21239     .addOperand(Scale)
21240     .addOperand(Index)
21241     .addDisp(Disp, 8)
21242     .addOperand(Segment)
21243     .addReg(NextAddrReg)
21244     .setMemRefs(MMOBegin, MMOEnd);
21245
21246   // If we branched, emit the PHI to the front of endMBB.
21247   if (offsetMBB) {
21248     BuildMI(*endMBB, endMBB->begin(), DL,
21249             TII->get(X86::PHI), DestReg)
21250       .addReg(OffsetDestReg).addMBB(offsetMBB)
21251       .addReg(OverflowDestReg).addMBB(overflowMBB);
21252   }
21253
21254   // Erase the pseudo instruction
21255   MI->eraseFromParent();
21256
21257   return endMBB;
21258 }
21259
21260 MachineBasicBlock *
21261 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21262                                                  MachineInstr *MI,
21263                                                  MachineBasicBlock *MBB) const {
21264   // Emit code to save XMM registers to the stack. The ABI says that the
21265   // number of registers to save is given in %al, so it's theoretically
21266   // possible to do an indirect jump trick to avoid saving all of them,
21267   // however this code takes a simpler approach and just executes all
21268   // of the stores if %al is non-zero. It's less code, and it's probably
21269   // easier on the hardware branch predictor, and stores aren't all that
21270   // expensive anyway.
21271
21272   // Create the new basic blocks. One block contains all the XMM stores,
21273   // and one block is the final destination regardless of whether any
21274   // stores were performed.
21275   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21276   MachineFunction *F = MBB->getParent();
21277   MachineFunction::iterator MBBIter = ++MBB->getIterator();
21278   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21279   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21280   F->insert(MBBIter, XMMSaveMBB);
21281   F->insert(MBBIter, EndMBB);
21282
21283   // Transfer the remainder of MBB and its successor edges to EndMBB.
21284   EndMBB->splice(EndMBB->begin(), MBB,
21285                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21286   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21287
21288   // The original block will now fall through to the XMM save block.
21289   MBB->addSuccessor(XMMSaveMBB);
21290   // The XMMSaveMBB will fall through to the end block.
21291   XMMSaveMBB->addSuccessor(EndMBB);
21292
21293   // Now add the instructions.
21294   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21295   DebugLoc DL = MI->getDebugLoc();
21296
21297   unsigned CountReg = MI->getOperand(0).getReg();
21298   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21299   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21300
21301   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21302     // If %al is 0, branch around the XMM save block.
21303     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21304     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21305     MBB->addSuccessor(EndMBB);
21306   }
21307
21308   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21309   // that was just emitted, but clearly shouldn't be "saved".
21310   assert((MI->getNumOperands() <= 3 ||
21311           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21312           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21313          && "Expected last argument to be EFLAGS");
21314   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21315   // In the XMM save block, save all the XMM argument registers.
21316   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21317     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21318     MachineMemOperand *MMO = F->getMachineMemOperand(
21319         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21320         MachineMemOperand::MOStore,
21321         /*Size=*/16, /*Align=*/16);
21322     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21323       .addFrameIndex(RegSaveFrameIndex)
21324       .addImm(/*Scale=*/1)
21325       .addReg(/*IndexReg=*/0)
21326       .addImm(/*Disp=*/Offset)
21327       .addReg(/*Segment=*/0)
21328       .addReg(MI->getOperand(i).getReg())
21329       .addMemOperand(MMO);
21330   }
21331
21332   MI->eraseFromParent();   // The pseudo instruction is gone now.
21333
21334   return EndMBB;
21335 }
21336
21337 // The EFLAGS operand of SelectItr might be missing a kill marker
21338 // because there were multiple uses of EFLAGS, and ISel didn't know
21339 // which to mark. Figure out whether SelectItr should have had a
21340 // kill marker, and set it if it should. Returns the correct kill
21341 // marker value.
21342 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21343                                      MachineBasicBlock* BB,
21344                                      const TargetRegisterInfo* TRI) {
21345   // Scan forward through BB for a use/def of EFLAGS.
21346   MachineBasicBlock::iterator miI(std::next(SelectItr));
21347   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21348     const MachineInstr& mi = *miI;
21349     if (mi.readsRegister(X86::EFLAGS))
21350       return false;
21351     if (mi.definesRegister(X86::EFLAGS))
21352       break; // Should have kill-flag - update below.
21353   }
21354
21355   // If we hit the end of the block, check whether EFLAGS is live into a
21356   // successor.
21357   if (miI == BB->end()) {
21358     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21359                                           sEnd = BB->succ_end();
21360          sItr != sEnd; ++sItr) {
21361       MachineBasicBlock* succ = *sItr;
21362       if (succ->isLiveIn(X86::EFLAGS))
21363         return false;
21364     }
21365   }
21366
21367   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21368   // out. SelectMI should have a kill flag on EFLAGS.
21369   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21370   return true;
21371 }
21372
21373 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21374 // together with other CMOV pseudo-opcodes into a single basic-block with
21375 // conditional jump around it.
21376 static bool isCMOVPseudo(MachineInstr *MI) {
21377   switch (MI->getOpcode()) {
21378   case X86::CMOV_FR32:
21379   case X86::CMOV_FR64:
21380   case X86::CMOV_GR8:
21381   case X86::CMOV_GR16:
21382   case X86::CMOV_GR32:
21383   case X86::CMOV_RFP32:
21384   case X86::CMOV_RFP64:
21385   case X86::CMOV_RFP80:
21386   case X86::CMOV_V2F64:
21387   case X86::CMOV_V2I64:
21388   case X86::CMOV_V4F32:
21389   case X86::CMOV_V4F64:
21390   case X86::CMOV_V4I64:
21391   case X86::CMOV_V16F32:
21392   case X86::CMOV_V8F32:
21393   case X86::CMOV_V8F64:
21394   case X86::CMOV_V8I64:
21395   case X86::CMOV_V8I1:
21396   case X86::CMOV_V16I1:
21397   case X86::CMOV_V32I1:
21398   case X86::CMOV_V64I1:
21399     return true;
21400
21401   default:
21402     return false;
21403   }
21404 }
21405
21406 MachineBasicBlock *
21407 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21408                                      MachineBasicBlock *BB) const {
21409   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21410   DebugLoc DL = MI->getDebugLoc();
21411
21412   // To "insert" a SELECT_CC instruction, we actually have to insert the
21413   // diamond control-flow pattern.  The incoming instruction knows the
21414   // destination vreg to set, the condition code register to branch on, the
21415   // true/false values to select between, and a branch opcode to use.
21416   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21417   MachineFunction::iterator It = ++BB->getIterator();
21418
21419   //  thisMBB:
21420   //  ...
21421   //   TrueVal = ...
21422   //   cmpTY ccX, r1, r2
21423   //   bCC copy1MBB
21424   //   fallthrough --> copy0MBB
21425   MachineBasicBlock *thisMBB = BB;
21426   MachineFunction *F = BB->getParent();
21427
21428   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21429   // as described above, by inserting a BB, and then making a PHI at the join
21430   // point to select the true and false operands of the CMOV in the PHI.
21431   //
21432   // The code also handles two different cases of multiple CMOV opcodes
21433   // in a row.
21434   //
21435   // Case 1:
21436   // In this case, there are multiple CMOVs in a row, all which are based on
21437   // the same condition setting (or the exact opposite condition setting).
21438   // In this case we can lower all the CMOVs using a single inserted BB, and
21439   // then make a number of PHIs at the join point to model the CMOVs. The only
21440   // trickiness here, is that in a case like:
21441   //
21442   // t2 = CMOV cond1 t1, f1
21443   // t3 = CMOV cond1 t2, f2
21444   //
21445   // when rewriting this into PHIs, we have to perform some renaming on the
21446   // temps since you cannot have a PHI operand refer to a PHI result earlier
21447   // in the same block.  The "simple" but wrong lowering would be:
21448   //
21449   // t2 = PHI t1(BB1), f1(BB2)
21450   // t3 = PHI t2(BB1), f2(BB2)
21451   //
21452   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21453   // renaming is to note that on the path through BB1, t2 is really just a
21454   // copy of t1, and do that renaming, properly generating:
21455   //
21456   // t2 = PHI t1(BB1), f1(BB2)
21457   // t3 = PHI t1(BB1), f2(BB2)
21458   //
21459   // Case 2, we lower cascaded CMOVs such as
21460   //
21461   //   (CMOV (CMOV F, T, cc1), T, cc2)
21462   //
21463   // to two successives branches.  For that, we look for another CMOV as the
21464   // following instruction.
21465   //
21466   // Without this, we would add a PHI between the two jumps, which ends up
21467   // creating a few copies all around. For instance, for
21468   //
21469   //    (sitofp (zext (fcmp une)))
21470   //
21471   // we would generate:
21472   //
21473   //         ucomiss %xmm1, %xmm0
21474   //         movss  <1.0f>, %xmm0
21475   //         movaps  %xmm0, %xmm1
21476   //         jne     .LBB5_2
21477   //         xorps   %xmm1, %xmm1
21478   // .LBB5_2:
21479   //         jp      .LBB5_4
21480   //         movaps  %xmm1, %xmm0
21481   // .LBB5_4:
21482   //         retq
21483   //
21484   // because this custom-inserter would have generated:
21485   //
21486   //   A
21487   //   | \
21488   //   |  B
21489   //   | /
21490   //   C
21491   //   | \
21492   //   |  D
21493   //   | /
21494   //   E
21495   //
21496   // A: X = ...; Y = ...
21497   // B: empty
21498   // C: Z = PHI [X, A], [Y, B]
21499   // D: empty
21500   // E: PHI [X, C], [Z, D]
21501   //
21502   // If we lower both CMOVs in a single step, we can instead generate:
21503   //
21504   //   A
21505   //   | \
21506   //   |  C
21507   //   | /|
21508   //   |/ |
21509   //   |  |
21510   //   |  D
21511   //   | /
21512   //   E
21513   //
21514   // A: X = ...; Y = ...
21515   // D: empty
21516   // E: PHI [X, A], [X, C], [Y, D]
21517   //
21518   // Which, in our sitofp/fcmp example, gives us something like:
21519   //
21520   //         ucomiss %xmm1, %xmm0
21521   //         movss  <1.0f>, %xmm0
21522   //         jne     .LBB5_4
21523   //         jp      .LBB5_4
21524   //         xorps   %xmm0, %xmm0
21525   // .LBB5_4:
21526   //         retq
21527   //
21528   MachineInstr *CascadedCMOV = nullptr;
21529   MachineInstr *LastCMOV = MI;
21530   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21531   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21532   MachineBasicBlock::iterator NextMIIt =
21533       std::next(MachineBasicBlock::iterator(MI));
21534
21535   // Check for case 1, where there are multiple CMOVs with the same condition
21536   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21537   // number of jumps the most.
21538
21539   if (isCMOVPseudo(MI)) {
21540     // See if we have a string of CMOVS with the same condition.
21541     while (NextMIIt != BB->end() &&
21542            isCMOVPseudo(NextMIIt) &&
21543            (NextMIIt->getOperand(3).getImm() == CC ||
21544             NextMIIt->getOperand(3).getImm() == OppCC)) {
21545       LastCMOV = &*NextMIIt;
21546       ++NextMIIt;
21547     }
21548   }
21549
21550   // This checks for case 2, but only do this if we didn't already find
21551   // case 1, as indicated by LastCMOV == MI.
21552   if (LastCMOV == MI &&
21553       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21554       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21555       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21556     CascadedCMOV = &*NextMIIt;
21557   }
21558
21559   MachineBasicBlock *jcc1MBB = nullptr;
21560
21561   // If we have a cascaded CMOV, we lower it to two successive branches to
21562   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21563   if (CascadedCMOV) {
21564     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21565     F->insert(It, jcc1MBB);
21566     jcc1MBB->addLiveIn(X86::EFLAGS);
21567   }
21568
21569   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21570   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21571   F->insert(It, copy0MBB);
21572   F->insert(It, sinkMBB);
21573
21574   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21575   // live into the sink and copy blocks.
21576   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21577
21578   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21579   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21580       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21581     copy0MBB->addLiveIn(X86::EFLAGS);
21582     sinkMBB->addLiveIn(X86::EFLAGS);
21583   }
21584
21585   // Transfer the remainder of BB and its successor edges to sinkMBB.
21586   sinkMBB->splice(sinkMBB->begin(), BB,
21587                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21588   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21589
21590   // Add the true and fallthrough blocks as its successors.
21591   if (CascadedCMOV) {
21592     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21593     BB->addSuccessor(jcc1MBB);
21594
21595     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21596     // jump to the sinkMBB.
21597     jcc1MBB->addSuccessor(copy0MBB);
21598     jcc1MBB->addSuccessor(sinkMBB);
21599   } else {
21600     BB->addSuccessor(copy0MBB);
21601   }
21602
21603   // The true block target of the first (or only) branch is always sinkMBB.
21604   BB->addSuccessor(sinkMBB);
21605
21606   // Create the conditional branch instruction.
21607   unsigned Opc = X86::GetCondBranchFromCond(CC);
21608   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21609
21610   if (CascadedCMOV) {
21611     unsigned Opc2 = X86::GetCondBranchFromCond(
21612         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21613     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21614   }
21615
21616   //  copy0MBB:
21617   //   %FalseValue = ...
21618   //   # fallthrough to sinkMBB
21619   copy0MBB->addSuccessor(sinkMBB);
21620
21621   //  sinkMBB:
21622   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21623   //  ...
21624   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21625   MachineBasicBlock::iterator MIItEnd =
21626     std::next(MachineBasicBlock::iterator(LastCMOV));
21627   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21628   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21629   MachineInstrBuilder MIB;
21630
21631   // As we are creating the PHIs, we have to be careful if there is more than
21632   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21633   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21634   // That also means that PHI construction must work forward from earlier to
21635   // later, and that the code must maintain a mapping from earlier PHI's
21636   // destination registers, and the registers that went into the PHI.
21637
21638   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21639     unsigned DestReg = MIIt->getOperand(0).getReg();
21640     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21641     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21642
21643     // If this CMOV we are generating is the opposite condition from
21644     // the jump we generated, then we have to swap the operands for the
21645     // PHI that is going to be generated.
21646     if (MIIt->getOperand(3).getImm() == OppCC)
21647         std::swap(Op1Reg, Op2Reg);
21648
21649     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21650       Op1Reg = RegRewriteTable[Op1Reg].first;
21651
21652     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21653       Op2Reg = RegRewriteTable[Op2Reg].second;
21654
21655     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21656                   TII->get(X86::PHI), DestReg)
21657           .addReg(Op1Reg).addMBB(copy0MBB)
21658           .addReg(Op2Reg).addMBB(thisMBB);
21659
21660     // Add this PHI to the rewrite table.
21661     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21662   }
21663
21664   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21665   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21666   if (CascadedCMOV) {
21667     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21668     // Copy the PHI result to the register defined by the second CMOV.
21669     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21670             DL, TII->get(TargetOpcode::COPY),
21671             CascadedCMOV->getOperand(0).getReg())
21672         .addReg(MI->getOperand(0).getReg());
21673     CascadedCMOV->eraseFromParent();
21674   }
21675
21676   // Now remove the CMOV(s).
21677   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21678     (MIIt++)->eraseFromParent();
21679
21680   return sinkMBB;
21681 }
21682
21683 MachineBasicBlock *
21684 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21685                                        MachineBasicBlock *BB) const {
21686   // Combine the following atomic floating-point modification pattern:
21687   //   a.store(reg OP a.load(acquire), release)
21688   // Transform them into:
21689   //   OPss (%gpr), %xmm
21690   //   movss %xmm, (%gpr)
21691   // Or sd equivalent for 64-bit operations.
21692   unsigned MOp, FOp;
21693   switch (MI->getOpcode()) {
21694   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21695   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21696   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21697   }
21698   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21699   DebugLoc DL = MI->getDebugLoc();
21700   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21701   MachineOperand MSrc = MI->getOperand(0);
21702   unsigned VSrc = MI->getOperand(5).getReg();
21703   const MachineOperand &Disp = MI->getOperand(3);
21704   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21705   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21706   if (hasDisp && MSrc.isReg())
21707     MSrc.setIsKill(false);
21708   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21709                                 .addOperand(/*Base=*/MSrc)
21710                                 .addImm(/*Scale=*/1)
21711                                 .addReg(/*Index=*/0)
21712                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21713                                 .addReg(0);
21714   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21715                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21716                           .addReg(VSrc)
21717                           .addOperand(/*Base=*/MSrc)
21718                           .addImm(/*Scale=*/1)
21719                           .addReg(/*Index=*/0)
21720                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21721                           .addReg(/*Segment=*/0);
21722   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21723   MI->eraseFromParent(); // The pseudo instruction is gone now.
21724   return BB;
21725 }
21726
21727 MachineBasicBlock *
21728 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21729                                         MachineBasicBlock *BB) const {
21730   MachineFunction *MF = BB->getParent();
21731   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21732   DebugLoc DL = MI->getDebugLoc();
21733   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21734
21735   assert(MF->shouldSplitStack());
21736
21737   const bool Is64Bit = Subtarget->is64Bit();
21738   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21739
21740   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21741   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21742
21743   // BB:
21744   //  ... [Till the alloca]
21745   // If stacklet is not large enough, jump to mallocMBB
21746   //
21747   // bumpMBB:
21748   //  Allocate by subtracting from RSP
21749   //  Jump to continueMBB
21750   //
21751   // mallocMBB:
21752   //  Allocate by call to runtime
21753   //
21754   // continueMBB:
21755   //  ...
21756   //  [rest of original BB]
21757   //
21758
21759   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21760   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21761   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21762
21763   MachineRegisterInfo &MRI = MF->getRegInfo();
21764   const TargetRegisterClass *AddrRegClass =
21765       getRegClassFor(getPointerTy(MF->getDataLayout()));
21766
21767   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21768     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21769     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21770     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21771     sizeVReg = MI->getOperand(1).getReg(),
21772     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21773
21774   MachineFunction::iterator MBBIter = ++BB->getIterator();
21775
21776   MF->insert(MBBIter, bumpMBB);
21777   MF->insert(MBBIter, mallocMBB);
21778   MF->insert(MBBIter, continueMBB);
21779
21780   continueMBB->splice(continueMBB->begin(), BB,
21781                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21782   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21783
21784   // Add code to the main basic block to check if the stack limit has been hit,
21785   // and if so, jump to mallocMBB otherwise to bumpMBB.
21786   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21787   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21788     .addReg(tmpSPVReg).addReg(sizeVReg);
21789   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21790     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21791     .addReg(SPLimitVReg);
21792   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21793
21794   // bumpMBB simply decreases the stack pointer, since we know the current
21795   // stacklet has enough space.
21796   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21797     .addReg(SPLimitVReg);
21798   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21799     .addReg(SPLimitVReg);
21800   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21801
21802   // Calls into a routine in libgcc to allocate more space from the heap.
21803   const uint32_t *RegMask =
21804       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21805   if (IsLP64) {
21806     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21807       .addReg(sizeVReg);
21808     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21809       .addExternalSymbol("__morestack_allocate_stack_space")
21810       .addRegMask(RegMask)
21811       .addReg(X86::RDI, RegState::Implicit)
21812       .addReg(X86::RAX, RegState::ImplicitDefine);
21813   } else if (Is64Bit) {
21814     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21815       .addReg(sizeVReg);
21816     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21817       .addExternalSymbol("__morestack_allocate_stack_space")
21818       .addRegMask(RegMask)
21819       .addReg(X86::EDI, RegState::Implicit)
21820       .addReg(X86::EAX, RegState::ImplicitDefine);
21821   } else {
21822     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21823       .addImm(12);
21824     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21825     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21826       .addExternalSymbol("__morestack_allocate_stack_space")
21827       .addRegMask(RegMask)
21828       .addReg(X86::EAX, RegState::ImplicitDefine);
21829   }
21830
21831   if (!Is64Bit)
21832     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21833       .addImm(16);
21834
21835   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21836     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21837   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21838
21839   // Set up the CFG correctly.
21840   BB->addSuccessor(bumpMBB);
21841   BB->addSuccessor(mallocMBB);
21842   mallocMBB->addSuccessor(continueMBB);
21843   bumpMBB->addSuccessor(continueMBB);
21844
21845   // Take care of the PHI nodes.
21846   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21847           MI->getOperand(0).getReg())
21848     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21849     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21850
21851   // Delete the original pseudo instruction.
21852   MI->eraseFromParent();
21853
21854   // And we're done.
21855   return continueMBB;
21856 }
21857
21858 MachineBasicBlock *
21859 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21860                                         MachineBasicBlock *BB) const {
21861   assert(!Subtarget->isTargetMachO());
21862   DebugLoc DL = MI->getDebugLoc();
21863   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
21864       *BB->getParent(), *BB, MI, DL, false);
21865   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
21866   MI->eraseFromParent(); // The pseudo instruction is gone now.
21867   return ResumeBB;
21868 }
21869
21870 MachineBasicBlock *
21871 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
21872                                        MachineBasicBlock *BB) const {
21873   MachineFunction *MF = BB->getParent();
21874   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21875   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
21876   DebugLoc DL = MI->getDebugLoc();
21877
21878   assert(!isAsynchronousEHPersonality(
21879              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
21880          "SEH does not use catchret!");
21881
21882   // Only 32-bit EH needs to worry about manually restoring stack pointers.
21883   if (!Subtarget->is32Bit())
21884     return BB;
21885
21886   // C++ EH creates a new target block to hold the restore code, and wires up
21887   // the new block to the return destination with a normal JMP_4.
21888   MachineBasicBlock *RestoreMBB =
21889       MF->CreateMachineBasicBlock(BB->getBasicBlock());
21890   assert(BB->succ_size() == 1);
21891   MF->insert(std::next(BB->getIterator()), RestoreMBB);
21892   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
21893   BB->addSuccessor(RestoreMBB);
21894   MI->getOperand(0).setMBB(RestoreMBB);
21895
21896   auto RestoreMBBI = RestoreMBB->begin();
21897   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
21898   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
21899   return BB;
21900 }
21901
21902 MachineBasicBlock *
21903 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
21904                                        MachineBasicBlock *BB) const {
21905   MachineFunction *MF = BB->getParent();
21906   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
21907   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
21908   // Only 32-bit SEH requires special handling for catchpad.
21909   if (IsSEH && Subtarget->is32Bit()) {
21910     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21911     DebugLoc DL = MI->getDebugLoc();
21912     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
21913   }
21914   MI->eraseFromParent();
21915   return BB;
21916 }
21917
21918 MachineBasicBlock *
21919 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21920                                       MachineBasicBlock *BB) const {
21921   // This is pretty easy.  We're taking the value that we received from
21922   // our load from the relocation, sticking it in either RDI (x86-64)
21923   // or EAX and doing an indirect call.  The return value will then
21924   // be in the normal return register.
21925   MachineFunction *F = BB->getParent();
21926   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21927   DebugLoc DL = MI->getDebugLoc();
21928
21929   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21930   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21931
21932   // Get a register mask for the lowered call.
21933   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21934   // proper register mask.
21935   const uint32_t *RegMask =
21936       Subtarget->is64Bit() ?
21937       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
21938       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21939   if (Subtarget->is64Bit()) {
21940     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21941                                       TII->get(X86::MOV64rm), X86::RDI)
21942     .addReg(X86::RIP)
21943     .addImm(0).addReg(0)
21944     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21945                       MI->getOperand(3).getTargetFlags())
21946     .addReg(0);
21947     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21948     addDirectMem(MIB, X86::RDI);
21949     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21950   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21951     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21952                                       TII->get(X86::MOV32rm), X86::EAX)
21953     .addReg(0)
21954     .addImm(0).addReg(0)
21955     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21956                       MI->getOperand(3).getTargetFlags())
21957     .addReg(0);
21958     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21959     addDirectMem(MIB, X86::EAX);
21960     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21961   } else {
21962     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21963                                       TII->get(X86::MOV32rm), X86::EAX)
21964     .addReg(TII->getGlobalBaseReg(F))
21965     .addImm(0).addReg(0)
21966     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21967                       MI->getOperand(3).getTargetFlags())
21968     .addReg(0);
21969     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21970     addDirectMem(MIB, X86::EAX);
21971     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21972   }
21973
21974   MI->eraseFromParent(); // The pseudo instruction is gone now.
21975   return BB;
21976 }
21977
21978 MachineBasicBlock *
21979 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21980                                     MachineBasicBlock *MBB) const {
21981   DebugLoc DL = MI->getDebugLoc();
21982   MachineFunction *MF = MBB->getParent();
21983   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21984   MachineRegisterInfo &MRI = MF->getRegInfo();
21985
21986   const BasicBlock *BB = MBB->getBasicBlock();
21987   MachineFunction::iterator I = ++MBB->getIterator();
21988
21989   // Memory Reference
21990   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21991   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21992
21993   unsigned DstReg;
21994   unsigned MemOpndSlot = 0;
21995
21996   unsigned CurOp = 0;
21997
21998   DstReg = MI->getOperand(CurOp++).getReg();
21999   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22000   assert(RC->hasType(MVT::i32) && "Invalid destination!");
22001   unsigned mainDstReg = MRI.createVirtualRegister(RC);
22002   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22003
22004   MemOpndSlot = CurOp;
22005
22006   MVT PVT = getPointerTy(MF->getDataLayout());
22007   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22008          "Invalid Pointer Size!");
22009
22010   // For v = setjmp(buf), we generate
22011   //
22012   // thisMBB:
22013   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22014   //  SjLjSetup restoreMBB
22015   //
22016   // mainMBB:
22017   //  v_main = 0
22018   //
22019   // sinkMBB:
22020   //  v = phi(main, restore)
22021   //
22022   // restoreMBB:
22023   //  if base pointer being used, load it from frame
22024   //  v_restore = 1
22025
22026   MachineBasicBlock *thisMBB = MBB;
22027   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22028   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22029   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22030   MF->insert(I, mainMBB);
22031   MF->insert(I, sinkMBB);
22032   MF->push_back(restoreMBB);
22033   restoreMBB->setHasAddressTaken();
22034
22035   MachineInstrBuilder MIB;
22036
22037   // Transfer the remainder of BB and its successor edges to sinkMBB.
22038   sinkMBB->splice(sinkMBB->begin(), MBB,
22039                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22040   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22041
22042   // thisMBB:
22043   unsigned PtrStoreOpc = 0;
22044   unsigned LabelReg = 0;
22045   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22046   Reloc::Model RM = MF->getTarget().getRelocationModel();
22047   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22048                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22049
22050   // Prepare IP either in reg or imm.
22051   if (!UseImmLabel) {
22052     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22053     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22054     LabelReg = MRI.createVirtualRegister(PtrRC);
22055     if (Subtarget->is64Bit()) {
22056       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22057               .addReg(X86::RIP)
22058               .addImm(0)
22059               .addReg(0)
22060               .addMBB(restoreMBB)
22061               .addReg(0);
22062     } else {
22063       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22064       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22065               .addReg(XII->getGlobalBaseReg(MF))
22066               .addImm(0)
22067               .addReg(0)
22068               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22069               .addReg(0);
22070     }
22071   } else
22072     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22073   // Store IP
22074   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22075   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22076     if (i == X86::AddrDisp)
22077       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22078     else
22079       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22080   }
22081   if (!UseImmLabel)
22082     MIB.addReg(LabelReg);
22083   else
22084     MIB.addMBB(restoreMBB);
22085   MIB.setMemRefs(MMOBegin, MMOEnd);
22086   // Setup
22087   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22088           .addMBB(restoreMBB);
22089
22090   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22091   MIB.addRegMask(RegInfo->getNoPreservedMask());
22092   thisMBB->addSuccessor(mainMBB);
22093   thisMBB->addSuccessor(restoreMBB);
22094
22095   // mainMBB:
22096   //  EAX = 0
22097   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22098   mainMBB->addSuccessor(sinkMBB);
22099
22100   // sinkMBB:
22101   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22102           TII->get(X86::PHI), DstReg)
22103     .addReg(mainDstReg).addMBB(mainMBB)
22104     .addReg(restoreDstReg).addMBB(restoreMBB);
22105
22106   // restoreMBB:
22107   if (RegInfo->hasBasePointer(*MF)) {
22108     const bool Uses64BitFramePtr =
22109         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22110     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22111     X86FI->setRestoreBasePointer(MF);
22112     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22113     unsigned BasePtr = RegInfo->getBaseRegister();
22114     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22115     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22116                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
22117       .setMIFlag(MachineInstr::FrameSetup);
22118   }
22119   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22120   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22121   restoreMBB->addSuccessor(sinkMBB);
22122
22123   MI->eraseFromParent();
22124   return sinkMBB;
22125 }
22126
22127 MachineBasicBlock *
22128 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22129                                      MachineBasicBlock *MBB) const {
22130   DebugLoc DL = MI->getDebugLoc();
22131   MachineFunction *MF = MBB->getParent();
22132   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22133   MachineRegisterInfo &MRI = MF->getRegInfo();
22134
22135   // Memory Reference
22136   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22137   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22138
22139   MVT PVT = getPointerTy(MF->getDataLayout());
22140   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22141          "Invalid Pointer Size!");
22142
22143   const TargetRegisterClass *RC =
22144     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22145   unsigned Tmp = MRI.createVirtualRegister(RC);
22146   // Since FP is only updated here but NOT referenced, it's treated as GPR.
22147   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22148   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22149   unsigned SP = RegInfo->getStackRegister();
22150
22151   MachineInstrBuilder MIB;
22152
22153   const int64_t LabelOffset = 1 * PVT.getStoreSize();
22154   const int64_t SPOffset = 2 * PVT.getStoreSize();
22155
22156   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22157   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22158
22159   // Reload FP
22160   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22161   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22162     MIB.addOperand(MI->getOperand(i));
22163   MIB.setMemRefs(MMOBegin, MMOEnd);
22164   // Reload IP
22165   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22166   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22167     if (i == X86::AddrDisp)
22168       MIB.addDisp(MI->getOperand(i), LabelOffset);
22169     else
22170       MIB.addOperand(MI->getOperand(i));
22171   }
22172   MIB.setMemRefs(MMOBegin, MMOEnd);
22173   // Reload SP
22174   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22175   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22176     if (i == X86::AddrDisp)
22177       MIB.addDisp(MI->getOperand(i), SPOffset);
22178     else
22179       MIB.addOperand(MI->getOperand(i));
22180   }
22181   MIB.setMemRefs(MMOBegin, MMOEnd);
22182   // Jump
22183   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22184
22185   MI->eraseFromParent();
22186   return MBB;
22187 }
22188
22189 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22190 // accumulator loops. Writing back to the accumulator allows the coalescer
22191 // to remove extra copies in the loop.
22192 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
22193 MachineBasicBlock *
22194 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22195                                  MachineBasicBlock *MBB) const {
22196   MachineOperand &AddendOp = MI->getOperand(3);
22197
22198   // Bail out early if the addend isn't a register - we can't switch these.
22199   if (!AddendOp.isReg())
22200     return MBB;
22201
22202   MachineFunction &MF = *MBB->getParent();
22203   MachineRegisterInfo &MRI = MF.getRegInfo();
22204
22205   // Check whether the addend is defined by a PHI:
22206   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22207   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22208   if (!AddendDef.isPHI())
22209     return MBB;
22210
22211   // Look for the following pattern:
22212   // loop:
22213   //   %addend = phi [%entry, 0], [%loop, %result]
22214   //   ...
22215   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22216
22217   // Replace with:
22218   //   loop:
22219   //   %addend = phi [%entry, 0], [%loop, %result]
22220   //   ...
22221   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22222
22223   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22224     assert(AddendDef.getOperand(i).isReg());
22225     MachineOperand PHISrcOp = AddendDef.getOperand(i);
22226     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22227     if (&PHISrcInst == MI) {
22228       // Found a matching instruction.
22229       unsigned NewFMAOpc = 0;
22230       switch (MI->getOpcode()) {
22231         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22232         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22233         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22234         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22235         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22236         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22237         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22238         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22239         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22240         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22241         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22242         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22243         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22244         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22245         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22246         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22247         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22248         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22249         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22250         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22251
22252         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22253         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22254         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22255         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22256         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22257         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22258         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22259         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22260         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22261         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22262         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22263         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22264         default: llvm_unreachable("Unrecognized FMA variant.");
22265       }
22266
22267       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22268       MachineInstrBuilder MIB =
22269         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22270         .addOperand(MI->getOperand(0))
22271         .addOperand(MI->getOperand(3))
22272         .addOperand(MI->getOperand(2))
22273         .addOperand(MI->getOperand(1));
22274       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22275       MI->eraseFromParent();
22276     }
22277   }
22278
22279   return MBB;
22280 }
22281
22282 MachineBasicBlock *
22283 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22284                                                MachineBasicBlock *BB) const {
22285   switch (MI->getOpcode()) {
22286   default: llvm_unreachable("Unexpected instr type to insert");
22287   case X86::TAILJMPd64:
22288   case X86::TAILJMPr64:
22289   case X86::TAILJMPm64:
22290   case X86::TAILJMPd64_REX:
22291   case X86::TAILJMPr64_REX:
22292   case X86::TAILJMPm64_REX:
22293     llvm_unreachable("TAILJMP64 would not be touched here.");
22294   case X86::TCRETURNdi64:
22295   case X86::TCRETURNri64:
22296   case X86::TCRETURNmi64:
22297     return BB;
22298   case X86::WIN_ALLOCA:
22299     return EmitLoweredWinAlloca(MI, BB);
22300   case X86::CATCHRET:
22301     return EmitLoweredCatchRet(MI, BB);
22302   case X86::CATCHPAD:
22303     return EmitLoweredCatchPad(MI, BB);
22304   case X86::SEG_ALLOCA_32:
22305   case X86::SEG_ALLOCA_64:
22306     return EmitLoweredSegAlloca(MI, BB);
22307   case X86::TLSCall_32:
22308   case X86::TLSCall_64:
22309     return EmitLoweredTLSCall(MI, BB);
22310   case X86::CMOV_FR32:
22311   case X86::CMOV_FR64:
22312   case X86::CMOV_FR128:
22313   case X86::CMOV_GR8:
22314   case X86::CMOV_GR16:
22315   case X86::CMOV_GR32:
22316   case X86::CMOV_RFP32:
22317   case X86::CMOV_RFP64:
22318   case X86::CMOV_RFP80:
22319   case X86::CMOV_V2F64:
22320   case X86::CMOV_V2I64:
22321   case X86::CMOV_V4F32:
22322   case X86::CMOV_V4F64:
22323   case X86::CMOV_V4I64:
22324   case X86::CMOV_V16F32:
22325   case X86::CMOV_V8F32:
22326   case X86::CMOV_V8F64:
22327   case X86::CMOV_V8I64:
22328   case X86::CMOV_V8I1:
22329   case X86::CMOV_V16I1:
22330   case X86::CMOV_V32I1:
22331   case X86::CMOV_V64I1:
22332     return EmitLoweredSelect(MI, BB);
22333
22334   case X86::RELEASE_FADD32mr:
22335   case X86::RELEASE_FADD64mr:
22336     return EmitLoweredAtomicFP(MI, BB);
22337
22338   case X86::FP32_TO_INT16_IN_MEM:
22339   case X86::FP32_TO_INT32_IN_MEM:
22340   case X86::FP32_TO_INT64_IN_MEM:
22341   case X86::FP64_TO_INT16_IN_MEM:
22342   case X86::FP64_TO_INT32_IN_MEM:
22343   case X86::FP64_TO_INT64_IN_MEM:
22344   case X86::FP80_TO_INT16_IN_MEM:
22345   case X86::FP80_TO_INT32_IN_MEM:
22346   case X86::FP80_TO_INT64_IN_MEM: {
22347     MachineFunction *F = BB->getParent();
22348     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22349     DebugLoc DL = MI->getDebugLoc();
22350
22351     // Change the floating point control register to use "round towards zero"
22352     // mode when truncating to an integer value.
22353     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22354     addFrameReference(BuildMI(*BB, MI, DL,
22355                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22356
22357     // Load the old value of the high byte of the control word...
22358     unsigned OldCW =
22359       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22360     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22361                       CWFrameIdx);
22362
22363     // Set the high part to be round to zero...
22364     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22365       .addImm(0xC7F);
22366
22367     // Reload the modified control word now...
22368     addFrameReference(BuildMI(*BB, MI, DL,
22369                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22370
22371     // Restore the memory image of control word to original value
22372     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22373       .addReg(OldCW);
22374
22375     // Get the X86 opcode to use.
22376     unsigned Opc;
22377     switch (MI->getOpcode()) {
22378     default: llvm_unreachable("illegal opcode!");
22379     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22380     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22381     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22382     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22383     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22384     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22385     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22386     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22387     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22388     }
22389
22390     X86AddressMode AM;
22391     MachineOperand &Op = MI->getOperand(0);
22392     if (Op.isReg()) {
22393       AM.BaseType = X86AddressMode::RegBase;
22394       AM.Base.Reg = Op.getReg();
22395     } else {
22396       AM.BaseType = X86AddressMode::FrameIndexBase;
22397       AM.Base.FrameIndex = Op.getIndex();
22398     }
22399     Op = MI->getOperand(1);
22400     if (Op.isImm())
22401       AM.Scale = Op.getImm();
22402     Op = MI->getOperand(2);
22403     if (Op.isImm())
22404       AM.IndexReg = Op.getImm();
22405     Op = MI->getOperand(3);
22406     if (Op.isGlobal()) {
22407       AM.GV = Op.getGlobal();
22408     } else {
22409       AM.Disp = Op.getImm();
22410     }
22411     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22412                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22413
22414     // Reload the original control word now.
22415     addFrameReference(BuildMI(*BB, MI, DL,
22416                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22417
22418     MI->eraseFromParent();   // The pseudo instruction is gone now.
22419     return BB;
22420   }
22421     // String/text processing lowering.
22422   case X86::PCMPISTRM128REG:
22423   case X86::VPCMPISTRM128REG:
22424   case X86::PCMPISTRM128MEM:
22425   case X86::VPCMPISTRM128MEM:
22426   case X86::PCMPESTRM128REG:
22427   case X86::VPCMPESTRM128REG:
22428   case X86::PCMPESTRM128MEM:
22429   case X86::VPCMPESTRM128MEM:
22430     assert(Subtarget->hasSSE42() &&
22431            "Target must have SSE4.2 or AVX features enabled");
22432     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22433
22434   // String/text processing lowering.
22435   case X86::PCMPISTRIREG:
22436   case X86::VPCMPISTRIREG:
22437   case X86::PCMPISTRIMEM:
22438   case X86::VPCMPISTRIMEM:
22439   case X86::PCMPESTRIREG:
22440   case X86::VPCMPESTRIREG:
22441   case X86::PCMPESTRIMEM:
22442   case X86::VPCMPESTRIMEM:
22443     assert(Subtarget->hasSSE42() &&
22444            "Target must have SSE4.2 or AVX features enabled");
22445     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22446
22447   // Thread synchronization.
22448   case X86::MONITOR:
22449     return EmitMonitor(MI, BB, Subtarget);
22450
22451   // xbegin
22452   case X86::XBEGIN:
22453     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22454
22455   case X86::VASTART_SAVE_XMM_REGS:
22456     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22457
22458   case X86::VAARG_64:
22459     return EmitVAARG64WithCustomInserter(MI, BB);
22460
22461   case X86::EH_SjLj_SetJmp32:
22462   case X86::EH_SjLj_SetJmp64:
22463     return emitEHSjLjSetJmp(MI, BB);
22464
22465   case X86::EH_SjLj_LongJmp32:
22466   case X86::EH_SjLj_LongJmp64:
22467     return emitEHSjLjLongJmp(MI, BB);
22468
22469   case TargetOpcode::STATEPOINT:
22470     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22471     // this point in the process.  We diverge later.
22472     return emitPatchPoint(MI, BB);
22473
22474   case TargetOpcode::STACKMAP:
22475   case TargetOpcode::PATCHPOINT:
22476     return emitPatchPoint(MI, BB);
22477
22478   case X86::VFMADDPDr213r:
22479   case X86::VFMADDPSr213r:
22480   case X86::VFMADDSDr213r:
22481   case X86::VFMADDSSr213r:
22482   case X86::VFMSUBPDr213r:
22483   case X86::VFMSUBPSr213r:
22484   case X86::VFMSUBSDr213r:
22485   case X86::VFMSUBSSr213r:
22486   case X86::VFNMADDPDr213r:
22487   case X86::VFNMADDPSr213r:
22488   case X86::VFNMADDSDr213r:
22489   case X86::VFNMADDSSr213r:
22490   case X86::VFNMSUBPDr213r:
22491   case X86::VFNMSUBPSr213r:
22492   case X86::VFNMSUBSDr213r:
22493   case X86::VFNMSUBSSr213r:
22494   case X86::VFMADDSUBPDr213r:
22495   case X86::VFMADDSUBPSr213r:
22496   case X86::VFMSUBADDPDr213r:
22497   case X86::VFMSUBADDPSr213r:
22498   case X86::VFMADDPDr213rY:
22499   case X86::VFMADDPSr213rY:
22500   case X86::VFMSUBPDr213rY:
22501   case X86::VFMSUBPSr213rY:
22502   case X86::VFNMADDPDr213rY:
22503   case X86::VFNMADDPSr213rY:
22504   case X86::VFNMSUBPDr213rY:
22505   case X86::VFNMSUBPSr213rY:
22506   case X86::VFMADDSUBPDr213rY:
22507   case X86::VFMADDSUBPSr213rY:
22508   case X86::VFMSUBADDPDr213rY:
22509   case X86::VFMSUBADDPSr213rY:
22510     return emitFMA3Instr(MI, BB);
22511   }
22512 }
22513
22514 //===----------------------------------------------------------------------===//
22515 //                           X86 Optimization Hooks
22516 //===----------------------------------------------------------------------===//
22517
22518 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22519                                                       APInt &KnownZero,
22520                                                       APInt &KnownOne,
22521                                                       const SelectionDAG &DAG,
22522                                                       unsigned Depth) const {
22523   unsigned BitWidth = KnownZero.getBitWidth();
22524   unsigned Opc = Op.getOpcode();
22525   assert((Opc >= ISD::BUILTIN_OP_END ||
22526           Opc == ISD::INTRINSIC_WO_CHAIN ||
22527           Opc == ISD::INTRINSIC_W_CHAIN ||
22528           Opc == ISD::INTRINSIC_VOID) &&
22529          "Should use MaskedValueIsZero if you don't know whether Op"
22530          " is a target node!");
22531
22532   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22533   switch (Opc) {
22534   default: break;
22535   case X86ISD::ADD:
22536   case X86ISD::SUB:
22537   case X86ISD::ADC:
22538   case X86ISD::SBB:
22539   case X86ISD::SMUL:
22540   case X86ISD::UMUL:
22541   case X86ISD::INC:
22542   case X86ISD::DEC:
22543   case X86ISD::OR:
22544   case X86ISD::XOR:
22545   case X86ISD::AND:
22546     // These nodes' second result is a boolean.
22547     if (Op.getResNo() == 0)
22548       break;
22549     // Fallthrough
22550   case X86ISD::SETCC:
22551     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22552     break;
22553   case ISD::INTRINSIC_WO_CHAIN: {
22554     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22555     unsigned NumLoBits = 0;
22556     switch (IntId) {
22557     default: break;
22558     case Intrinsic::x86_sse_movmsk_ps:
22559     case Intrinsic::x86_avx_movmsk_ps_256:
22560     case Intrinsic::x86_sse2_movmsk_pd:
22561     case Intrinsic::x86_avx_movmsk_pd_256:
22562     case Intrinsic::x86_mmx_pmovmskb:
22563     case Intrinsic::x86_sse2_pmovmskb_128:
22564     case Intrinsic::x86_avx2_pmovmskb: {
22565       // High bits of movmskp{s|d}, pmovmskb are known zero.
22566       switch (IntId) {
22567         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22568         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22569         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22570         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22571         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22572         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22573         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22574         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22575       }
22576       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22577       break;
22578     }
22579     }
22580     break;
22581   }
22582   }
22583 }
22584
22585 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22586   SDValue Op,
22587   const SelectionDAG &,
22588   unsigned Depth) const {
22589   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22590   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22591     return Op.getValueType().getScalarSizeInBits();
22592
22593   // Fallback case.
22594   return 1;
22595 }
22596
22597 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22598 /// node is a GlobalAddress + offset.
22599 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22600                                        const GlobalValue* &GA,
22601                                        int64_t &Offset) const {
22602   if (N->getOpcode() == X86ISD::Wrapper) {
22603     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22604       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22605       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22606       return true;
22607     }
22608   }
22609   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22610 }
22611
22612 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22613 /// same as extracting the high 128-bit part of 256-bit vector and then
22614 /// inserting the result into the low part of a new 256-bit vector
22615 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22616   EVT VT = SVOp->getValueType(0);
22617   unsigned NumElems = VT.getVectorNumElements();
22618
22619   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22620   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22621     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22622         SVOp->getMaskElt(j) >= 0)
22623       return false;
22624
22625   return true;
22626 }
22627
22628 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22629 /// same as extracting the low 128-bit part of 256-bit vector and then
22630 /// inserting the result into the high part of a new 256-bit vector
22631 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22632   EVT VT = SVOp->getValueType(0);
22633   unsigned NumElems = VT.getVectorNumElements();
22634
22635   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22636   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22637     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22638         SVOp->getMaskElt(j) >= 0)
22639       return false;
22640
22641   return true;
22642 }
22643
22644 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22645 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22646                                         TargetLowering::DAGCombinerInfo &DCI,
22647                                         const X86Subtarget* Subtarget) {
22648   SDLoc dl(N);
22649   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22650   SDValue V1 = SVOp->getOperand(0);
22651   SDValue V2 = SVOp->getOperand(1);
22652   MVT VT = SVOp->getSimpleValueType(0);
22653   unsigned NumElems = VT.getVectorNumElements();
22654
22655   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22656       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22657     //
22658     //                   0,0,0,...
22659     //                      |
22660     //    V      UNDEF    BUILD_VECTOR    UNDEF
22661     //     \      /           \           /
22662     //  CONCAT_VECTOR         CONCAT_VECTOR
22663     //         \                  /
22664     //          \                /
22665     //          RESULT: V + zero extended
22666     //
22667     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22668         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22669         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22670       return SDValue();
22671
22672     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22673       return SDValue();
22674
22675     // To match the shuffle mask, the first half of the mask should
22676     // be exactly the first vector, and all the rest a splat with the
22677     // first element of the second one.
22678     for (unsigned i = 0; i != NumElems/2; ++i)
22679       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22680           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22681         return SDValue();
22682
22683     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22684     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22685       if (Ld->hasNUsesOfValue(1, 0)) {
22686         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22687         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22688         SDValue ResNode =
22689           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22690                                   Ld->getMemoryVT(),
22691                                   Ld->getPointerInfo(),
22692                                   Ld->getAlignment(),
22693                                   false/*isVolatile*/, true/*ReadMem*/,
22694                                   false/*WriteMem*/);
22695
22696         // Make sure the newly-created LOAD is in the same position as Ld in
22697         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22698         // and update uses of Ld's output chain to use the TokenFactor.
22699         if (Ld->hasAnyUseOfValue(1)) {
22700           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22701                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22702           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22703           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22704                                  SDValue(ResNode.getNode(), 1));
22705         }
22706
22707         return DAG.getBitcast(VT, ResNode);
22708       }
22709     }
22710
22711     // Emit a zeroed vector and insert the desired subvector on its
22712     // first half.
22713     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22714     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22715     return DCI.CombineTo(N, InsV);
22716   }
22717
22718   //===--------------------------------------------------------------------===//
22719   // Combine some shuffles into subvector extracts and inserts:
22720   //
22721
22722   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22723   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22724     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22725     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22726     return DCI.CombineTo(N, InsV);
22727   }
22728
22729   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22730   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22731     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22732     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22733     return DCI.CombineTo(N, InsV);
22734   }
22735
22736   return SDValue();
22737 }
22738
22739 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22740 /// possible.
22741 ///
22742 /// This is the leaf of the recursive combinine below. When we have found some
22743 /// chain of single-use x86 shuffle instructions and accumulated the combined
22744 /// shuffle mask represented by them, this will try to pattern match that mask
22745 /// into either a single instruction if there is a special purpose instruction
22746 /// for this operation, or into a PSHUFB instruction which is a fully general
22747 /// instruction but should only be used to replace chains over a certain depth.
22748 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22749                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22750                                    TargetLowering::DAGCombinerInfo &DCI,
22751                                    const X86Subtarget *Subtarget) {
22752   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22753
22754   // Find the operand that enters the chain. Note that multiple uses are OK
22755   // here, we're not going to remove the operand we find.
22756   SDValue Input = Op.getOperand(0);
22757   while (Input.getOpcode() == ISD::BITCAST)
22758     Input = Input.getOperand(0);
22759
22760   MVT VT = Input.getSimpleValueType();
22761   MVT RootVT = Root.getSimpleValueType();
22762   SDLoc DL(Root);
22763
22764   if (Mask.size() == 1) {
22765     int Index = Mask[0];
22766     assert((Index >= 0 || Index == SM_SentinelUndef ||
22767             Index == SM_SentinelZero) &&
22768            "Invalid shuffle index found!");
22769
22770     // We may end up with an accumulated mask of size 1 as a result of
22771     // widening of shuffle operands (see function canWidenShuffleElements).
22772     // If the only shuffle index is equal to SM_SentinelZero then propagate
22773     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22774     // mask, and therefore the entire chain of shuffles can be folded away.
22775     if (Index == SM_SentinelZero)
22776       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22777     else
22778       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22779                     /*AddTo*/ true);
22780     return true;
22781   }
22782
22783   // Use the float domain if the operand type is a floating point type.
22784   bool FloatDomain = VT.isFloatingPoint();
22785
22786   // For floating point shuffles, we don't have free copies in the shuffle
22787   // instructions or the ability to load as part of the instruction, so
22788   // canonicalize their shuffles to UNPCK or MOV variants.
22789   //
22790   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22791   // vectors because it can have a load folded into it that UNPCK cannot. This
22792   // doesn't preclude something switching to the shorter encoding post-RA.
22793   //
22794   // FIXME: Should teach these routines about AVX vector widths.
22795   if (FloatDomain && VT.is128BitVector()) {
22796     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22797       bool Lo = Mask.equals({0, 0});
22798       unsigned Shuffle;
22799       MVT ShuffleVT;
22800       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22801       // is no slower than UNPCKLPD but has the option to fold the input operand
22802       // into even an unaligned memory load.
22803       if (Lo && Subtarget->hasSSE3()) {
22804         Shuffle = X86ISD::MOVDDUP;
22805         ShuffleVT = MVT::v2f64;
22806       } else {
22807         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22808         // than the UNPCK variants.
22809         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22810         ShuffleVT = MVT::v4f32;
22811       }
22812       if (Depth == 1 && Root->getOpcode() == Shuffle)
22813         return false; // Nothing to do!
22814       Op = DAG.getBitcast(ShuffleVT, Input);
22815       DCI.AddToWorklist(Op.getNode());
22816       if (Shuffle == X86ISD::MOVDDUP)
22817         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22818       else
22819         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22820       DCI.AddToWorklist(Op.getNode());
22821       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22822                     /*AddTo*/ true);
22823       return true;
22824     }
22825     if (Subtarget->hasSSE3() &&
22826         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22827       bool Lo = Mask.equals({0, 0, 2, 2});
22828       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22829       MVT ShuffleVT = MVT::v4f32;
22830       if (Depth == 1 && Root->getOpcode() == Shuffle)
22831         return false; // Nothing to do!
22832       Op = DAG.getBitcast(ShuffleVT, Input);
22833       DCI.AddToWorklist(Op.getNode());
22834       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22835       DCI.AddToWorklist(Op.getNode());
22836       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22837                     /*AddTo*/ true);
22838       return true;
22839     }
22840     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22841       bool Lo = Mask.equals({0, 0, 1, 1});
22842       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22843       MVT ShuffleVT = MVT::v4f32;
22844       if (Depth == 1 && Root->getOpcode() == Shuffle)
22845         return false; // Nothing to do!
22846       Op = DAG.getBitcast(ShuffleVT, Input);
22847       DCI.AddToWorklist(Op.getNode());
22848       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22849       DCI.AddToWorklist(Op.getNode());
22850       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22851                     /*AddTo*/ true);
22852       return true;
22853     }
22854   }
22855
22856   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22857   // variants as none of these have single-instruction variants that are
22858   // superior to the UNPCK formulation.
22859   if (!FloatDomain && VT.is128BitVector() &&
22860       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22861        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22862        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22863        Mask.equals(
22864            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22865     bool Lo = Mask[0] == 0;
22866     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22867     if (Depth == 1 && Root->getOpcode() == Shuffle)
22868       return false; // Nothing to do!
22869     MVT ShuffleVT;
22870     switch (Mask.size()) {
22871     case 8:
22872       ShuffleVT = MVT::v8i16;
22873       break;
22874     case 16:
22875       ShuffleVT = MVT::v16i8;
22876       break;
22877     default:
22878       llvm_unreachable("Impossible mask size!");
22879     };
22880     Op = DAG.getBitcast(ShuffleVT, Input);
22881     DCI.AddToWorklist(Op.getNode());
22882     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22883     DCI.AddToWorklist(Op.getNode());
22884     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22885                   /*AddTo*/ true);
22886     return true;
22887   }
22888
22889   // Don't try to re-form single instruction chains under any circumstances now
22890   // that we've done encoding canonicalization for them.
22891   if (Depth < 2)
22892     return false;
22893
22894   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22895   // can replace them with a single PSHUFB instruction profitably. Intel's
22896   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22897   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22898   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22899     SmallVector<SDValue, 16> PSHUFBMask;
22900     int NumBytes = VT.getSizeInBits() / 8;
22901     int Ratio = NumBytes / Mask.size();
22902     for (int i = 0; i < NumBytes; ++i) {
22903       if (Mask[i / Ratio] == SM_SentinelUndef) {
22904         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22905         continue;
22906       }
22907       int M = Mask[i / Ratio] != SM_SentinelZero
22908                   ? Ratio * Mask[i / Ratio] + i % Ratio
22909                   : 255;
22910       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22911     }
22912     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22913     Op = DAG.getBitcast(ByteVT, Input);
22914     DCI.AddToWorklist(Op.getNode());
22915     SDValue PSHUFBMaskOp =
22916         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22917     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22918     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22919     DCI.AddToWorklist(Op.getNode());
22920     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22921                   /*AddTo*/ true);
22922     return true;
22923   }
22924
22925   // Failed to find any combines.
22926   return false;
22927 }
22928
22929 /// \brief Fully generic combining of x86 shuffle instructions.
22930 ///
22931 /// This should be the last combine run over the x86 shuffle instructions. Once
22932 /// they have been fully optimized, this will recursively consider all chains
22933 /// of single-use shuffle instructions, build a generic model of the cumulative
22934 /// shuffle operation, and check for simpler instructions which implement this
22935 /// operation. We use this primarily for two purposes:
22936 ///
22937 /// 1) Collapse generic shuffles to specialized single instructions when
22938 ///    equivalent. In most cases, this is just an encoding size win, but
22939 ///    sometimes we will collapse multiple generic shuffles into a single
22940 ///    special-purpose shuffle.
22941 /// 2) Look for sequences of shuffle instructions with 3 or more total
22942 ///    instructions, and replace them with the slightly more expensive SSSE3
22943 ///    PSHUFB instruction if available. We do this as the last combining step
22944 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22945 ///    a suitable short sequence of other instructions. The PHUFB will either
22946 ///    use a register or have to read from memory and so is slightly (but only
22947 ///    slightly) more expensive than the other shuffle instructions.
22948 ///
22949 /// Because this is inherently a quadratic operation (for each shuffle in
22950 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22951 /// This should never be an issue in practice as the shuffle lowering doesn't
22952 /// produce sequences of more than 8 instructions.
22953 ///
22954 /// FIXME: We will currently miss some cases where the redundant shuffling
22955 /// would simplify under the threshold for PSHUFB formation because of
22956 /// combine-ordering. To fix this, we should do the redundant instruction
22957 /// combining in this recursive walk.
22958 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22959                                           ArrayRef<int> RootMask,
22960                                           int Depth, bool HasPSHUFB,
22961                                           SelectionDAG &DAG,
22962                                           TargetLowering::DAGCombinerInfo &DCI,
22963                                           const X86Subtarget *Subtarget) {
22964   // Bound the depth of our recursive combine because this is ultimately
22965   // quadratic in nature.
22966   if (Depth > 8)
22967     return false;
22968
22969   // Directly rip through bitcasts to find the underlying operand.
22970   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22971     Op = Op.getOperand(0);
22972
22973   MVT VT = Op.getSimpleValueType();
22974   if (!VT.isVector())
22975     return false; // Bail if we hit a non-vector.
22976
22977   assert(Root.getSimpleValueType().isVector() &&
22978          "Shuffles operate on vector types!");
22979   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22980          "Can only combine shuffles of the same vector register size.");
22981
22982   if (!isTargetShuffle(Op.getOpcode()))
22983     return false;
22984   SmallVector<int, 16> OpMask;
22985   bool IsUnary;
22986   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22987   // We only can combine unary shuffles which we can decode the mask for.
22988   if (!HaveMask || !IsUnary)
22989     return false;
22990
22991   assert(VT.getVectorNumElements() == OpMask.size() &&
22992          "Different mask size from vector size!");
22993   assert(((RootMask.size() > OpMask.size() &&
22994            RootMask.size() % OpMask.size() == 0) ||
22995           (OpMask.size() > RootMask.size() &&
22996            OpMask.size() % RootMask.size() == 0) ||
22997           OpMask.size() == RootMask.size()) &&
22998          "The smaller number of elements must divide the larger.");
22999   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23000   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23001   assert(((RootRatio == 1 && OpRatio == 1) ||
23002           (RootRatio == 1) != (OpRatio == 1)) &&
23003          "Must not have a ratio for both incoming and op masks!");
23004
23005   SmallVector<int, 16> Mask;
23006   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23007
23008   // Merge this shuffle operation's mask into our accumulated mask. Note that
23009   // this shuffle's mask will be the first applied to the input, followed by the
23010   // root mask to get us all the way to the root value arrangement. The reason
23011   // for this order is that we are recursing up the operation chain.
23012   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23013     int RootIdx = i / RootRatio;
23014     if (RootMask[RootIdx] < 0) {
23015       // This is a zero or undef lane, we're done.
23016       Mask.push_back(RootMask[RootIdx]);
23017       continue;
23018     }
23019
23020     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23021     int OpIdx = RootMaskedIdx / OpRatio;
23022     if (OpMask[OpIdx] < 0) {
23023       // The incoming lanes are zero or undef, it doesn't matter which ones we
23024       // are using.
23025       Mask.push_back(OpMask[OpIdx]);
23026       continue;
23027     }
23028
23029     // Ok, we have non-zero lanes, map them through.
23030     Mask.push_back(OpMask[OpIdx] * OpRatio +
23031                    RootMaskedIdx % OpRatio);
23032   }
23033
23034   // See if we can recurse into the operand to combine more things.
23035   switch (Op.getOpcode()) {
23036   case X86ISD::PSHUFB:
23037     HasPSHUFB = true;
23038   case X86ISD::PSHUFD:
23039   case X86ISD::PSHUFHW:
23040   case X86ISD::PSHUFLW:
23041     if (Op.getOperand(0).hasOneUse() &&
23042         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23043                                       HasPSHUFB, DAG, DCI, Subtarget))
23044       return true;
23045     break;
23046
23047   case X86ISD::UNPCKL:
23048   case X86ISD::UNPCKH:
23049     assert(Op.getOperand(0) == Op.getOperand(1) &&
23050            "We only combine unary shuffles!");
23051     // We can't check for single use, we have to check that this shuffle is the
23052     // only user.
23053     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23054         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23055                                       HasPSHUFB, DAG, DCI, Subtarget))
23056       return true;
23057     break;
23058   }
23059
23060   // Minor canonicalization of the accumulated shuffle mask to make it easier
23061   // to match below. All this does is detect masks with squential pairs of
23062   // elements, and shrink them to the half-width mask. It does this in a loop
23063   // so it will reduce the size of the mask to the minimal width mask which
23064   // performs an equivalent shuffle.
23065   SmallVector<int, 16> WidenedMask;
23066   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23067     Mask = std::move(WidenedMask);
23068     WidenedMask.clear();
23069   }
23070
23071   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23072                                 Subtarget);
23073 }
23074
23075 /// \brief Get the PSHUF-style mask from PSHUF node.
23076 ///
23077 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23078 /// PSHUF-style masks that can be reused with such instructions.
23079 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23080   MVT VT = N.getSimpleValueType();
23081   SmallVector<int, 4> Mask;
23082   bool IsUnary;
23083   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
23084   (void)HaveMask;
23085   assert(HaveMask);
23086
23087   // If we have more than 128-bits, only the low 128-bits of shuffle mask
23088   // matter. Check that the upper masks are repeats and remove them.
23089   if (VT.getSizeInBits() > 128) {
23090     int LaneElts = 128 / VT.getScalarSizeInBits();
23091 #ifndef NDEBUG
23092     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23093       for (int j = 0; j < LaneElts; ++j)
23094         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23095                "Mask doesn't repeat in high 128-bit lanes!");
23096 #endif
23097     Mask.resize(LaneElts);
23098   }
23099
23100   switch (N.getOpcode()) {
23101   case X86ISD::PSHUFD:
23102     return Mask;
23103   case X86ISD::PSHUFLW:
23104     Mask.resize(4);
23105     return Mask;
23106   case X86ISD::PSHUFHW:
23107     Mask.erase(Mask.begin(), Mask.begin() + 4);
23108     for (int &M : Mask)
23109       M -= 4;
23110     return Mask;
23111   default:
23112     llvm_unreachable("No valid shuffle instruction found!");
23113   }
23114 }
23115
23116 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23117 ///
23118 /// We walk up the chain and look for a combinable shuffle, skipping over
23119 /// shuffles that we could hoist this shuffle's transformation past without
23120 /// altering anything.
23121 static SDValue
23122 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23123                              SelectionDAG &DAG,
23124                              TargetLowering::DAGCombinerInfo &DCI) {
23125   assert(N.getOpcode() == X86ISD::PSHUFD &&
23126          "Called with something other than an x86 128-bit half shuffle!");
23127   SDLoc DL(N);
23128
23129   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23130   // of the shuffles in the chain so that we can form a fresh chain to replace
23131   // this one.
23132   SmallVector<SDValue, 8> Chain;
23133   SDValue V = N.getOperand(0);
23134   for (; V.hasOneUse(); V = V.getOperand(0)) {
23135     switch (V.getOpcode()) {
23136     default:
23137       return SDValue(); // Nothing combined!
23138
23139     case ISD::BITCAST:
23140       // Skip bitcasts as we always know the type for the target specific
23141       // instructions.
23142       continue;
23143
23144     case X86ISD::PSHUFD:
23145       // Found another dword shuffle.
23146       break;
23147
23148     case X86ISD::PSHUFLW:
23149       // Check that the low words (being shuffled) are the identity in the
23150       // dword shuffle, and the high words are self-contained.
23151       if (Mask[0] != 0 || Mask[1] != 1 ||
23152           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23153         return SDValue();
23154
23155       Chain.push_back(V);
23156       continue;
23157
23158     case X86ISD::PSHUFHW:
23159       // Check that the high words (being shuffled) are the identity in the
23160       // dword shuffle, and the low words are self-contained.
23161       if (Mask[2] != 2 || Mask[3] != 3 ||
23162           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23163         return SDValue();
23164
23165       Chain.push_back(V);
23166       continue;
23167
23168     case X86ISD::UNPCKL:
23169     case X86ISD::UNPCKH:
23170       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23171       // shuffle into a preceding word shuffle.
23172       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23173           V.getSimpleValueType().getVectorElementType() != MVT::i16)
23174         return SDValue();
23175
23176       // Search for a half-shuffle which we can combine with.
23177       unsigned CombineOp =
23178           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23179       if (V.getOperand(0) != V.getOperand(1) ||
23180           !V->isOnlyUserOf(V.getOperand(0).getNode()))
23181         return SDValue();
23182       Chain.push_back(V);
23183       V = V.getOperand(0);
23184       do {
23185         switch (V.getOpcode()) {
23186         default:
23187           return SDValue(); // Nothing to combine.
23188
23189         case X86ISD::PSHUFLW:
23190         case X86ISD::PSHUFHW:
23191           if (V.getOpcode() == CombineOp)
23192             break;
23193
23194           Chain.push_back(V);
23195
23196           // Fallthrough!
23197         case ISD::BITCAST:
23198           V = V.getOperand(0);
23199           continue;
23200         }
23201         break;
23202       } while (V.hasOneUse());
23203       break;
23204     }
23205     // Break out of the loop if we break out of the switch.
23206     break;
23207   }
23208
23209   if (!V.hasOneUse())
23210     // We fell out of the loop without finding a viable combining instruction.
23211     return SDValue();
23212
23213   // Merge this node's mask and our incoming mask.
23214   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23215   for (int &M : Mask)
23216     M = VMask[M];
23217   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23218                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23219
23220   // Rebuild the chain around this new shuffle.
23221   while (!Chain.empty()) {
23222     SDValue W = Chain.pop_back_val();
23223
23224     if (V.getValueType() != W.getOperand(0).getValueType())
23225       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23226
23227     switch (W.getOpcode()) {
23228     default:
23229       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23230
23231     case X86ISD::UNPCKL:
23232     case X86ISD::UNPCKH:
23233       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23234       break;
23235
23236     case X86ISD::PSHUFD:
23237     case X86ISD::PSHUFLW:
23238     case X86ISD::PSHUFHW:
23239       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23240       break;
23241     }
23242   }
23243   if (V.getValueType() != N.getValueType())
23244     V = DAG.getBitcast(N.getValueType(), V);
23245
23246   // Return the new chain to replace N.
23247   return V;
23248 }
23249
23250 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23251 /// pshufhw.
23252 ///
23253 /// We walk up the chain, skipping shuffles of the other half and looking
23254 /// through shuffles which switch halves trying to find a shuffle of the same
23255 /// pair of dwords.
23256 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23257                                         SelectionDAG &DAG,
23258                                         TargetLowering::DAGCombinerInfo &DCI) {
23259   assert(
23260       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23261       "Called with something other than an x86 128-bit half shuffle!");
23262   SDLoc DL(N);
23263   unsigned CombineOpcode = N.getOpcode();
23264
23265   // Walk up a single-use chain looking for a combinable shuffle.
23266   SDValue V = N.getOperand(0);
23267   for (; V.hasOneUse(); V = V.getOperand(0)) {
23268     switch (V.getOpcode()) {
23269     default:
23270       return false; // Nothing combined!
23271
23272     case ISD::BITCAST:
23273       // Skip bitcasts as we always know the type for the target specific
23274       // instructions.
23275       continue;
23276
23277     case X86ISD::PSHUFLW:
23278     case X86ISD::PSHUFHW:
23279       if (V.getOpcode() == CombineOpcode)
23280         break;
23281
23282       // Other-half shuffles are no-ops.
23283       continue;
23284     }
23285     // Break out of the loop if we break out of the switch.
23286     break;
23287   }
23288
23289   if (!V.hasOneUse())
23290     // We fell out of the loop without finding a viable combining instruction.
23291     return false;
23292
23293   // Combine away the bottom node as its shuffle will be accumulated into
23294   // a preceding shuffle.
23295   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23296
23297   // Record the old value.
23298   SDValue Old = V;
23299
23300   // Merge this node's mask and our incoming mask (adjusted to account for all
23301   // the pshufd instructions encountered).
23302   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23303   for (int &M : Mask)
23304     M = VMask[M];
23305   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23306                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23307
23308   // Check that the shuffles didn't cancel each other out. If not, we need to
23309   // combine to the new one.
23310   if (Old != V)
23311     // Replace the combinable shuffle with the combined one, updating all users
23312     // so that we re-evaluate the chain here.
23313     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23314
23315   return true;
23316 }
23317
23318 /// \brief Try to combine x86 target specific shuffles.
23319 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23320                                            TargetLowering::DAGCombinerInfo &DCI,
23321                                            const X86Subtarget *Subtarget) {
23322   SDLoc DL(N);
23323   MVT VT = N.getSimpleValueType();
23324   SmallVector<int, 4> Mask;
23325
23326   switch (N.getOpcode()) {
23327   case X86ISD::PSHUFD:
23328   case X86ISD::PSHUFLW:
23329   case X86ISD::PSHUFHW:
23330     Mask = getPSHUFShuffleMask(N);
23331     assert(Mask.size() == 4);
23332     break;
23333   case X86ISD::UNPCKL: {
23334     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23335     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23336     // moves upper half elements into the lower half part. For example:
23337     //
23338     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23339     //     undef:v16i8
23340     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23341     //
23342     // will be combined to:
23343     //
23344     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23345
23346     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23347     // happen due to advanced instructions.
23348     if (!VT.is128BitVector())
23349       return SDValue();
23350
23351     auto Op0 = N.getOperand(0);
23352     auto Op1 = N.getOperand(1);
23353     if (Op0.getOpcode() == ISD::UNDEF &&
23354         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23355       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23356
23357       unsigned NumElts = VT.getVectorNumElements();
23358       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23359       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23360                 NumElts / 2);
23361
23362       auto ShufOp = Op1.getOperand(0);
23363       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23364         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23365     }
23366     return SDValue();
23367   }
23368   default:
23369     return SDValue();
23370   }
23371
23372   // Nuke no-op shuffles that show up after combining.
23373   if (isNoopShuffleMask(Mask))
23374     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23375
23376   // Look for simplifications involving one or two shuffle instructions.
23377   SDValue V = N.getOperand(0);
23378   switch (N.getOpcode()) {
23379   default:
23380     break;
23381   case X86ISD::PSHUFLW:
23382   case X86ISD::PSHUFHW:
23383     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23384
23385     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23386       return SDValue(); // We combined away this shuffle, so we're done.
23387
23388     // See if this reduces to a PSHUFD which is no more expensive and can
23389     // combine with more operations. Note that it has to at least flip the
23390     // dwords as otherwise it would have been removed as a no-op.
23391     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23392       int DMask[] = {0, 1, 2, 3};
23393       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23394       DMask[DOffset + 0] = DOffset + 1;
23395       DMask[DOffset + 1] = DOffset + 0;
23396       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23397       V = DAG.getBitcast(DVT, V);
23398       DCI.AddToWorklist(V.getNode());
23399       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23400                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23401       DCI.AddToWorklist(V.getNode());
23402       return DAG.getBitcast(VT, V);
23403     }
23404
23405     // Look for shuffle patterns which can be implemented as a single unpack.
23406     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23407     // only works when we have a PSHUFD followed by two half-shuffles.
23408     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23409         (V.getOpcode() == X86ISD::PSHUFLW ||
23410          V.getOpcode() == X86ISD::PSHUFHW) &&
23411         V.getOpcode() != N.getOpcode() &&
23412         V.hasOneUse()) {
23413       SDValue D = V.getOperand(0);
23414       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23415         D = D.getOperand(0);
23416       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23417         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23418         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23419         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23420         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23421         int WordMask[8];
23422         for (int i = 0; i < 4; ++i) {
23423           WordMask[i + NOffset] = Mask[i] + NOffset;
23424           WordMask[i + VOffset] = VMask[i] + VOffset;
23425         }
23426         // Map the word mask through the DWord mask.
23427         int MappedMask[8];
23428         for (int i = 0; i < 8; ++i)
23429           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23430         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23431             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23432           // We can replace all three shuffles with an unpack.
23433           V = DAG.getBitcast(VT, D.getOperand(0));
23434           DCI.AddToWorklist(V.getNode());
23435           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23436                                                 : X86ISD::UNPCKH,
23437                              DL, VT, V, V);
23438         }
23439       }
23440     }
23441
23442     break;
23443
23444   case X86ISD::PSHUFD:
23445     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23446       return NewN;
23447
23448     break;
23449   }
23450
23451   return SDValue();
23452 }
23453
23454 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23455 ///
23456 /// We combine this directly on the abstract vector shuffle nodes so it is
23457 /// easier to generically match. We also insert dummy vector shuffle nodes for
23458 /// the operands which explicitly discard the lanes which are unused by this
23459 /// operation to try to flow through the rest of the combiner the fact that
23460 /// they're unused.
23461 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23462   SDLoc DL(N);
23463   EVT VT = N->getValueType(0);
23464
23465   // We only handle target-independent shuffles.
23466   // FIXME: It would be easy and harmless to use the target shuffle mask
23467   // extraction tool to support more.
23468   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23469     return SDValue();
23470
23471   auto *SVN = cast<ShuffleVectorSDNode>(N);
23472   SmallVector<int, 8> Mask;
23473   for (int M : SVN->getMask())
23474     Mask.push_back(M);
23475
23476   SDValue V1 = N->getOperand(0);
23477   SDValue V2 = N->getOperand(1);
23478
23479   // We require the first shuffle operand to be the FSUB node, and the second to
23480   // be the FADD node.
23481   if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23482     ShuffleVectorSDNode::commuteMask(Mask);
23483     std::swap(V1, V2);
23484   } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23485     return SDValue();
23486
23487   // If there are other uses of these operations we can't fold them.
23488   if (!V1->hasOneUse() || !V2->hasOneUse())
23489     return SDValue();
23490
23491   // Ensure that both operations have the same operands. Note that we can
23492   // commute the FADD operands.
23493   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23494   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23495       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23496     return SDValue();
23497
23498   // We're looking for blends between FADD and FSUB nodes. We insist on these
23499   // nodes being lined up in a specific expected pattern.
23500   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23501         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23502         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23503     return SDValue();
23504
23505   // Only specific types are legal at this point, assert so we notice if and
23506   // when these change.
23507   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23508           VT == MVT::v4f64) &&
23509          "Unknown vector type encountered!");
23510
23511   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23512 }
23513
23514 /// PerformShuffleCombine - Performs several different shuffle combines.
23515 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23516                                      TargetLowering::DAGCombinerInfo &DCI,
23517                                      const X86Subtarget *Subtarget) {
23518   SDLoc dl(N);
23519   SDValue N0 = N->getOperand(0);
23520   SDValue N1 = N->getOperand(1);
23521   EVT VT = N->getValueType(0);
23522
23523   // Don't create instructions with illegal types after legalize types has run.
23524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23525   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23526     return SDValue();
23527
23528   // If we have legalized the vector types, look for blends of FADD and FSUB
23529   // nodes that we can fuse into an ADDSUB node.
23530   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23531     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23532       return AddSub;
23533
23534   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23535   if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23536       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23537     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23538
23539   // During Type Legalization, when promoting illegal vector types,
23540   // the backend might introduce new shuffle dag nodes and bitcasts.
23541   //
23542   // This code performs the following transformation:
23543   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23544   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23545   //
23546   // We do this only if both the bitcast and the BINOP dag nodes have
23547   // one use. Also, perform this transformation only if the new binary
23548   // operation is legal. This is to avoid introducing dag nodes that
23549   // potentially need to be further expanded (or custom lowered) into a
23550   // less optimal sequence of dag nodes.
23551   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23552       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23553       N0.getOpcode() == ISD::BITCAST) {
23554     SDValue BC0 = N0.getOperand(0);
23555     EVT SVT = BC0.getValueType();
23556     unsigned Opcode = BC0.getOpcode();
23557     unsigned NumElts = VT.getVectorNumElements();
23558
23559     if (BC0.hasOneUse() && SVT.isVector() &&
23560         SVT.getVectorNumElements() * 2 == NumElts &&
23561         TLI.isOperationLegal(Opcode, VT)) {
23562       bool CanFold = false;
23563       switch (Opcode) {
23564       default : break;
23565       case ISD::ADD :
23566       case ISD::FADD :
23567       case ISD::SUB :
23568       case ISD::FSUB :
23569       case ISD::MUL :
23570       case ISD::FMUL :
23571         CanFold = true;
23572       }
23573
23574       unsigned SVTNumElts = SVT.getVectorNumElements();
23575       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23576       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23577         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23578       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23579         CanFold = SVOp->getMaskElt(i) < 0;
23580
23581       if (CanFold) {
23582         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23583         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23584         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23585         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23586       }
23587     }
23588   }
23589
23590   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23591   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23592   // consecutive, non-overlapping, and in the right order.
23593   SmallVector<SDValue, 16> Elts;
23594   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23595     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23596
23597   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23598     return LD;
23599
23600   if (isTargetShuffle(N->getOpcode())) {
23601     SDValue Shuffle =
23602         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23603     if (Shuffle.getNode())
23604       return Shuffle;
23605
23606     // Try recursively combining arbitrary sequences of x86 shuffle
23607     // instructions into higher-order shuffles. We do this after combining
23608     // specific PSHUF instruction sequences into their minimal form so that we
23609     // can evaluate how many specialized shuffle instructions are involved in
23610     // a particular chain.
23611     SmallVector<int, 1> NonceMask; // Just a placeholder.
23612     NonceMask.push_back(0);
23613     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23614                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23615                                       DCI, Subtarget))
23616       return SDValue(); // This routine will use CombineTo to replace N.
23617   }
23618
23619   return SDValue();
23620 }
23621
23622 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23623 /// specific shuffle of a load can be folded into a single element load.
23624 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23625 /// shuffles have been custom lowered so we need to handle those here.
23626 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23627                                          TargetLowering::DAGCombinerInfo &DCI) {
23628   if (DCI.isBeforeLegalizeOps())
23629     return SDValue();
23630
23631   SDValue InVec = N->getOperand(0);
23632   SDValue EltNo = N->getOperand(1);
23633
23634   if (!isa<ConstantSDNode>(EltNo))
23635     return SDValue();
23636
23637   EVT OriginalVT = InVec.getValueType();
23638
23639   if (InVec.getOpcode() == ISD::BITCAST) {
23640     // Don't duplicate a load with other uses.
23641     if (!InVec.hasOneUse())
23642       return SDValue();
23643     EVT BCVT = InVec.getOperand(0).getValueType();
23644     if (!BCVT.isVector() ||
23645         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23646       return SDValue();
23647     InVec = InVec.getOperand(0);
23648   }
23649
23650   EVT CurrentVT = InVec.getValueType();
23651
23652   if (!isTargetShuffle(InVec.getOpcode()))
23653     return SDValue();
23654
23655   // Don't duplicate a load with other uses.
23656   if (!InVec.hasOneUse())
23657     return SDValue();
23658
23659   SmallVector<int, 16> ShuffleMask;
23660   bool UnaryShuffle;
23661   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23662                             ShuffleMask, UnaryShuffle))
23663     return SDValue();
23664
23665   // Select the input vector, guarding against out of range extract vector.
23666   unsigned NumElems = CurrentVT.getVectorNumElements();
23667   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23668   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23669   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23670                                          : InVec.getOperand(1);
23671
23672   // If inputs to shuffle are the same for both ops, then allow 2 uses
23673   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23674                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23675
23676   if (LdNode.getOpcode() == ISD::BITCAST) {
23677     // Don't duplicate a load with other uses.
23678     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23679       return SDValue();
23680
23681     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23682     LdNode = LdNode.getOperand(0);
23683   }
23684
23685   if (!ISD::isNormalLoad(LdNode.getNode()))
23686     return SDValue();
23687
23688   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23689
23690   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23691     return SDValue();
23692
23693   EVT EltVT = N->getValueType(0);
23694   // If there's a bitcast before the shuffle, check if the load type and
23695   // alignment is valid.
23696   unsigned Align = LN0->getAlignment();
23697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23698   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23699       EltVT.getTypeForEVT(*DAG.getContext()));
23700
23701   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23702     return SDValue();
23703
23704   // All checks match so transform back to vector_shuffle so that DAG combiner
23705   // can finish the job
23706   SDLoc dl(N);
23707
23708   // Create shuffle node taking into account the case that its a unary shuffle
23709   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23710                                    : InVec.getOperand(1);
23711   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23712                                  InVec.getOperand(0), Shuffle,
23713                                  &ShuffleMask[0]);
23714   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23715   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23716                      EltNo);
23717 }
23718
23719 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23720                                      const X86Subtarget *Subtarget) {
23721   SDValue N0 = N->getOperand(0);
23722   EVT VT = N->getValueType(0);
23723
23724   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23725   // special and don't usually play with other vector types, it's better to
23726   // handle them early to be sure we emit efficient code by avoiding
23727   // store-load conversions.
23728   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23729       N0.getValueType() == MVT::v2i32 &&
23730       isNullConstant(N0.getOperand(1))) {
23731     SDValue N00 = N0->getOperand(0);
23732     if (N00.getValueType() == MVT::i32)
23733       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23734   }
23735
23736   // Convert a bitcasted integer logic operation that has one bitcasted
23737   // floating-point operand and one constant operand into a floating-point
23738   // logic operation. This may create a load of the constant, but that is
23739   // cheaper than materializing the constant in an integer register and
23740   // transferring it to an SSE register or transferring the SSE operand to
23741   // integer register and back.
23742   unsigned FPOpcode;
23743   switch (N0.getOpcode()) {
23744     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23745     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23746     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23747     default: return SDValue();
23748   }
23749   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23750        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23751       isa<ConstantSDNode>(N0.getOperand(1)) &&
23752       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23753       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23754     SDValue N000 = N0.getOperand(0).getOperand(0);
23755     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23756     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23757   }
23758
23759   return SDValue();
23760 }
23761
23762 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23763 /// generation and convert it from being a bunch of shuffles and extracts
23764 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23765 /// storing the value and loading scalars back, while for x64 we should
23766 /// use 64-bit extracts and shifts.
23767 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23768                                          TargetLowering::DAGCombinerInfo &DCI) {
23769   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23770     return NewOp;
23771
23772   SDValue InputVector = N->getOperand(0);
23773   SDLoc dl(InputVector);
23774   // Detect mmx to i32 conversion through a v2i32 elt extract.
23775   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23776       N->getValueType(0) == MVT::i32 &&
23777       InputVector.getValueType() == MVT::v2i32) {
23778
23779     // The bitcast source is a direct mmx result.
23780     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23781     if (MMXSrc.getValueType() == MVT::x86mmx)
23782       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23783                          N->getValueType(0),
23784                          InputVector.getNode()->getOperand(0));
23785
23786     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23787     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23788         MMXSrc.getValueType() == MVT::i64) {
23789       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23790       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23791           MMXSrcOp.getValueType() == MVT::v1i64 &&
23792           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23793         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23794                            N->getValueType(0), MMXSrcOp.getOperand(0));
23795     }
23796   }
23797
23798   EVT VT = N->getValueType(0);
23799
23800   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
23801       InputVector.getOpcode() == ISD::BITCAST &&
23802       isa<ConstantSDNode>(InputVector.getOperand(0))) {
23803     uint64_t ExtractedElt =
23804         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23805     uint64_t InputValue =
23806         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23807     uint64_t Res = (InputValue >> ExtractedElt) & 1;
23808     return DAG.getConstant(Res, dl, MVT::i1);
23809   }
23810   // Only operate on vectors of 4 elements, where the alternative shuffling
23811   // gets to be more expensive.
23812   if (InputVector.getValueType() != MVT::v4i32)
23813     return SDValue();
23814
23815   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23816   // single use which is a sign-extend or zero-extend, and all elements are
23817   // used.
23818   SmallVector<SDNode *, 4> Uses;
23819   unsigned ExtractedElements = 0;
23820   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23821        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23822     if (UI.getUse().getResNo() != InputVector.getResNo())
23823       return SDValue();
23824
23825     SDNode *Extract = *UI;
23826     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23827       return SDValue();
23828
23829     if (Extract->getValueType(0) != MVT::i32)
23830       return SDValue();
23831     if (!Extract->hasOneUse())
23832       return SDValue();
23833     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23834         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23835       return SDValue();
23836     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23837       return SDValue();
23838
23839     // Record which element was extracted.
23840     ExtractedElements |=
23841       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23842
23843     Uses.push_back(Extract);
23844   }
23845
23846   // If not all the elements were used, this may not be worthwhile.
23847   if (ExtractedElements != 15)
23848     return SDValue();
23849
23850   // Ok, we've now decided to do the transformation.
23851   // If 64-bit shifts are legal, use the extract-shift sequence,
23852   // otherwise bounce the vector off the cache.
23853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23854   SDValue Vals[4];
23855
23856   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23857     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23858     auto &DL = DAG.getDataLayout();
23859     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23860     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23861       DAG.getConstant(0, dl, VecIdxTy));
23862     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23863       DAG.getConstant(1, dl, VecIdxTy));
23864
23865     SDValue ShAmt = DAG.getConstant(
23866         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23867     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23868     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23869       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23870     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23871     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23872       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23873   } else {
23874     // Store the value to a temporary stack slot.
23875     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23876     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23877       MachinePointerInfo(), false, false, 0);
23878
23879     EVT ElementType = InputVector.getValueType().getVectorElementType();
23880     unsigned EltSize = ElementType.getSizeInBits() / 8;
23881
23882     // Replace each use (extract) with a load of the appropriate element.
23883     for (unsigned i = 0; i < 4; ++i) {
23884       uint64_t Offset = EltSize * i;
23885       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23886       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23887
23888       SDValue ScalarAddr =
23889           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23890
23891       // Load the scalar.
23892       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23893                             ScalarAddr, MachinePointerInfo(),
23894                             false, false, false, 0);
23895
23896     }
23897   }
23898
23899   // Replace the extracts
23900   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23901     UE = Uses.end(); UI != UE; ++UI) {
23902     SDNode *Extract = *UI;
23903
23904     SDValue Idx = Extract->getOperand(1);
23905     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23906     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23907   }
23908
23909   // The replacement was made in place; don't return anything.
23910   return SDValue();
23911 }
23912
23913 static SDValue
23914 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23915                                       const X86Subtarget *Subtarget) {
23916   SDLoc dl(N);
23917   SDValue Cond = N->getOperand(0);
23918   SDValue LHS = N->getOperand(1);
23919   SDValue RHS = N->getOperand(2);
23920
23921   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23922     SDValue CondSrc = Cond->getOperand(0);
23923     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23924       Cond = CondSrc->getOperand(0);
23925   }
23926
23927   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23928     return SDValue();
23929
23930   // A vselect where all conditions and data are constants can be optimized into
23931   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23932   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23933       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23934     return SDValue();
23935
23936   unsigned MaskValue = 0;
23937   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23938     return SDValue();
23939
23940   MVT VT = N->getSimpleValueType(0);
23941   unsigned NumElems = VT.getVectorNumElements();
23942   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23943   for (unsigned i = 0; i < NumElems; ++i) {
23944     // Be sure we emit undef where we can.
23945     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23946       ShuffleMask[i] = -1;
23947     else
23948       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23949   }
23950
23951   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23952   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23953     return SDValue();
23954   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23955 }
23956
23957 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23958 /// nodes.
23959 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23960                                     TargetLowering::DAGCombinerInfo &DCI,
23961                                     const X86Subtarget *Subtarget) {
23962   SDLoc DL(N);
23963   SDValue Cond = N->getOperand(0);
23964   // Get the LHS/RHS of the select.
23965   SDValue LHS = N->getOperand(1);
23966   SDValue RHS = N->getOperand(2);
23967   EVT VT = LHS.getValueType();
23968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23969
23970   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23971   // instructions match the semantics of the common C idiom x<y?x:y but not
23972   // x<=y?x:y, because of how they handle negative zero (which can be
23973   // ignored in unsafe-math mode).
23974   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23975   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23976       VT != MVT::f80 && VT != MVT::f128 &&
23977       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23978       (Subtarget->hasSSE2() ||
23979        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23980     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23981
23982     unsigned Opcode = 0;
23983     // Check for x CC y ? x : y.
23984     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23985         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23986       switch (CC) {
23987       default: break;
23988       case ISD::SETULT:
23989         // Converting this to a min would handle NaNs incorrectly, and swapping
23990         // the operands would cause it to handle comparisons between positive
23991         // and negative zero incorrectly.
23992         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23993           if (!DAG.getTarget().Options.UnsafeFPMath &&
23994               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23995             break;
23996           std::swap(LHS, RHS);
23997         }
23998         Opcode = X86ISD::FMIN;
23999         break;
24000       case ISD::SETOLE:
24001         // Converting this to a min would handle comparisons between positive
24002         // and negative zero incorrectly.
24003         if (!DAG.getTarget().Options.UnsafeFPMath &&
24004             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24005           break;
24006         Opcode = X86ISD::FMIN;
24007         break;
24008       case ISD::SETULE:
24009         // Converting this to a min would handle both negative zeros and NaNs
24010         // incorrectly, but we can swap the operands to fix both.
24011         std::swap(LHS, RHS);
24012       case ISD::SETOLT:
24013       case ISD::SETLT:
24014       case ISD::SETLE:
24015         Opcode = X86ISD::FMIN;
24016         break;
24017
24018       case ISD::SETOGE:
24019         // Converting this to a max would handle comparisons between positive
24020         // and negative zero incorrectly.
24021         if (!DAG.getTarget().Options.UnsafeFPMath &&
24022             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24023           break;
24024         Opcode = X86ISD::FMAX;
24025         break;
24026       case ISD::SETUGT:
24027         // Converting this to a max would handle NaNs incorrectly, and swapping
24028         // the operands would cause it to handle comparisons between positive
24029         // and negative zero incorrectly.
24030         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24031           if (!DAG.getTarget().Options.UnsafeFPMath &&
24032               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24033             break;
24034           std::swap(LHS, RHS);
24035         }
24036         Opcode = X86ISD::FMAX;
24037         break;
24038       case ISD::SETUGE:
24039         // Converting this to a max would handle both negative zeros and NaNs
24040         // incorrectly, but we can swap the operands to fix both.
24041         std::swap(LHS, RHS);
24042       case ISD::SETOGT:
24043       case ISD::SETGT:
24044       case ISD::SETGE:
24045         Opcode = X86ISD::FMAX;
24046         break;
24047       }
24048     // Check for x CC y ? y : x -- a min/max with reversed arms.
24049     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24050                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24051       switch (CC) {
24052       default: break;
24053       case ISD::SETOGE:
24054         // Converting this to a min would handle comparisons between positive
24055         // and negative zero incorrectly, and swapping the operands would
24056         // cause it to handle NaNs incorrectly.
24057         if (!DAG.getTarget().Options.UnsafeFPMath &&
24058             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24059           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24060             break;
24061           std::swap(LHS, RHS);
24062         }
24063         Opcode = X86ISD::FMIN;
24064         break;
24065       case ISD::SETUGT:
24066         // Converting this to a min would handle NaNs incorrectly.
24067         if (!DAG.getTarget().Options.UnsafeFPMath &&
24068             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24069           break;
24070         Opcode = X86ISD::FMIN;
24071         break;
24072       case ISD::SETUGE:
24073         // Converting this to a min would handle both negative zeros and NaNs
24074         // incorrectly, but we can swap the operands to fix both.
24075         std::swap(LHS, RHS);
24076       case ISD::SETOGT:
24077       case ISD::SETGT:
24078       case ISD::SETGE:
24079         Opcode = X86ISD::FMIN;
24080         break;
24081
24082       case ISD::SETULT:
24083         // Converting this to a max would handle NaNs incorrectly.
24084         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24085           break;
24086         Opcode = X86ISD::FMAX;
24087         break;
24088       case ISD::SETOLE:
24089         // Converting this to a max would handle comparisons between positive
24090         // and negative zero incorrectly, and swapping the operands would
24091         // cause it to handle NaNs incorrectly.
24092         if (!DAG.getTarget().Options.UnsafeFPMath &&
24093             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24094           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24095             break;
24096           std::swap(LHS, RHS);
24097         }
24098         Opcode = X86ISD::FMAX;
24099         break;
24100       case ISD::SETULE:
24101         // Converting this to a max would handle both negative zeros and NaNs
24102         // incorrectly, but we can swap the operands to fix both.
24103         std::swap(LHS, RHS);
24104       case ISD::SETOLT:
24105       case ISD::SETLT:
24106       case ISD::SETLE:
24107         Opcode = X86ISD::FMAX;
24108         break;
24109       }
24110     }
24111
24112     if (Opcode)
24113       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24114   }
24115
24116   EVT CondVT = Cond.getValueType();
24117   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24118       CondVT.getVectorElementType() == MVT::i1) {
24119     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24120     // lowering on KNL. In this case we convert it to
24121     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24122     // The same situation for all 128 and 256-bit vectors of i8 and i16.
24123     // Since SKX these selects have a proper lowering.
24124     EVT OpVT = LHS.getValueType();
24125     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24126         (OpVT.getVectorElementType() == MVT::i8 ||
24127          OpVT.getVectorElementType() == MVT::i16) &&
24128         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24129       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24130       DCI.AddToWorklist(Cond.getNode());
24131       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24132     }
24133   }
24134   // If this is a select between two integer constants, try to do some
24135   // optimizations.
24136   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24137     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24138       // Don't do this for crazy integer types.
24139       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24140         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24141         // so that TrueC (the true value) is larger than FalseC.
24142         bool NeedsCondInvert = false;
24143
24144         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24145             // Efficiently invertible.
24146             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
24147              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
24148               isa<ConstantSDNode>(Cond.getOperand(1))))) {
24149           NeedsCondInvert = true;
24150           std::swap(TrueC, FalseC);
24151         }
24152
24153         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
24154         if (FalseC->getAPIntValue() == 0 &&
24155             TrueC->getAPIntValue().isPowerOf2()) {
24156           if (NeedsCondInvert) // Invert the condition if needed.
24157             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24158                                DAG.getConstant(1, DL, Cond.getValueType()));
24159
24160           // Zero extend the condition if needed.
24161           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24162
24163           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24164           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24165                              DAG.getConstant(ShAmt, DL, MVT::i8));
24166         }
24167
24168         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24169         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24170           if (NeedsCondInvert) // Invert the condition if needed.
24171             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24172                                DAG.getConstant(1, DL, Cond.getValueType()));
24173
24174           // Zero extend the condition if needed.
24175           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24176                              FalseC->getValueType(0), Cond);
24177           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24178                              SDValue(FalseC, 0));
24179         }
24180
24181         // Optimize cases that will turn into an LEA instruction.  This requires
24182         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24183         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24184           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24185           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24186
24187           bool isFastMultiplier = false;
24188           if (Diff < 10) {
24189             switch ((unsigned char)Diff) {
24190               default: break;
24191               case 1:  // result = add base, cond
24192               case 2:  // result = lea base(    , cond*2)
24193               case 3:  // result = lea base(cond, cond*2)
24194               case 4:  // result = lea base(    , cond*4)
24195               case 5:  // result = lea base(cond, cond*4)
24196               case 8:  // result = lea base(    , cond*8)
24197               case 9:  // result = lea base(cond, cond*8)
24198                 isFastMultiplier = true;
24199                 break;
24200             }
24201           }
24202
24203           if (isFastMultiplier) {
24204             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24205             if (NeedsCondInvert) // Invert the condition if needed.
24206               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24207                                  DAG.getConstant(1, DL, Cond.getValueType()));
24208
24209             // Zero extend the condition if needed.
24210             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24211                                Cond);
24212             // Scale the condition by the difference.
24213             if (Diff != 1)
24214               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24215                                  DAG.getConstant(Diff, DL,
24216                                                  Cond.getValueType()));
24217
24218             // Add the base if non-zero.
24219             if (FalseC->getAPIntValue() != 0)
24220               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24221                                  SDValue(FalseC, 0));
24222             return Cond;
24223           }
24224         }
24225       }
24226   }
24227
24228   // Canonicalize max and min:
24229   // (x > y) ? x : y -> (x >= y) ? x : y
24230   // (x < y) ? x : y -> (x <= y) ? x : y
24231   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24232   // the need for an extra compare
24233   // against zero. e.g.
24234   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24235   // subl   %esi, %edi
24236   // testl  %edi, %edi
24237   // movl   $0, %eax
24238   // cmovgl %edi, %eax
24239   // =>
24240   // xorl   %eax, %eax
24241   // subl   %esi, $edi
24242   // cmovsl %eax, %edi
24243   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24244       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24245       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24246     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24247     switch (CC) {
24248     default: break;
24249     case ISD::SETLT:
24250     case ISD::SETGT: {
24251       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24252       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24253                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
24254       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24255     }
24256     }
24257   }
24258
24259   // Early exit check
24260   if (!TLI.isTypeLegal(VT))
24261     return SDValue();
24262
24263   // Match VSELECTs into subs with unsigned saturation.
24264   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24265       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24266       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24267        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24268     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24269
24270     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24271     // left side invert the predicate to simplify logic below.
24272     SDValue Other;
24273     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24274       Other = RHS;
24275       CC = ISD::getSetCCInverse(CC, true);
24276     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24277       Other = LHS;
24278     }
24279
24280     if (Other.getNode() && Other->getNumOperands() == 2 &&
24281         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24282       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24283       SDValue CondRHS = Cond->getOperand(1);
24284
24285       // Look for a general sub with unsigned saturation first.
24286       // x >= y ? x-y : 0 --> subus x, y
24287       // x >  y ? x-y : 0 --> subus x, y
24288       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24289           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24290         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24291
24292       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24293         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24294           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24295             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24296               // If the RHS is a constant we have to reverse the const
24297               // canonicalization.
24298               // x > C-1 ? x+-C : 0 --> subus x, C
24299               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24300                   CondRHSConst->getAPIntValue() ==
24301                       (-OpRHSConst->getAPIntValue() - 1))
24302                 return DAG.getNode(
24303                     X86ISD::SUBUS, DL, VT, OpLHS,
24304                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24305
24306           // Another special case: If C was a sign bit, the sub has been
24307           // canonicalized into a xor.
24308           // FIXME: Would it be better to use computeKnownBits to determine
24309           //        whether it's safe to decanonicalize the xor?
24310           // x s< 0 ? x^C : 0 --> subus x, C
24311           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24312               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24313               OpRHSConst->getAPIntValue().isSignBit())
24314             // Note that we have to rebuild the RHS constant here to ensure we
24315             // don't rely on particular values of undef lanes.
24316             return DAG.getNode(
24317                 X86ISD::SUBUS, DL, VT, OpLHS,
24318                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24319         }
24320     }
24321   }
24322
24323   // Simplify vector selection if condition value type matches vselect
24324   // operand type
24325   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24326     assert(Cond.getValueType().isVector() &&
24327            "vector select expects a vector selector!");
24328
24329     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24330     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24331
24332     // Try invert the condition if true value is not all 1s and false value
24333     // is not all 0s.
24334     if (!TValIsAllOnes && !FValIsAllZeros &&
24335         // Check if the selector will be produced by CMPP*/PCMP*
24336         Cond.getOpcode() == ISD::SETCC &&
24337         // Check if SETCC has already been promoted
24338         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24339             CondVT) {
24340       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24341       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24342
24343       if (TValIsAllZeros || FValIsAllOnes) {
24344         SDValue CC = Cond.getOperand(2);
24345         ISD::CondCode NewCC =
24346           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24347                                Cond.getOperand(0).getValueType().isInteger());
24348         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24349         std::swap(LHS, RHS);
24350         TValIsAllOnes = FValIsAllOnes;
24351         FValIsAllZeros = TValIsAllZeros;
24352       }
24353     }
24354
24355     if (TValIsAllOnes || FValIsAllZeros) {
24356       SDValue Ret;
24357
24358       if (TValIsAllOnes && FValIsAllZeros)
24359         Ret = Cond;
24360       else if (TValIsAllOnes)
24361         Ret =
24362             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24363       else if (FValIsAllZeros)
24364         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24365                           DAG.getBitcast(CondVT, LHS));
24366
24367       return DAG.getBitcast(VT, Ret);
24368     }
24369   }
24370
24371   // We should generate an X86ISD::BLENDI from a vselect if its argument
24372   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24373   // constants. This specific pattern gets generated when we split a
24374   // selector for a 512 bit vector in a machine without AVX512 (but with
24375   // 256-bit vectors), during legalization:
24376   //
24377   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24378   //
24379   // Iff we find this pattern and the build_vectors are built from
24380   // constants, we translate the vselect into a shuffle_vector that we
24381   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24382   if ((N->getOpcode() == ISD::VSELECT ||
24383        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24384       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24385     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24386     if (Shuffle.getNode())
24387       return Shuffle;
24388   }
24389
24390   // If this is a *dynamic* select (non-constant condition) and we can match
24391   // this node with one of the variable blend instructions, restructure the
24392   // condition so that the blends can use the high bit of each element and use
24393   // SimplifyDemandedBits to simplify the condition operand.
24394   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24395       !DCI.isBeforeLegalize() &&
24396       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24397     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24398
24399     // Don't optimize vector selects that map to mask-registers.
24400     if (BitWidth == 1)
24401       return SDValue();
24402
24403     // We can only handle the cases where VSELECT is directly legal on the
24404     // subtarget. We custom lower VSELECT nodes with constant conditions and
24405     // this makes it hard to see whether a dynamic VSELECT will correctly
24406     // lower, so we both check the operation's status and explicitly handle the
24407     // cases where a *dynamic* blend will fail even though a constant-condition
24408     // blend could be custom lowered.
24409     // FIXME: We should find a better way to handle this class of problems.
24410     // Potentially, we should combine constant-condition vselect nodes
24411     // pre-legalization into shuffles and not mark as many types as custom
24412     // lowered.
24413     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24414       return SDValue();
24415     // FIXME: We don't support i16-element blends currently. We could and
24416     // should support them by making *all* the bits in the condition be set
24417     // rather than just the high bit and using an i8-element blend.
24418     if (VT.getVectorElementType() == MVT::i16)
24419       return SDValue();
24420     // Dynamic blending was only available from SSE4.1 onward.
24421     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24422       return SDValue();
24423     // Byte blends are only available in AVX2
24424     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24425       return SDValue();
24426
24427     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24428     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24429
24430     APInt KnownZero, KnownOne;
24431     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24432                                           DCI.isBeforeLegalizeOps());
24433     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24434         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24435                                  TLO)) {
24436       // If we changed the computation somewhere in the DAG, this change
24437       // will affect all users of Cond.
24438       // Make sure it is fine and update all the nodes so that we do not
24439       // use the generic VSELECT anymore. Otherwise, we may perform
24440       // wrong optimizations as we messed up with the actual expectation
24441       // for the vector boolean values.
24442       if (Cond != TLO.Old) {
24443         // Check all uses of that condition operand to check whether it will be
24444         // consumed by non-BLEND instructions, which may depend on all bits are
24445         // set properly.
24446         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24447              I != E; ++I)
24448           if (I->getOpcode() != ISD::VSELECT)
24449             // TODO: Add other opcodes eventually lowered into BLEND.
24450             return SDValue();
24451
24452         // Update all the users of the condition, before committing the change,
24453         // so that the VSELECT optimizations that expect the correct vector
24454         // boolean value will not be triggered.
24455         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24456              I != E; ++I)
24457           DAG.ReplaceAllUsesOfValueWith(
24458               SDValue(*I, 0),
24459               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24460                           Cond, I->getOperand(1), I->getOperand(2)));
24461         DCI.CommitTargetLoweringOpt(TLO);
24462         return SDValue();
24463       }
24464       // At this point, only Cond is changed. Change the condition
24465       // just for N to keep the opportunity to optimize all other
24466       // users their own way.
24467       DAG.ReplaceAllUsesOfValueWith(
24468           SDValue(N, 0),
24469           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24470                       TLO.New, N->getOperand(1), N->getOperand(2)));
24471       return SDValue();
24472     }
24473   }
24474
24475   return SDValue();
24476 }
24477
24478 // Check whether a boolean test is testing a boolean value generated by
24479 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24480 // code.
24481 //
24482 // Simplify the following patterns:
24483 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24484 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24485 // to (Op EFLAGS Cond)
24486 //
24487 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24488 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24489 // to (Op EFLAGS !Cond)
24490 //
24491 // where Op could be BRCOND or CMOV.
24492 //
24493 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24494   // Quit if not CMP and SUB with its value result used.
24495   if (Cmp.getOpcode() != X86ISD::CMP &&
24496       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24497       return SDValue();
24498
24499   // Quit if not used as a boolean value.
24500   if (CC != X86::COND_E && CC != X86::COND_NE)
24501     return SDValue();
24502
24503   // Check CMP operands. One of them should be 0 or 1 and the other should be
24504   // an SetCC or extended from it.
24505   SDValue Op1 = Cmp.getOperand(0);
24506   SDValue Op2 = Cmp.getOperand(1);
24507
24508   SDValue SetCC;
24509   const ConstantSDNode* C = nullptr;
24510   bool needOppositeCond = (CC == X86::COND_E);
24511   bool checkAgainstTrue = false; // Is it a comparison against 1?
24512
24513   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24514     SetCC = Op2;
24515   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24516     SetCC = Op1;
24517   else // Quit if all operands are not constants.
24518     return SDValue();
24519
24520   if (C->getZExtValue() == 1) {
24521     needOppositeCond = !needOppositeCond;
24522     checkAgainstTrue = true;
24523   } else if (C->getZExtValue() != 0)
24524     // Quit if the constant is neither 0 or 1.
24525     return SDValue();
24526
24527   bool truncatedToBoolWithAnd = false;
24528   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24529   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24530          SetCC.getOpcode() == ISD::TRUNCATE ||
24531          SetCC.getOpcode() == ISD::AND) {
24532     if (SetCC.getOpcode() == ISD::AND) {
24533       int OpIdx = -1;
24534       if (isOneConstant(SetCC.getOperand(0)))
24535         OpIdx = 1;
24536       if (isOneConstant(SetCC.getOperand(1)))
24537         OpIdx = 0;
24538       if (OpIdx == -1)
24539         break;
24540       SetCC = SetCC.getOperand(OpIdx);
24541       truncatedToBoolWithAnd = true;
24542     } else
24543       SetCC = SetCC.getOperand(0);
24544   }
24545
24546   switch (SetCC.getOpcode()) {
24547   case X86ISD::SETCC_CARRY:
24548     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24549     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24550     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24551     // truncated to i1 using 'and'.
24552     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24553       break;
24554     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24555            "Invalid use of SETCC_CARRY!");
24556     // FALL THROUGH
24557   case X86ISD::SETCC:
24558     // Set the condition code or opposite one if necessary.
24559     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24560     if (needOppositeCond)
24561       CC = X86::GetOppositeBranchCondition(CC);
24562     return SetCC.getOperand(1);
24563   case X86ISD::CMOV: {
24564     // Check whether false/true value has canonical one, i.e. 0 or 1.
24565     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24566     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24567     // Quit if true value is not a constant.
24568     if (!TVal)
24569       return SDValue();
24570     // Quit if false value is not a constant.
24571     if (!FVal) {
24572       SDValue Op = SetCC.getOperand(0);
24573       // Skip 'zext' or 'trunc' node.
24574       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24575           Op.getOpcode() == ISD::TRUNCATE)
24576         Op = Op.getOperand(0);
24577       // A special case for rdrand/rdseed, where 0 is set if false cond is
24578       // found.
24579       if ((Op.getOpcode() != X86ISD::RDRAND &&
24580            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24581         return SDValue();
24582     }
24583     // Quit if false value is not the constant 0 or 1.
24584     bool FValIsFalse = true;
24585     if (FVal && FVal->getZExtValue() != 0) {
24586       if (FVal->getZExtValue() != 1)
24587         return SDValue();
24588       // If FVal is 1, opposite cond is needed.
24589       needOppositeCond = !needOppositeCond;
24590       FValIsFalse = false;
24591     }
24592     // Quit if TVal is not the constant opposite of FVal.
24593     if (FValIsFalse && TVal->getZExtValue() != 1)
24594       return SDValue();
24595     if (!FValIsFalse && TVal->getZExtValue() != 0)
24596       return SDValue();
24597     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24598     if (needOppositeCond)
24599       CC = X86::GetOppositeBranchCondition(CC);
24600     return SetCC.getOperand(3);
24601   }
24602   }
24603
24604   return SDValue();
24605 }
24606
24607 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24608 /// Match:
24609 ///   (X86or (X86setcc) (X86setcc))
24610 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24611 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24612                                            X86::CondCode &CC1, SDValue &Flags,
24613                                            bool &isAnd) {
24614   if (Cond->getOpcode() == X86ISD::CMP) {
24615     if (!isNullConstant(Cond->getOperand(1)))
24616       return false;
24617
24618     Cond = Cond->getOperand(0);
24619   }
24620
24621   isAnd = false;
24622
24623   SDValue SetCC0, SetCC1;
24624   switch (Cond->getOpcode()) {
24625   default: return false;
24626   case ISD::AND:
24627   case X86ISD::AND:
24628     isAnd = true;
24629     // fallthru
24630   case ISD::OR:
24631   case X86ISD::OR:
24632     SetCC0 = Cond->getOperand(0);
24633     SetCC1 = Cond->getOperand(1);
24634     break;
24635   };
24636
24637   // Make sure we have SETCC nodes, using the same flags value.
24638   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24639       SetCC1.getOpcode() != X86ISD::SETCC ||
24640       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24641     return false;
24642
24643   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24644   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24645   Flags = SetCC0->getOperand(1);
24646   return true;
24647 }
24648
24649 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24650 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24651                                   TargetLowering::DAGCombinerInfo &DCI,
24652                                   const X86Subtarget *Subtarget) {
24653   SDLoc DL(N);
24654
24655   // If the flag operand isn't dead, don't touch this CMOV.
24656   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24657     return SDValue();
24658
24659   SDValue FalseOp = N->getOperand(0);
24660   SDValue TrueOp = N->getOperand(1);
24661   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24662   SDValue Cond = N->getOperand(3);
24663
24664   if (CC == X86::COND_E || CC == X86::COND_NE) {
24665     switch (Cond.getOpcode()) {
24666     default: break;
24667     case X86ISD::BSR:
24668     case X86ISD::BSF:
24669       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24670       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24671         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24672     }
24673   }
24674
24675   SDValue Flags;
24676
24677   Flags = checkBoolTestSetCCCombine(Cond, CC);
24678   if (Flags.getNode() &&
24679       // Extra check as FCMOV only supports a subset of X86 cond.
24680       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24681     SDValue Ops[] = { FalseOp, TrueOp,
24682                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24683     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24684   }
24685
24686   // If this is a select between two integer constants, try to do some
24687   // optimizations.  Note that the operands are ordered the opposite of SELECT
24688   // operands.
24689   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24690     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24691       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24692       // larger than FalseC (the false value).
24693       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24694         CC = X86::GetOppositeBranchCondition(CC);
24695         std::swap(TrueC, FalseC);
24696         std::swap(TrueOp, FalseOp);
24697       }
24698
24699       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24700       // This is efficient for any integer data type (including i8/i16) and
24701       // shift amount.
24702       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24703         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24704                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24705
24706         // Zero extend the condition if needed.
24707         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24708
24709         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24710         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24711                            DAG.getConstant(ShAmt, DL, MVT::i8));
24712         if (N->getNumValues() == 2)  // Dead flag value?
24713           return DCI.CombineTo(N, Cond, SDValue());
24714         return Cond;
24715       }
24716
24717       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24718       // for any integer data type, including i8/i16.
24719       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24720         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24721                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24722
24723         // Zero extend the condition if needed.
24724         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24725                            FalseC->getValueType(0), Cond);
24726         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24727                            SDValue(FalseC, 0));
24728
24729         if (N->getNumValues() == 2)  // Dead flag value?
24730           return DCI.CombineTo(N, Cond, SDValue());
24731         return Cond;
24732       }
24733
24734       // Optimize cases that will turn into an LEA instruction.  This requires
24735       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24736       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24737         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24738         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24739
24740         bool isFastMultiplier = false;
24741         if (Diff < 10) {
24742           switch ((unsigned char)Diff) {
24743           default: break;
24744           case 1:  // result = add base, cond
24745           case 2:  // result = lea base(    , cond*2)
24746           case 3:  // result = lea base(cond, cond*2)
24747           case 4:  // result = lea base(    , cond*4)
24748           case 5:  // result = lea base(cond, cond*4)
24749           case 8:  // result = lea base(    , cond*8)
24750           case 9:  // result = lea base(cond, cond*8)
24751             isFastMultiplier = true;
24752             break;
24753           }
24754         }
24755
24756         if (isFastMultiplier) {
24757           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24758           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24759                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24760           // Zero extend the condition if needed.
24761           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24762                              Cond);
24763           // Scale the condition by the difference.
24764           if (Diff != 1)
24765             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24766                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24767
24768           // Add the base if non-zero.
24769           if (FalseC->getAPIntValue() != 0)
24770             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24771                                SDValue(FalseC, 0));
24772           if (N->getNumValues() == 2)  // Dead flag value?
24773             return DCI.CombineTo(N, Cond, SDValue());
24774           return Cond;
24775         }
24776       }
24777     }
24778   }
24779
24780   // Handle these cases:
24781   //   (select (x != c), e, c) -> select (x != c), e, x),
24782   //   (select (x == c), c, e) -> select (x == c), x, e)
24783   // where the c is an integer constant, and the "select" is the combination
24784   // of CMOV and CMP.
24785   //
24786   // The rationale for this change is that the conditional-move from a constant
24787   // needs two instructions, however, conditional-move from a register needs
24788   // only one instruction.
24789   //
24790   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24791   //  some instruction-combining opportunities. This opt needs to be
24792   //  postponed as late as possible.
24793   //
24794   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24795     // the DCI.xxxx conditions are provided to postpone the optimization as
24796     // late as possible.
24797
24798     ConstantSDNode *CmpAgainst = nullptr;
24799     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24800         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24801         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24802
24803       if (CC == X86::COND_NE &&
24804           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24805         CC = X86::GetOppositeBranchCondition(CC);
24806         std::swap(TrueOp, FalseOp);
24807       }
24808
24809       if (CC == X86::COND_E &&
24810           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24811         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24812                           DAG.getConstant(CC, DL, MVT::i8), Cond };
24813         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24814       }
24815     }
24816   }
24817
24818   // Fold and/or of setcc's to double CMOV:
24819   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24820   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24821   //
24822   // This combine lets us generate:
24823   //   cmovcc1 (jcc1 if we don't have CMOV)
24824   //   cmovcc2 (same)
24825   // instead of:
24826   //   setcc1
24827   //   setcc2
24828   //   and/or
24829   //   cmovne (jne if we don't have CMOV)
24830   // When we can't use the CMOV instruction, it might increase branch
24831   // mispredicts.
24832   // When we can use CMOV, or when there is no mispredict, this improves
24833   // throughput and reduces register pressure.
24834   //
24835   if (CC == X86::COND_NE) {
24836     SDValue Flags;
24837     X86::CondCode CC0, CC1;
24838     bool isAndSetCC;
24839     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24840       if (isAndSetCC) {
24841         std::swap(FalseOp, TrueOp);
24842         CC0 = X86::GetOppositeBranchCondition(CC0);
24843         CC1 = X86::GetOppositeBranchCondition(CC1);
24844       }
24845
24846       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24847         Flags};
24848       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24849       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24850       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24851       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24852       return CMOV;
24853     }
24854   }
24855
24856   return SDValue();
24857 }
24858
24859 /// PerformMulCombine - Optimize a single multiply with constant into two
24860 /// in order to implement it with two cheaper instructions, e.g.
24861 /// LEA + SHL, LEA + LEA.
24862 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24863                                  TargetLowering::DAGCombinerInfo &DCI) {
24864   // An imul is usually smaller than the alternative sequence.
24865   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24866     return SDValue();
24867
24868   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24869     return SDValue();
24870
24871   EVT VT = N->getValueType(0);
24872   if (VT != MVT::i64 && VT != MVT::i32)
24873     return SDValue();
24874
24875   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24876   if (!C)
24877     return SDValue();
24878   uint64_t MulAmt = C->getZExtValue();
24879   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24880     return SDValue();
24881
24882   uint64_t MulAmt1 = 0;
24883   uint64_t MulAmt2 = 0;
24884   if ((MulAmt % 9) == 0) {
24885     MulAmt1 = 9;
24886     MulAmt2 = MulAmt / 9;
24887   } else if ((MulAmt % 5) == 0) {
24888     MulAmt1 = 5;
24889     MulAmt2 = MulAmt / 5;
24890   } else if ((MulAmt % 3) == 0) {
24891     MulAmt1 = 3;
24892     MulAmt2 = MulAmt / 3;
24893   }
24894
24895   SDLoc DL(N);
24896   SDValue NewMul;
24897   if (MulAmt2 &&
24898       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24899
24900     if (isPowerOf2_64(MulAmt2) &&
24901         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24902       // If second multiplifer is pow2, issue it first. We want the multiply by
24903       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24904       // is an add.
24905       std::swap(MulAmt1, MulAmt2);
24906
24907     if (isPowerOf2_64(MulAmt1))
24908       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24909                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24910     else
24911       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24912                            DAG.getConstant(MulAmt1, DL, VT));
24913
24914     if (isPowerOf2_64(MulAmt2))
24915       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24916                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24917     else
24918       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24919                            DAG.getConstant(MulAmt2, DL, VT));
24920   }
24921
24922   if (!NewMul) {
24923     assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
24924            && "Both cases that could cause potential overflows should have "
24925               "already been handled.");
24926     if (isPowerOf2_64(MulAmt - 1))
24927       // (mul x, 2^N + 1) => (add (shl x, N), x)
24928       NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
24929                                 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24930                                 DAG.getConstant(Log2_64(MulAmt - 1), DL,
24931                                 MVT::i8)));
24932
24933     else if (isPowerOf2_64(MulAmt + 1))
24934       // (mul x, 2^N - 1) => (sub (shl x, N), x)
24935       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
24936                                 N->getOperand(0),
24937                                 DAG.getConstant(Log2_64(MulAmt + 1),
24938                                 DL, MVT::i8)), N->getOperand(0));
24939   }
24940
24941   if (NewMul)
24942     // Do not add new nodes to DAG combiner worklist.
24943     DCI.CombineTo(N, NewMul, false);
24944
24945   return SDValue();
24946 }
24947
24948 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24949   SDValue N0 = N->getOperand(0);
24950   SDValue N1 = N->getOperand(1);
24951   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24952   EVT VT = N0.getValueType();
24953
24954   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24955   // since the result of setcc_c is all zero's or all ones.
24956   if (VT.isInteger() && !VT.isVector() &&
24957       N1C && N0.getOpcode() == ISD::AND &&
24958       N0.getOperand(1).getOpcode() == ISD::Constant) {
24959     SDValue N00 = N0.getOperand(0);
24960     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24961     APInt ShAmt = N1C->getAPIntValue();
24962     Mask = Mask.shl(ShAmt);
24963     bool MaskOK = false;
24964     // We can handle cases concerning bit-widening nodes containing setcc_c if
24965     // we carefully interrogate the mask to make sure we are semantics
24966     // preserving.
24967     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24968     // of the underlying setcc_c operation if the setcc_c was zero extended.
24969     // Consider the following example:
24970     //   zext(setcc_c)                 -> i32 0x0000FFFF
24971     //   c1                            -> i32 0x0000FFFF
24972     //   c2                            -> i32 0x00000001
24973     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24974     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24975     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24976       MaskOK = true;
24977     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24978                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24979       MaskOK = true;
24980     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24981                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24982                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24983       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24984     }
24985     if (MaskOK && Mask != 0) {
24986       SDLoc DL(N);
24987       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24988     }
24989   }
24990
24991   // Hardware support for vector shifts is sparse which makes us scalarize the
24992   // vector operations in many cases. Also, on sandybridge ADD is faster than
24993   // shl.
24994   // (shl V, 1) -> add V,V
24995   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24996     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24997       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24998       // We shift all of the values by one. In many cases we do not have
24999       // hardware support for this operation. This is better expressed as an ADD
25000       // of two values.
25001       if (N1SplatC->getAPIntValue() == 1)
25002         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25003     }
25004
25005   return SDValue();
25006 }
25007
25008 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25009   SDValue N0 = N->getOperand(0);
25010   SDValue N1 = N->getOperand(1);
25011   EVT VT = N0.getValueType();
25012   unsigned Size = VT.getSizeInBits();
25013
25014   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25015   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25016   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25017   // depending on sign of (SarConst - [56,48,32,24,16])
25018
25019   // sexts in X86 are MOVs. The MOVs have the same code size
25020   // as above SHIFTs (only SHIFT on 1 has lower code size).
25021   // However the MOVs have 2 advantages to a SHIFT:
25022   // 1. MOVs can write to a register that differs from source
25023   // 2. MOVs accept memory operands
25024
25025   if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25026       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25027       N0.getOperand(1).getOpcode() != ISD::Constant)
25028     return SDValue();
25029
25030   SDValue N00 = N0.getOperand(0);
25031   SDValue N01 = N0.getOperand(1);
25032   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25033   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25034   EVT CVT = N1.getValueType();
25035
25036   if (SarConst.isNegative())
25037     return SDValue();
25038
25039   for (MVT SVT : MVT::integer_valuetypes()) {
25040     unsigned ShiftSize = SVT.getSizeInBits();
25041     // skipping types without corresponding sext/zext and
25042     // ShlConst that is not one of [56,48,32,24,16]
25043     if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25044       continue;
25045     SDLoc DL(N);
25046     SDValue NN =
25047         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25048     SarConst = SarConst - (Size - ShiftSize);
25049     if (SarConst == 0)
25050       return NN;
25051     else if (SarConst.isNegative())
25052       return DAG.getNode(ISD::SHL, DL, VT, NN,
25053                          DAG.getConstant(-SarConst, DL, CVT));
25054     else
25055       return DAG.getNode(ISD::SRA, DL, VT, NN,
25056                          DAG.getConstant(SarConst, DL, CVT));
25057   }
25058   return SDValue();
25059 }
25060
25061 /// \brief Returns a vector of 0s if the node in input is a vector logical
25062 /// shift by a constant amount which is known to be bigger than or equal
25063 /// to the vector element size in bits.
25064 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25065                                       const X86Subtarget *Subtarget) {
25066   EVT VT = N->getValueType(0);
25067
25068   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25069       (!Subtarget->hasInt256() ||
25070        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25071     return SDValue();
25072
25073   SDValue Amt = N->getOperand(1);
25074   SDLoc DL(N);
25075   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25076     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25077       APInt ShiftAmt = AmtSplat->getAPIntValue();
25078       unsigned MaxAmount =
25079         VT.getSimpleVT().getVectorElementType().getSizeInBits();
25080
25081       // SSE2/AVX2 logical shifts always return a vector of 0s
25082       // if the shift amount is bigger than or equal to
25083       // the element size. The constant shift amount will be
25084       // encoded as a 8-bit immediate.
25085       if (ShiftAmt.trunc(8).uge(MaxAmount))
25086         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25087     }
25088
25089   return SDValue();
25090 }
25091
25092 /// PerformShiftCombine - Combine shifts.
25093 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25094                                    TargetLowering::DAGCombinerInfo &DCI,
25095                                    const X86Subtarget *Subtarget) {
25096   if (N->getOpcode() == ISD::SHL)
25097     if (SDValue V = PerformSHLCombine(N, DAG))
25098       return V;
25099
25100   if (N->getOpcode() == ISD::SRA)
25101     if (SDValue V = PerformSRACombine(N, DAG))
25102       return V;
25103
25104   // Try to fold this logical shift into a zero vector.
25105   if (N->getOpcode() != ISD::SRA)
25106     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25107       return V;
25108
25109   return SDValue();
25110 }
25111
25112 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
25113 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25114 // and friends.  Likewise for OR -> CMPNEQSS.
25115 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25116                             TargetLowering::DAGCombinerInfo &DCI,
25117                             const X86Subtarget *Subtarget) {
25118   unsigned opcode;
25119
25120   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25121   // we're requiring SSE2 for both.
25122   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25123     SDValue N0 = N->getOperand(0);
25124     SDValue N1 = N->getOperand(1);
25125     SDValue CMP0 = N0->getOperand(1);
25126     SDValue CMP1 = N1->getOperand(1);
25127     SDLoc DL(N);
25128
25129     // The SETCCs should both refer to the same CMP.
25130     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25131       return SDValue();
25132
25133     SDValue CMP00 = CMP0->getOperand(0);
25134     SDValue CMP01 = CMP0->getOperand(1);
25135     EVT     VT    = CMP00.getValueType();
25136
25137     if (VT == MVT::f32 || VT == MVT::f64) {
25138       bool ExpectingFlags = false;
25139       // Check for any users that want flags:
25140       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25141            !ExpectingFlags && UI != UE; ++UI)
25142         switch (UI->getOpcode()) {
25143         default:
25144         case ISD::BR_CC:
25145         case ISD::BRCOND:
25146         case ISD::SELECT:
25147           ExpectingFlags = true;
25148           break;
25149         case ISD::CopyToReg:
25150         case ISD::SIGN_EXTEND:
25151         case ISD::ZERO_EXTEND:
25152         case ISD::ANY_EXTEND:
25153           break;
25154         }
25155
25156       if (!ExpectingFlags) {
25157         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25158         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25159
25160         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25161           X86::CondCode tmp = cc0;
25162           cc0 = cc1;
25163           cc1 = tmp;
25164         }
25165
25166         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
25167             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25168           // FIXME: need symbolic constants for these magic numbers.
25169           // See X86ATTInstPrinter.cpp:printSSECC().
25170           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25171           if (Subtarget->hasAVX512()) {
25172             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25173                                          CMP01,
25174                                          DAG.getConstant(x86cc, DL, MVT::i8));
25175             if (N->getValueType(0) != MVT::i1)
25176               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25177                                  FSetCC);
25178             return FSetCC;
25179           }
25180           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25181                                               CMP00.getValueType(), CMP00, CMP01,
25182                                               DAG.getConstant(x86cc, DL,
25183                                                               MVT::i8));
25184
25185           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25186           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25187
25188           if (is64BitFP && !Subtarget->is64Bit()) {
25189             // On a 32-bit target, we cannot bitcast the 64-bit float to a
25190             // 64-bit integer, since that's not a legal type. Since
25191             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25192             // bits, but can do this little dance to extract the lowest 32 bits
25193             // and work with those going forward.
25194             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25195                                            OnesOrZeroesF);
25196             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25197             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25198                                         Vector32, DAG.getIntPtrConstant(0, DL));
25199             IntVT = MVT::i32;
25200           }
25201
25202           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25203           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25204                                       DAG.getConstant(1, DL, IntVT));
25205           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25206                                               ANDed);
25207           return OneBitOfTruth;
25208         }
25209       }
25210     }
25211   }
25212   return SDValue();
25213 }
25214
25215 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25216 /// so it can be folded inside ANDNP.
25217 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25218   EVT VT = N->getValueType(0);
25219
25220   // Match direct AllOnes for 128 and 256-bit vectors
25221   if (ISD::isBuildVectorAllOnes(N))
25222     return true;
25223
25224   // Look through a bit convert.
25225   if (N->getOpcode() == ISD::BITCAST)
25226     N = N->getOperand(0).getNode();
25227
25228   // Sometimes the operand may come from a insert_subvector building a 256-bit
25229   // allones vector
25230   if (VT.is256BitVector() &&
25231       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25232     SDValue V1 = N->getOperand(0);
25233     SDValue V2 = N->getOperand(1);
25234
25235     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25236         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25237         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25238         ISD::isBuildVectorAllOnes(V2.getNode()))
25239       return true;
25240   }
25241
25242   return false;
25243 }
25244
25245 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25246 // register. In most cases we actually compare or select YMM-sized registers
25247 // and mixing the two types creates horrible code. This method optimizes
25248 // some of the transition sequences.
25249 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25250                                  TargetLowering::DAGCombinerInfo &DCI,
25251                                  const X86Subtarget *Subtarget) {
25252   EVT VT = N->getValueType(0);
25253   if (!VT.is256BitVector())
25254     return SDValue();
25255
25256   assert((N->getOpcode() == ISD::ANY_EXTEND ||
25257           N->getOpcode() == ISD::ZERO_EXTEND ||
25258           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25259
25260   SDValue Narrow = N->getOperand(0);
25261   EVT NarrowVT = Narrow->getValueType(0);
25262   if (!NarrowVT.is128BitVector())
25263     return SDValue();
25264
25265   if (Narrow->getOpcode() != ISD::XOR &&
25266       Narrow->getOpcode() != ISD::AND &&
25267       Narrow->getOpcode() != ISD::OR)
25268     return SDValue();
25269
25270   SDValue N0  = Narrow->getOperand(0);
25271   SDValue N1  = Narrow->getOperand(1);
25272   SDLoc DL(Narrow);
25273
25274   // The Left side has to be a trunc.
25275   if (N0.getOpcode() != ISD::TRUNCATE)
25276     return SDValue();
25277
25278   // The type of the truncated inputs.
25279   EVT WideVT = N0->getOperand(0)->getValueType(0);
25280   if (WideVT != VT)
25281     return SDValue();
25282
25283   // The right side has to be a 'trunc' or a constant vector.
25284   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25285   ConstantSDNode *RHSConstSplat = nullptr;
25286   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25287     RHSConstSplat = RHSBV->getConstantSplatNode();
25288   if (!RHSTrunc && !RHSConstSplat)
25289     return SDValue();
25290
25291   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25292
25293   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25294     return SDValue();
25295
25296   // Set N0 and N1 to hold the inputs to the new wide operation.
25297   N0 = N0->getOperand(0);
25298   if (RHSConstSplat) {
25299     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25300                      SDValue(RHSConstSplat, 0));
25301     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25302     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25303   } else if (RHSTrunc) {
25304     N1 = N1->getOperand(0);
25305   }
25306
25307   // Generate the wide operation.
25308   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25309   unsigned Opcode = N->getOpcode();
25310   switch (Opcode) {
25311   case ISD::ANY_EXTEND:
25312     return Op;
25313   case ISD::ZERO_EXTEND: {
25314     unsigned InBits = NarrowVT.getScalarSizeInBits();
25315     APInt Mask = APInt::getAllOnesValue(InBits);
25316     Mask = Mask.zext(VT.getScalarSizeInBits());
25317     return DAG.getNode(ISD::AND, DL, VT,
25318                        Op, DAG.getConstant(Mask, DL, VT));
25319   }
25320   case ISD::SIGN_EXTEND:
25321     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25322                        Op, DAG.getValueType(NarrowVT));
25323   default:
25324     llvm_unreachable("Unexpected opcode");
25325   }
25326 }
25327
25328 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25329                                  TargetLowering::DAGCombinerInfo &DCI,
25330                                  const X86Subtarget *Subtarget) {
25331   SDValue N0 = N->getOperand(0);
25332   SDValue N1 = N->getOperand(1);
25333   SDLoc DL(N);
25334
25335   // A vector zext_in_reg may be represented as a shuffle,
25336   // feeding into a bitcast (this represents anyext) feeding into
25337   // an and with a mask.
25338   // We'd like to try to combine that into a shuffle with zero
25339   // plus a bitcast, removing the and.
25340   if (N0.getOpcode() != ISD::BITCAST ||
25341       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25342     return SDValue();
25343
25344   // The other side of the AND should be a splat of 2^C, where C
25345   // is the number of bits in the source type.
25346   if (N1.getOpcode() == ISD::BITCAST)
25347     N1 = N1.getOperand(0);
25348   if (N1.getOpcode() != ISD::BUILD_VECTOR)
25349     return SDValue();
25350   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25351
25352   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25353   EVT SrcType = Shuffle->getValueType(0);
25354
25355   // We expect a single-source shuffle
25356   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25357     return SDValue();
25358
25359   unsigned SrcSize = SrcType.getScalarSizeInBits();
25360
25361   APInt SplatValue, SplatUndef;
25362   unsigned SplatBitSize;
25363   bool HasAnyUndefs;
25364   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25365                                 SplatBitSize, HasAnyUndefs))
25366     return SDValue();
25367
25368   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25369   // Make sure the splat matches the mask we expect
25370   if (SplatBitSize > ResSize ||
25371       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25372     return SDValue();
25373
25374   // Make sure the input and output size make sense
25375   if (SrcSize >= ResSize || ResSize % SrcSize)
25376     return SDValue();
25377
25378   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25379   // The number of u's between each two values depends on the ratio between
25380   // the source and dest type.
25381   unsigned ZextRatio = ResSize / SrcSize;
25382   bool IsZext = true;
25383   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25384     if (i % ZextRatio) {
25385       if (Shuffle->getMaskElt(i) > 0) {
25386         // Expected undef
25387         IsZext = false;
25388         break;
25389       }
25390     } else {
25391       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25392         // Expected element number
25393         IsZext = false;
25394         break;
25395       }
25396     }
25397   }
25398
25399   if (!IsZext)
25400     return SDValue();
25401
25402   // Ok, perform the transformation - replace the shuffle with
25403   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25404   // (instead of undef) where the k elements come from the zero vector.
25405   SmallVector<int, 8> Mask;
25406   unsigned NumElems = SrcType.getVectorNumElements();
25407   for (unsigned i = 0; i < NumElems; ++i)
25408     if (i % ZextRatio)
25409       Mask.push_back(NumElems);
25410     else
25411       Mask.push_back(i / ZextRatio);
25412
25413   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25414     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25415   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25416 }
25417
25418 /// If both input operands of a logic op are being cast from floating point
25419 /// types, try to convert this into a floating point logic node to avoid
25420 /// unnecessary moves from SSE to integer registers.
25421 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25422                                         const X86Subtarget *Subtarget) {
25423   unsigned FPOpcode = ISD::DELETED_NODE;
25424   if (N->getOpcode() == ISD::AND)
25425     FPOpcode = X86ISD::FAND;
25426   else if (N->getOpcode() == ISD::OR)
25427     FPOpcode = X86ISD::FOR;
25428   else if (N->getOpcode() == ISD::XOR)
25429     FPOpcode = X86ISD::FXOR;
25430
25431   assert(FPOpcode != ISD::DELETED_NODE &&
25432          "Unexpected input node for FP logic conversion");
25433
25434   EVT VT = N->getValueType(0);
25435   SDValue N0 = N->getOperand(0);
25436   SDValue N1 = N->getOperand(1);
25437   SDLoc DL(N);
25438   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25439       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25440        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25441     SDValue N00 = N0.getOperand(0);
25442     SDValue N10 = N1.getOperand(0);
25443     EVT N00Type = N00.getValueType();
25444     EVT N10Type = N10.getValueType();
25445     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25446       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25447       return DAG.getBitcast(VT, FPLogic);
25448     }
25449   }
25450   return SDValue();
25451 }
25452
25453 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25454                                  TargetLowering::DAGCombinerInfo &DCI,
25455                                  const X86Subtarget *Subtarget) {
25456   if (DCI.isBeforeLegalizeOps())
25457     return SDValue();
25458
25459   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25460     return Zext;
25461
25462   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25463     return R;
25464
25465   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25466     return FPLogic;
25467
25468   EVT VT = N->getValueType(0);
25469   SDValue N0 = N->getOperand(0);
25470   SDValue N1 = N->getOperand(1);
25471   SDLoc DL(N);
25472
25473   // Create BEXTR instructions
25474   // BEXTR is ((X >> imm) & (2**size-1))
25475   if (VT == MVT::i32 || VT == MVT::i64) {
25476     // Check for BEXTR.
25477     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25478         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25479       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25480       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25481       if (MaskNode && ShiftNode) {
25482         uint64_t Mask = MaskNode->getZExtValue();
25483         uint64_t Shift = ShiftNode->getZExtValue();
25484         if (isMask_64(Mask)) {
25485           uint64_t MaskSize = countPopulation(Mask);
25486           if (Shift + MaskSize <= VT.getSizeInBits())
25487             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25488                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25489                                                VT));
25490         }
25491       }
25492     } // BEXTR
25493
25494     return SDValue();
25495   }
25496
25497   // Want to form ANDNP nodes:
25498   // 1) In the hopes of then easily combining them with OR and AND nodes
25499   //    to form PBLEND/PSIGN.
25500   // 2) To match ANDN packed intrinsics
25501   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25502     return SDValue();
25503
25504   // Check LHS for vnot
25505   if (N0.getOpcode() == ISD::XOR &&
25506       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25507       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25508     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25509
25510   // Check RHS for vnot
25511   if (N1.getOpcode() == ISD::XOR &&
25512       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25513       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25514     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25515
25516   return SDValue();
25517 }
25518
25519 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25520                                 TargetLowering::DAGCombinerInfo &DCI,
25521                                 const X86Subtarget *Subtarget) {
25522   if (DCI.isBeforeLegalizeOps())
25523     return SDValue();
25524
25525   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25526     return R;
25527
25528   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25529     return FPLogic;
25530
25531   SDValue N0 = N->getOperand(0);
25532   SDValue N1 = N->getOperand(1);
25533   EVT VT = N->getValueType(0);
25534
25535   // look for psign/blend
25536   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25537     if (!Subtarget->hasSSSE3() ||
25538         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25539       return SDValue();
25540
25541     // Canonicalize pandn to RHS
25542     if (N0.getOpcode() == X86ISD::ANDNP)
25543       std::swap(N0, N1);
25544     // or (and (m, y), (pandn m, x))
25545     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25546       SDValue Mask = N1.getOperand(0);
25547       SDValue X    = N1.getOperand(1);
25548       SDValue Y;
25549       if (N0.getOperand(0) == Mask)
25550         Y = N0.getOperand(1);
25551       if (N0.getOperand(1) == Mask)
25552         Y = N0.getOperand(0);
25553
25554       // Check to see if the mask appeared in both the AND and ANDNP and
25555       if (!Y.getNode())
25556         return SDValue();
25557
25558       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25559       // Look through mask bitcast.
25560       if (Mask.getOpcode() == ISD::BITCAST)
25561         Mask = Mask.getOperand(0);
25562       if (X.getOpcode() == ISD::BITCAST)
25563         X = X.getOperand(0);
25564       if (Y.getOpcode() == ISD::BITCAST)
25565         Y = Y.getOperand(0);
25566
25567       EVT MaskVT = Mask.getValueType();
25568
25569       // Validate that the Mask operand is a vector sra node.
25570       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25571       // there is no psrai.b
25572       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25573       unsigned SraAmt = ~0;
25574       if (Mask.getOpcode() == ISD::SRA) {
25575         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25576           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25577             SraAmt = AmtConst->getZExtValue();
25578       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25579         SDValue SraC = Mask.getOperand(1);
25580         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25581       }
25582       if ((SraAmt + 1) != EltBits)
25583         return SDValue();
25584
25585       SDLoc DL(N);
25586
25587       // Now we know we at least have a plendvb with the mask val.  See if
25588       // we can form a psignb/w/d.
25589       // psign = x.type == y.type == mask.type && y = sub(0, x);
25590       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25591           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25592           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25593         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25594                "Unsupported VT for PSIGN");
25595         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25596         return DAG.getBitcast(VT, Mask);
25597       }
25598       // PBLENDVB only available on SSE 4.1
25599       if (!Subtarget->hasSSE41())
25600         return SDValue();
25601
25602       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25603
25604       X = DAG.getBitcast(BlendVT, X);
25605       Y = DAG.getBitcast(BlendVT, Y);
25606       Mask = DAG.getBitcast(BlendVT, Mask);
25607       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25608       return DAG.getBitcast(VT, Mask);
25609     }
25610   }
25611
25612   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25613     return SDValue();
25614
25615   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25616   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25617
25618   // SHLD/SHRD instructions have lower register pressure, but on some
25619   // platforms they have higher latency than the equivalent
25620   // series of shifts/or that would otherwise be generated.
25621   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25622   // have higher latencies and we are not optimizing for size.
25623   if (!OptForSize && Subtarget->isSHLDSlow())
25624     return SDValue();
25625
25626   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25627     std::swap(N0, N1);
25628   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25629     return SDValue();
25630   if (!N0.hasOneUse() || !N1.hasOneUse())
25631     return SDValue();
25632
25633   SDValue ShAmt0 = N0.getOperand(1);
25634   if (ShAmt0.getValueType() != MVT::i8)
25635     return SDValue();
25636   SDValue ShAmt1 = N1.getOperand(1);
25637   if (ShAmt1.getValueType() != MVT::i8)
25638     return SDValue();
25639   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25640     ShAmt0 = ShAmt0.getOperand(0);
25641   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25642     ShAmt1 = ShAmt1.getOperand(0);
25643
25644   SDLoc DL(N);
25645   unsigned Opc = X86ISD::SHLD;
25646   SDValue Op0 = N0.getOperand(0);
25647   SDValue Op1 = N1.getOperand(0);
25648   if (ShAmt0.getOpcode() == ISD::SUB) {
25649     Opc = X86ISD::SHRD;
25650     std::swap(Op0, Op1);
25651     std::swap(ShAmt0, ShAmt1);
25652   }
25653
25654   unsigned Bits = VT.getSizeInBits();
25655   if (ShAmt1.getOpcode() == ISD::SUB) {
25656     SDValue Sum = ShAmt1.getOperand(0);
25657     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25658       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25659       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25660         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25661       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25662         return DAG.getNode(Opc, DL, VT,
25663                            Op0, Op1,
25664                            DAG.getNode(ISD::TRUNCATE, DL,
25665                                        MVT::i8, ShAmt0));
25666     }
25667   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25668     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25669     if (ShAmt0C &&
25670         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25671       return DAG.getNode(Opc, DL, VT,
25672                          N0.getOperand(0), N1.getOperand(0),
25673                          DAG.getNode(ISD::TRUNCATE, DL,
25674                                        MVT::i8, ShAmt0));
25675   }
25676
25677   return SDValue();
25678 }
25679
25680 // Generate NEG and CMOV for integer abs.
25681 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25682   EVT VT = N->getValueType(0);
25683
25684   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25685   // 8-bit integer abs to NEG and CMOV.
25686   if (VT.isInteger() && VT.getSizeInBits() == 8)
25687     return SDValue();
25688
25689   SDValue N0 = N->getOperand(0);
25690   SDValue N1 = N->getOperand(1);
25691   SDLoc DL(N);
25692
25693   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25694   // and change it to SUB and CMOV.
25695   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25696       N0.getOpcode() == ISD::ADD &&
25697       N0.getOperand(1) == N1 &&
25698       N1.getOpcode() == ISD::SRA &&
25699       N1.getOperand(0) == N0.getOperand(0))
25700     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25701       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25702         // Generate SUB & CMOV.
25703         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25704                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25705
25706         SDValue Ops[] = { N0.getOperand(0), Neg,
25707                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25708                           SDValue(Neg.getNode(), 1) };
25709         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25710       }
25711   return SDValue();
25712 }
25713
25714 // Try to turn tests against the signbit in the form of:
25715 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25716 // into:
25717 //   SETGT(X, -1)
25718 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25719   // This is only worth doing if the output type is i8.
25720   if (N->getValueType(0) != MVT::i8)
25721     return SDValue();
25722
25723   SDValue N0 = N->getOperand(0);
25724   SDValue N1 = N->getOperand(1);
25725
25726   // We should be performing an xor against a truncated shift.
25727   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25728     return SDValue();
25729
25730   // Make sure we are performing an xor against one.
25731   if (!isOneConstant(N1))
25732     return SDValue();
25733
25734   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25735   SDValue Shift = N0.getOperand(0);
25736   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25737     return SDValue();
25738
25739   // Make sure we are truncating from one of i16, i32 or i64.
25740   EVT ShiftTy = Shift.getValueType();
25741   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25742     return SDValue();
25743
25744   // Make sure the shift amount extracts the sign bit.
25745   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25746       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25747     return SDValue();
25748
25749   // Create a greater-than comparison against -1.
25750   // N.B. Using SETGE against 0 works but we want a canonical looking
25751   // comparison, using SETGT matches up with what TranslateX86CC.
25752   SDLoc DL(N);
25753   SDValue ShiftOp = Shift.getOperand(0);
25754   EVT ShiftOpTy = ShiftOp.getValueType();
25755   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25756                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25757   return Cond;
25758 }
25759
25760 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25761                                  TargetLowering::DAGCombinerInfo &DCI,
25762                                  const X86Subtarget *Subtarget) {
25763   if (DCI.isBeforeLegalizeOps())
25764     return SDValue();
25765
25766   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25767     return RV;
25768
25769   if (Subtarget->hasCMov())
25770     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25771       return RV;
25772
25773   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25774     return FPLogic;
25775
25776   return SDValue();
25777 }
25778
25779 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
25780 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
25781 /// X86ISD::AVG instruction.
25782 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
25783                                 const X86Subtarget *Subtarget, SDLoc DL) {
25784   if (!VT.isVector() || !VT.isSimple())
25785     return SDValue();
25786   EVT InVT = In.getValueType();
25787   unsigned NumElems = VT.getVectorNumElements();
25788
25789   EVT ScalarVT = VT.getVectorElementType();
25790   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
25791         isPowerOf2_32(NumElems)))
25792     return SDValue();
25793
25794   // InScalarVT is the intermediate type in AVG pattern and it should be greater
25795   // than the original input type (i8/i16).
25796   EVT InScalarVT = InVT.getVectorElementType();
25797   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
25798     return SDValue();
25799
25800   if (Subtarget->hasAVX512()) {
25801     if (VT.getSizeInBits() > 512)
25802       return SDValue();
25803   } else if (Subtarget->hasAVX2()) {
25804     if (VT.getSizeInBits() > 256)
25805       return SDValue();
25806   } else {
25807     if (VT.getSizeInBits() > 128)
25808       return SDValue();
25809   }
25810
25811   // Detect the following pattern:
25812   //
25813   //   %1 = zext <N x i8> %a to <N x i32>
25814   //   %2 = zext <N x i8> %b to <N x i32>
25815   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
25816   //   %4 = add nuw nsw <N x i32> %3, %2
25817   //   %5 = lshr <N x i32> %N, <i32 1 x N>
25818   //   %6 = trunc <N x i32> %5 to <N x i8>
25819   //
25820   // In AVX512, the last instruction can also be a trunc store.
25821
25822   if (In.getOpcode() != ISD::SRL)
25823     return SDValue();
25824
25825   // A lambda checking the given SDValue is a constant vector and each element
25826   // is in the range [Min, Max].
25827   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
25828     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
25829     if (!BV || !BV->isConstant())
25830       return false;
25831     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
25832       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
25833       if (!C)
25834         return false;
25835       uint64_t Val = C->getZExtValue();
25836       if (Val < Min || Val > Max)
25837         return false;
25838     }
25839     return true;
25840   };
25841
25842   // Check if each element of the vector is left-shifted by one.
25843   auto LHS = In.getOperand(0);
25844   auto RHS = In.getOperand(1);
25845   if (!IsConstVectorInRange(RHS, 1, 1))
25846     return SDValue();
25847   if (LHS.getOpcode() != ISD::ADD)
25848     return SDValue();
25849
25850   // Detect a pattern of a + b + 1 where the order doesn't matter.
25851   SDValue Operands[3];
25852   Operands[0] = LHS.getOperand(0);
25853   Operands[1] = LHS.getOperand(1);
25854
25855   // Take care of the case when one of the operands is a constant vector whose
25856   // element is in the range [1, 256].
25857   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
25858       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
25859       Operands[0].getOperand(0).getValueType() == VT) {
25860     // The pattern is detected. Subtract one from the constant vector, then
25861     // demote it and emit X86ISD::AVG instruction.
25862     SDValue One = DAG.getConstant(1, DL, InScalarVT);
25863     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
25864                                SmallVector<SDValue, 8>(NumElems, One));
25865     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
25866     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
25867     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
25868                        Operands[1]);
25869   }
25870
25871   if (Operands[0].getOpcode() == ISD::ADD)
25872     std::swap(Operands[0], Operands[1]);
25873   else if (Operands[1].getOpcode() != ISD::ADD)
25874     return SDValue();
25875   Operands[2] = Operands[1].getOperand(0);
25876   Operands[1] = Operands[1].getOperand(1);
25877
25878   // Now we have three operands of two additions. Check that one of them is a
25879   // constant vector with ones, and the other two are promoted from i8/i16.
25880   for (int i = 0; i < 3; ++i) {
25881     if (!IsConstVectorInRange(Operands[i], 1, 1))
25882       continue;
25883     std::swap(Operands[i], Operands[2]);
25884
25885     // Check if Operands[0] and Operands[1] are results of type promotion.
25886     for (int j = 0; j < 2; ++j)
25887       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
25888           Operands[j].getOperand(0).getValueType() != VT)
25889         return SDValue();
25890
25891     // The pattern is detected, emit X86ISD::AVG instruction.
25892     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
25893                        Operands[1].getOperand(0));
25894   }
25895
25896   return SDValue();
25897 }
25898
25899 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25900 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25901                                   TargetLowering::DAGCombinerInfo &DCI,
25902                                   const X86Subtarget *Subtarget) {
25903   LoadSDNode *Ld = cast<LoadSDNode>(N);
25904   EVT RegVT = Ld->getValueType(0);
25905   EVT MemVT = Ld->getMemoryVT();
25906   SDLoc dl(Ld);
25907   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25908
25909   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25910   // into two 16-byte operations.
25911   ISD::LoadExtType Ext = Ld->getExtensionType();
25912   bool Fast;
25913   unsigned AddressSpace = Ld->getAddressSpace();
25914   unsigned Alignment = Ld->getAlignment();
25915   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25916       Ext == ISD::NON_EXTLOAD &&
25917       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25918                              AddressSpace, Alignment, &Fast) && !Fast) {
25919     unsigned NumElems = RegVT.getVectorNumElements();
25920     if (NumElems < 2)
25921       return SDValue();
25922
25923     SDValue Ptr = Ld->getBasePtr();
25924     SDValue Increment =
25925         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25926
25927     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25928                                   NumElems/2);
25929     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25930                                 Ld->getPointerInfo(), Ld->isVolatile(),
25931                                 Ld->isNonTemporal(), Ld->isInvariant(),
25932                                 Alignment);
25933     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25934     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25935                                 Ld->getPointerInfo(), Ld->isVolatile(),
25936                                 Ld->isNonTemporal(), Ld->isInvariant(),
25937                                 std::min(16U, Alignment));
25938     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25939                              Load1.getValue(1),
25940                              Load2.getValue(1));
25941
25942     SDValue NewVec = DAG.getUNDEF(RegVT);
25943     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25944     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25945     return DCI.CombineTo(N, NewVec, TF, true);
25946   }
25947
25948   return SDValue();
25949 }
25950
25951 /// PerformMLOADCombine - Resolve extending loads
25952 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25953                                    TargetLowering::DAGCombinerInfo &DCI,
25954                                    const X86Subtarget *Subtarget) {
25955   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25956   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25957     return SDValue();
25958
25959   EVT VT = Mld->getValueType(0);
25960   unsigned NumElems = VT.getVectorNumElements();
25961   EVT LdVT = Mld->getMemoryVT();
25962   SDLoc dl(Mld);
25963
25964   assert(LdVT != VT && "Cannot extend to the same type");
25965   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25966   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25967   // From, To sizes and ElemCount must be pow of two
25968   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25969     "Unexpected size for extending masked load");
25970
25971   unsigned SizeRatio  = ToSz / FromSz;
25972   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25973
25974   // Create a type on which we perform the shuffle
25975   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25976           LdVT.getScalarType(), NumElems*SizeRatio);
25977   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25978
25979   // Convert Src0 value
25980   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25981   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25982     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25983     for (unsigned i = 0; i != NumElems; ++i)
25984       ShuffleVec[i] = i * SizeRatio;
25985
25986     // Can't shuffle using an illegal type.
25987     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25988            "WideVecVT should be legal");
25989     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25990                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25991   }
25992   // Prepare the new mask
25993   SDValue NewMask;
25994   SDValue Mask = Mld->getMask();
25995   if (Mask.getValueType() == VT) {
25996     // Mask and original value have the same type
25997     NewMask = DAG.getBitcast(WideVecVT, Mask);
25998     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25999     for (unsigned i = 0; i != NumElems; ++i)
26000       ShuffleVec[i] = i * SizeRatio;
26001     for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26002       ShuffleVec[i] = NumElems * SizeRatio;
26003     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26004                                    DAG.getConstant(0, dl, WideVecVT),
26005                                    &ShuffleVec[0]);
26006   }
26007   else {
26008     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26009     unsigned WidenNumElts = NumElems*SizeRatio;
26010     unsigned MaskNumElts = VT.getVectorNumElements();
26011     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26012                                      WidenNumElts);
26013
26014     unsigned NumConcat = WidenNumElts / MaskNumElts;
26015     SmallVector<SDValue, 16> Ops(NumConcat);
26016     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26017     Ops[0] = Mask;
26018     for (unsigned i = 1; i != NumConcat; ++i)
26019       Ops[i] = ZeroVal;
26020
26021     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26022   }
26023
26024   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26025                                      Mld->getBasePtr(), NewMask, WideSrc0,
26026                                      Mld->getMemoryVT(), Mld->getMemOperand(),
26027                                      ISD::NON_EXTLOAD);
26028   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26029   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26030 }
26031 /// PerformMSTORECombine - Resolve truncating stores
26032 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26033                                     const X86Subtarget *Subtarget) {
26034   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26035   if (!Mst->isTruncatingStore())
26036     return SDValue();
26037
26038   EVT VT = Mst->getValue().getValueType();
26039   unsigned NumElems = VT.getVectorNumElements();
26040   EVT StVT = Mst->getMemoryVT();
26041   SDLoc dl(Mst);
26042
26043   assert(StVT != VT && "Cannot truncate to the same type");
26044   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26045   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26046
26047   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26048
26049   // The truncating store is legal in some cases. For example
26050   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26051   // are designated for truncate store.
26052   // In this case we don't need any further transformations.
26053   if (TLI.isTruncStoreLegal(VT, StVT))
26054     return SDValue();
26055
26056   // From, To sizes and ElemCount must be pow of two
26057   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26058     "Unexpected size for truncating masked store");
26059   // We are going to use the original vector elt for storing.
26060   // Accumulated smaller vector elements must be a multiple of the store size.
26061   assert (((NumElems * FromSz) % ToSz) == 0 &&
26062           "Unexpected ratio for truncating masked store");
26063
26064   unsigned SizeRatio  = FromSz / ToSz;
26065   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26066
26067   // Create a type on which we perform the shuffle
26068   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26069           StVT.getScalarType(), NumElems*SizeRatio);
26070
26071   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26072
26073   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26074   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26075   for (unsigned i = 0; i != NumElems; ++i)
26076     ShuffleVec[i] = i * SizeRatio;
26077
26078   // Can't shuffle using an illegal type.
26079   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26080          "WideVecVT should be legal");
26081
26082   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26083                                               DAG.getUNDEF(WideVecVT),
26084                                               &ShuffleVec[0]);
26085
26086   SDValue NewMask;
26087   SDValue Mask = Mst->getMask();
26088   if (Mask.getValueType() == VT) {
26089     // Mask and original value have the same type
26090     NewMask = DAG.getBitcast(WideVecVT, Mask);
26091     for (unsigned i = 0; i != NumElems; ++i)
26092       ShuffleVec[i] = i * SizeRatio;
26093     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26094       ShuffleVec[i] = NumElems*SizeRatio;
26095     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26096                                    DAG.getConstant(0, dl, WideVecVT),
26097                                    &ShuffleVec[0]);
26098   }
26099   else {
26100     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26101     unsigned WidenNumElts = NumElems*SizeRatio;
26102     unsigned MaskNumElts = VT.getVectorNumElements();
26103     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
26104                                      WidenNumElts);
26105
26106     unsigned NumConcat = WidenNumElts / MaskNumElts;
26107     SmallVector<SDValue, 16> Ops(NumConcat);
26108     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26109     Ops[0] = Mask;
26110     for (unsigned i = 1; i != NumConcat; ++i)
26111       Ops[i] = ZeroVal;
26112
26113     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26114   }
26115
26116   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26117                             Mst->getBasePtr(), NewMask, StVT,
26118                             Mst->getMemOperand(), false);
26119 }
26120 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26121 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26122                                    const X86Subtarget *Subtarget) {
26123   StoreSDNode *St = cast<StoreSDNode>(N);
26124   EVT VT = St->getValue().getValueType();
26125   EVT StVT = St->getMemoryVT();
26126   SDLoc dl(St);
26127   SDValue StoredVal = St->getOperand(1);
26128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26129
26130   // If we are saving a concatenation of two XMM registers and 32-byte stores
26131   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26132   bool Fast;
26133   unsigned AddressSpace = St->getAddressSpace();
26134   unsigned Alignment = St->getAlignment();
26135   if (VT.is256BitVector() && StVT == VT &&
26136       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26137                              AddressSpace, Alignment, &Fast) && !Fast) {
26138     unsigned NumElems = VT.getVectorNumElements();
26139     if (NumElems < 2)
26140       return SDValue();
26141
26142     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26143     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26144
26145     SDValue Stride =
26146         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26147     SDValue Ptr0 = St->getBasePtr();
26148     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26149
26150     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26151                                 St->getPointerInfo(), St->isVolatile(),
26152                                 St->isNonTemporal(), Alignment);
26153     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26154                                 St->getPointerInfo(), St->isVolatile(),
26155                                 St->isNonTemporal(),
26156                                 std::min(16U, Alignment));
26157     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26158   }
26159
26160   // Optimize trunc store (of multiple scalars) to shuffle and store.
26161   // First, pack all of the elements in one place. Next, store to memory
26162   // in fewer chunks.
26163   if (St->isTruncatingStore() && VT.isVector()) {
26164     // Check if we can detect an AVG pattern from the truncation. If yes,
26165     // replace the trunc store by a normal store with the result of X86ISD::AVG
26166     // instruction.
26167     SDValue Avg =
26168         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26169     if (Avg.getNode())
26170       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26171                           St->getPointerInfo(), St->isVolatile(),
26172                           St->isNonTemporal(), St->getAlignment());
26173
26174     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26175     unsigned NumElems = VT.getVectorNumElements();
26176     assert(StVT != VT && "Cannot truncate to the same type");
26177     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26178     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26179
26180     // The truncating store is legal in some cases. For example
26181     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26182     // are designated for truncate store.
26183     // In this case we don't need any further transformations.
26184     if (TLI.isTruncStoreLegal(VT, StVT))
26185       return SDValue();
26186
26187     // From, To sizes and ElemCount must be pow of two
26188     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26189     // We are going to use the original vector elt for storing.
26190     // Accumulated smaller vector elements must be a multiple of the store size.
26191     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26192
26193     unsigned SizeRatio  = FromSz / ToSz;
26194
26195     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26196
26197     // Create a type on which we perform the shuffle
26198     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26199             StVT.getScalarType(), NumElems*SizeRatio);
26200
26201     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26202
26203     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26204     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26205     for (unsigned i = 0; i != NumElems; ++i)
26206       ShuffleVec[i] = i * SizeRatio;
26207
26208     // Can't shuffle using an illegal type.
26209     if (!TLI.isTypeLegal(WideVecVT))
26210       return SDValue();
26211
26212     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26213                                          DAG.getUNDEF(WideVecVT),
26214                                          &ShuffleVec[0]);
26215     // At this point all of the data is stored at the bottom of the
26216     // register. We now need to save it to mem.
26217
26218     // Find the largest store unit
26219     MVT StoreType = MVT::i8;
26220     for (MVT Tp : MVT::integer_valuetypes()) {
26221       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26222         StoreType = Tp;
26223     }
26224
26225     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26226     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26227         (64 <= NumElems * ToSz))
26228       StoreType = MVT::f64;
26229
26230     // Bitcast the original vector into a vector of store-size units
26231     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26232             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26233     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26234     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26235     SmallVector<SDValue, 8> Chains;
26236     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26237                                         TLI.getPointerTy(DAG.getDataLayout()));
26238     SDValue Ptr = St->getBasePtr();
26239
26240     // Perform one or more big stores into memory.
26241     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26242       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26243                                    StoreType, ShuffWide,
26244                                    DAG.getIntPtrConstant(i, dl));
26245       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26246                                 St->getPointerInfo(), St->isVolatile(),
26247                                 St->isNonTemporal(), St->getAlignment());
26248       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26249       Chains.push_back(Ch);
26250     }
26251
26252     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26253   }
26254
26255   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
26256   // the FP state in cases where an emms may be missing.
26257   // A preferable solution to the general problem is to figure out the right
26258   // places to insert EMMS.  This qualifies as a quick hack.
26259
26260   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26261   if (VT.getSizeInBits() != 64)
26262     return SDValue();
26263
26264   const Function *F = DAG.getMachineFunction().getFunction();
26265   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26266   bool F64IsLegal =
26267       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26268   if ((VT.isVector() ||
26269        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26270       isa<LoadSDNode>(St->getValue()) &&
26271       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26272       St->getChain().hasOneUse() && !St->isVolatile()) {
26273     SDNode* LdVal = St->getValue().getNode();
26274     LoadSDNode *Ld = nullptr;
26275     int TokenFactorIndex = -1;
26276     SmallVector<SDValue, 8> Ops;
26277     SDNode* ChainVal = St->getChain().getNode();
26278     // Must be a store of a load.  We currently handle two cases:  the load
26279     // is a direct child, and it's under an intervening TokenFactor.  It is
26280     // possible to dig deeper under nested TokenFactors.
26281     if (ChainVal == LdVal)
26282       Ld = cast<LoadSDNode>(St->getChain());
26283     else if (St->getValue().hasOneUse() &&
26284              ChainVal->getOpcode() == ISD::TokenFactor) {
26285       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26286         if (ChainVal->getOperand(i).getNode() == LdVal) {
26287           TokenFactorIndex = i;
26288           Ld = cast<LoadSDNode>(St->getValue());
26289         } else
26290           Ops.push_back(ChainVal->getOperand(i));
26291       }
26292     }
26293
26294     if (!Ld || !ISD::isNormalLoad(Ld))
26295       return SDValue();
26296
26297     // If this is not the MMX case, i.e. we are just turning i64 load/store
26298     // into f64 load/store, avoid the transformation if there are multiple
26299     // uses of the loaded value.
26300     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26301       return SDValue();
26302
26303     SDLoc LdDL(Ld);
26304     SDLoc StDL(N);
26305     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26306     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26307     // pair instead.
26308     if (Subtarget->is64Bit() || F64IsLegal) {
26309       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26310       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26311                                   Ld->getPointerInfo(), Ld->isVolatile(),
26312                                   Ld->isNonTemporal(), Ld->isInvariant(),
26313                                   Ld->getAlignment());
26314       SDValue NewChain = NewLd.getValue(1);
26315       if (TokenFactorIndex != -1) {
26316         Ops.push_back(NewChain);
26317         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26318       }
26319       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26320                           St->getPointerInfo(),
26321                           St->isVolatile(), St->isNonTemporal(),
26322                           St->getAlignment());
26323     }
26324
26325     // Otherwise, lower to two pairs of 32-bit loads / stores.
26326     SDValue LoAddr = Ld->getBasePtr();
26327     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26328                                  DAG.getConstant(4, LdDL, MVT::i32));
26329
26330     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26331                                Ld->getPointerInfo(),
26332                                Ld->isVolatile(), Ld->isNonTemporal(),
26333                                Ld->isInvariant(), Ld->getAlignment());
26334     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26335                                Ld->getPointerInfo().getWithOffset(4),
26336                                Ld->isVolatile(), Ld->isNonTemporal(),
26337                                Ld->isInvariant(),
26338                                MinAlign(Ld->getAlignment(), 4));
26339
26340     SDValue NewChain = LoLd.getValue(1);
26341     if (TokenFactorIndex != -1) {
26342       Ops.push_back(LoLd);
26343       Ops.push_back(HiLd);
26344       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26345     }
26346
26347     LoAddr = St->getBasePtr();
26348     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26349                          DAG.getConstant(4, StDL, MVT::i32));
26350
26351     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26352                                 St->getPointerInfo(),
26353                                 St->isVolatile(), St->isNonTemporal(),
26354                                 St->getAlignment());
26355     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26356                                 St->getPointerInfo().getWithOffset(4),
26357                                 St->isVolatile(),
26358                                 St->isNonTemporal(),
26359                                 MinAlign(St->getAlignment(), 4));
26360     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26361   }
26362
26363   // This is similar to the above case, but here we handle a scalar 64-bit
26364   // integer store that is extracted from a vector on a 32-bit target.
26365   // If we have SSE2, then we can treat it like a floating-point double
26366   // to get past legalization. The execution dependencies fixup pass will
26367   // choose the optimal machine instruction for the store if this really is
26368   // an integer or v2f32 rather than an f64.
26369   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26370       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26371     SDValue OldExtract = St->getOperand(1);
26372     SDValue ExtOp0 = OldExtract.getOperand(0);
26373     unsigned VecSize = ExtOp0.getValueSizeInBits();
26374     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26375     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26376     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26377                                      BitCast, OldExtract.getOperand(1));
26378     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26379                         St->getPointerInfo(), St->isVolatile(),
26380                         St->isNonTemporal(), St->getAlignment());
26381   }
26382
26383   return SDValue();
26384 }
26385
26386 /// Return 'true' if this vector operation is "horizontal"
26387 /// and return the operands for the horizontal operation in LHS and RHS.  A
26388 /// horizontal operation performs the binary operation on successive elements
26389 /// of its first operand, then on successive elements of its second operand,
26390 /// returning the resulting values in a vector.  For example, if
26391 ///   A = < float a0, float a1, float a2, float a3 >
26392 /// and
26393 ///   B = < float b0, float b1, float b2, float b3 >
26394 /// then the result of doing a horizontal operation on A and B is
26395 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26396 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26397 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26398 /// set to A, RHS to B, and the routine returns 'true'.
26399 /// Note that the binary operation should have the property that if one of the
26400 /// operands is UNDEF then the result is UNDEF.
26401 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26402   // Look for the following pattern: if
26403   //   A = < float a0, float a1, float a2, float a3 >
26404   //   B = < float b0, float b1, float b2, float b3 >
26405   // and
26406   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26407   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26408   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26409   // which is A horizontal-op B.
26410
26411   // At least one of the operands should be a vector shuffle.
26412   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26413       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26414     return false;
26415
26416   MVT VT = LHS.getSimpleValueType();
26417
26418   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26419          "Unsupported vector type for horizontal add/sub");
26420
26421   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26422   // operate independently on 128-bit lanes.
26423   unsigned NumElts = VT.getVectorNumElements();
26424   unsigned NumLanes = VT.getSizeInBits()/128;
26425   unsigned NumLaneElts = NumElts / NumLanes;
26426   assert((NumLaneElts % 2 == 0) &&
26427          "Vector type should have an even number of elements in each lane");
26428   unsigned HalfLaneElts = NumLaneElts/2;
26429
26430   // View LHS in the form
26431   //   LHS = VECTOR_SHUFFLE A, B, LMask
26432   // If LHS is not a shuffle then pretend it is the shuffle
26433   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26434   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26435   // type VT.
26436   SDValue A, B;
26437   SmallVector<int, 16> LMask(NumElts);
26438   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26439     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26440       A = LHS.getOperand(0);
26441     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26442       B = LHS.getOperand(1);
26443     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26444     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26445   } else {
26446     if (LHS.getOpcode() != ISD::UNDEF)
26447       A = LHS;
26448     for (unsigned i = 0; i != NumElts; ++i)
26449       LMask[i] = i;
26450   }
26451
26452   // Likewise, view RHS in the form
26453   //   RHS = VECTOR_SHUFFLE C, D, RMask
26454   SDValue C, D;
26455   SmallVector<int, 16> RMask(NumElts);
26456   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26457     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26458       C = RHS.getOperand(0);
26459     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26460       D = RHS.getOperand(1);
26461     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26462     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26463   } else {
26464     if (RHS.getOpcode() != ISD::UNDEF)
26465       C = RHS;
26466     for (unsigned i = 0; i != NumElts; ++i)
26467       RMask[i] = i;
26468   }
26469
26470   // Check that the shuffles are both shuffling the same vectors.
26471   if (!(A == C && B == D) && !(A == D && B == C))
26472     return false;
26473
26474   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26475   if (!A.getNode() && !B.getNode())
26476     return false;
26477
26478   // If A and B occur in reverse order in RHS, then "swap" them (which means
26479   // rewriting the mask).
26480   if (A != C)
26481     ShuffleVectorSDNode::commuteMask(RMask);
26482
26483   // At this point LHS and RHS are equivalent to
26484   //   LHS = VECTOR_SHUFFLE A, B, LMask
26485   //   RHS = VECTOR_SHUFFLE A, B, RMask
26486   // Check that the masks correspond to performing a horizontal operation.
26487   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26488     for (unsigned i = 0; i != NumLaneElts; ++i) {
26489       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26490
26491       // Ignore any UNDEF components.
26492       if (LIdx < 0 || RIdx < 0 ||
26493           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26494           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26495         continue;
26496
26497       // Check that successive elements are being operated on.  If not, this is
26498       // not a horizontal operation.
26499       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26500       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26501       if (!(LIdx == Index && RIdx == Index + 1) &&
26502           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26503         return false;
26504     }
26505   }
26506
26507   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26508   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26509   return true;
26510 }
26511
26512 /// Do target-specific dag combines on floating point adds.
26513 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26514                                   const X86Subtarget *Subtarget) {
26515   EVT VT = N->getValueType(0);
26516   SDValue LHS = N->getOperand(0);
26517   SDValue RHS = N->getOperand(1);
26518
26519   // Try to synthesize horizontal adds from adds of shuffles.
26520   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26521        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26522       isHorizontalBinOp(LHS, RHS, true))
26523     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26524   return SDValue();
26525 }
26526
26527 /// Do target-specific dag combines on floating point subs.
26528 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26529                                   const X86Subtarget *Subtarget) {
26530   EVT VT = N->getValueType(0);
26531   SDValue LHS = N->getOperand(0);
26532   SDValue RHS = N->getOperand(1);
26533
26534   // Try to synthesize horizontal subs from subs of shuffles.
26535   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26536        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26537       isHorizontalBinOp(LHS, RHS, false))
26538     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26539   return SDValue();
26540 }
26541
26542 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26543 static SDValue
26544 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26545                                   SmallVector<SDValue, 8> &Regs) {
26546   assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26547                              Regs[0].getValueType() == MVT::v2i64));
26548   EVT OutVT = N->getValueType(0);
26549   EVT OutSVT = OutVT.getVectorElementType();
26550   EVT InVT = Regs[0].getValueType();
26551   EVT InSVT = InVT.getVectorElementType();
26552   SDLoc DL(N);
26553
26554   // First, use mask to unset all bits that won't appear in the result.
26555   assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26556          "OutSVT can only be either i8 or i16.");
26557   SDValue MaskVal =
26558       DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26559   SDValue MaskVec = DAG.getNode(
26560       ISD::BUILD_VECTOR, DL, InVT,
26561       SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26562   for (auto &Reg : Regs)
26563     Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26564
26565   MVT UnpackedVT, PackedVT;
26566   if (OutSVT == MVT::i8) {
26567     UnpackedVT = MVT::v8i16;
26568     PackedVT = MVT::v16i8;
26569   } else {
26570     UnpackedVT = MVT::v4i32;
26571     PackedVT = MVT::v8i16;
26572   }
26573
26574   // In each iteration, truncate the type by a half size.
26575   auto RegNum = Regs.size();
26576   for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26577        j < e; j *= 2, RegNum /= 2) {
26578     for (unsigned i = 0; i < RegNum; i++)
26579       Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26580     for (unsigned i = 0; i < RegNum / 2; i++)
26581       Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26582                             Regs[i * 2 + 1]);
26583   }
26584
26585   // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26586   // then extract a subvector as the result since v8i8 is not a legal type.
26587   if (OutVT == MVT::v8i8) {
26588     Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26589     Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26590                           DAG.getIntPtrConstant(0, DL));
26591     return Regs[0];
26592   } else if (RegNum > 1) {
26593     Regs.resize(RegNum);
26594     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26595   } else
26596     return Regs[0];
26597 }
26598
26599 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26600 static SDValue
26601 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26602                                   SmallVector<SDValue, 8> &Regs) {
26603   assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26604   EVT OutVT = N->getValueType(0);
26605   SDLoc DL(N);
26606
26607   // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26608   SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26609   for (auto &Reg : Regs) {
26610     Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26611     Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26612   }
26613
26614   for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26615     Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26616                           Regs[i * 2 + 1]);
26617
26618   if (Regs.size() > 2) {
26619     Regs.resize(Regs.size() / 2);
26620     return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26621   } else
26622     return Regs[0];
26623 }
26624
26625 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26626 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26627 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26628 /// element that is extracted from a vector and then truncated, and it is
26629 /// diffcult to do this optimization based on them.
26630 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26631                                        const X86Subtarget *Subtarget) {
26632   EVT OutVT = N->getValueType(0);
26633   if (!OutVT.isVector())
26634     return SDValue();
26635
26636   SDValue In = N->getOperand(0);
26637   if (!In.getValueType().isSimple())
26638     return SDValue();
26639
26640   EVT InVT = In.getValueType();
26641   unsigned NumElems = OutVT.getVectorNumElements();
26642
26643   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26644   // SSE2, and we need to take care of it specially.
26645   // AVX512 provides vpmovdb.
26646   if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26647     return SDValue();
26648
26649   EVT OutSVT = OutVT.getVectorElementType();
26650   EVT InSVT = InVT.getVectorElementType();
26651   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26652         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26653         NumElems >= 8))
26654     return SDValue();
26655
26656   // SSSE3's pshufb results in less instructions in the cases below.
26657   if (Subtarget->hasSSSE3() && NumElems == 8 &&
26658       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26659        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26660     return SDValue();
26661
26662   SDLoc DL(N);
26663
26664   // Split a long vector into vectors of legal type.
26665   unsigned RegNum = InVT.getSizeInBits() / 128;
26666   SmallVector<SDValue, 8> SubVec(RegNum);
26667   if (InSVT == MVT::i32) {
26668     for (unsigned i = 0; i < RegNum; i++)
26669       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26670                               DAG.getIntPtrConstant(i * 4, DL));
26671   } else {
26672     for (unsigned i = 0; i < RegNum; i++)
26673       SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
26674                               DAG.getIntPtrConstant(i * 2, DL));
26675   }
26676
26677   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
26678   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
26679   // truncate 2 x v4i32 to v8i16.
26680   if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
26681     return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
26682   else if (InSVT == MVT::i32)
26683     return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
26684   else
26685     return SDValue();
26686 }
26687
26688 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
26689                                       const X86Subtarget *Subtarget) {
26690   // Try to detect AVG pattern first.
26691   SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
26692                                  Subtarget, SDLoc(N));
26693   if (Avg.getNode())
26694     return Avg;
26695
26696   return combineVectorTruncation(N, DAG, Subtarget);
26697 }
26698
26699 /// Do target-specific dag combines on floating point negations.
26700 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26701                                   const X86Subtarget *Subtarget) {
26702   EVT VT = N->getValueType(0);
26703   EVT SVT = VT.getScalarType();
26704   SDValue Arg = N->getOperand(0);
26705   SDLoc DL(N);
26706
26707   // Let legalize expand this if it isn't a legal type yet.
26708   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26709     return SDValue();
26710
26711   // If we're negating a FMUL node on a target with FMA, then we can avoid the
26712   // use of a constant by performing (-0 - A*B) instead.
26713   // FIXME: Check rounding control flags as well once it becomes available. 
26714   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
26715       Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
26716     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
26717     return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26718                        Arg.getOperand(1), Zero);
26719   }
26720
26721   // If we're negating a FMA node, then we can adjust the
26722   // instruction to include the extra negation.
26723   if (Arg.hasOneUse()) {
26724     switch (Arg.getOpcode()) {
26725     case X86ISD::FMADD:
26726       return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26727                          Arg.getOperand(1), Arg.getOperand(2));
26728     case X86ISD::FMSUB:
26729       return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
26730                          Arg.getOperand(1), Arg.getOperand(2));
26731     case X86ISD::FNMADD:
26732       return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
26733                          Arg.getOperand(1), Arg.getOperand(2));
26734     case X86ISD::FNMSUB:
26735       return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
26736                          Arg.getOperand(1), Arg.getOperand(2));
26737     }
26738   }
26739   return SDValue();
26740 }
26741
26742 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
26743                               const X86Subtarget *Subtarget) {
26744   EVT VT = N->getValueType(0);
26745   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
26746     // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
26747     // These logic operations may be executed in the integer domain.
26748     SDLoc dl(N);
26749     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
26750     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
26751
26752     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
26753     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
26754     unsigned IntOpcode = 0;
26755     switch (N->getOpcode()) {
26756       default: llvm_unreachable("Unexpected FP logic op");
26757       case X86ISD::FOR: IntOpcode = ISD::OR; break;
26758       case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
26759       case X86ISD::FAND: IntOpcode = ISD::AND; break;
26760       case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
26761     }
26762     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
26763     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
26764   }
26765   return SDValue();
26766 }
26767 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
26768 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
26769                                  const X86Subtarget *Subtarget) {
26770   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
26771
26772   // F[X]OR(0.0, x) -> x
26773   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26774     if (C->getValueAPF().isPosZero())
26775       return N->getOperand(1);
26776
26777   // F[X]OR(x, 0.0) -> x
26778   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26779     if (C->getValueAPF().isPosZero())
26780       return N->getOperand(0);
26781
26782   return lowerX86FPLogicOp(N, DAG, Subtarget);
26783 }
26784
26785 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
26786 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
26787   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
26788
26789   // Only perform optimizations if UnsafeMath is used.
26790   if (!DAG.getTarget().Options.UnsafeFPMath)
26791     return SDValue();
26792
26793   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
26794   // into FMINC and FMAXC, which are Commutative operations.
26795   unsigned NewOp = 0;
26796   switch (N->getOpcode()) {
26797     default: llvm_unreachable("unknown opcode");
26798     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
26799     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
26800   }
26801
26802   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
26803                      N->getOperand(0), N->getOperand(1));
26804 }
26805
26806 static SDValue performFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
26807                                      const X86Subtarget *Subtarget) {
26808   // This takes at least 3 instructions, so favor a library call when
26809   // minimizing code size.
26810   if (DAG.getMachineFunction().getFunction()->optForMinSize())
26811     return SDValue();
26812
26813   EVT VT = N->getValueType(0);
26814
26815   // TODO: Check for global or instruction-level "nnan". In that case, we
26816   //       should be able to lower to FMAX/FMIN alone.
26817   // TODO: If an operand is already known to be a NaN or not a NaN, this
26818   //       should be an optional swap and FMAX/FMIN.
26819   // TODO: Allow f64, vectors, and fminnum.
26820
26821   if (VT != MVT::f32 || !Subtarget->hasSSE1() || Subtarget->useSoftFloat())
26822     return SDValue();
26823
26824   SDValue Op0 = N->getOperand(0);
26825   SDValue Op1 = N->getOperand(1);
26826   SDLoc DL(N);
26827   EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
26828       DAG.getDataLayout(), *DAG.getContext(), VT);
26829
26830   // There are 4 possibilities involving NaN inputs, and these are the required
26831   // outputs:
26832   //                   Op1
26833   //               Num     NaN
26834   //            ----------------
26835   //       Num  |  Max  |  Op0 |
26836   // Op0        ----------------
26837   //       NaN  |  Op1  |  NaN |
26838   //            ----------------
26839   //
26840   // The SSE FP max/min instructions were not designed for this case, but rather
26841   // to implement:
26842   //   Max = Op1 > Op0 ? Op1 : Op0
26843   //
26844   // So they always return Op0 if either input is a NaN. However, we can still
26845   // use those instructions for fmaxnum by selecting away a NaN input.
26846
26847   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
26848   SDValue Max = DAG.getNode(X86ISD::FMAX, DL, VT, Op1, Op0);
26849   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
26850
26851   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
26852   // are NaN, the NaN value of Op1 is the result.
26853   return DAG.getNode(ISD::SELECT, DL, VT, IsOp0Nan, Op1, Max);
26854 }
26855
26856 /// Do target-specific dag combines on X86ISD::FAND nodes.
26857 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
26858                                   const X86Subtarget *Subtarget) {
26859   // FAND(0.0, x) -> 0.0
26860   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26861     if (C->getValueAPF().isPosZero())
26862       return N->getOperand(0);
26863
26864   // FAND(x, 0.0) -> 0.0
26865   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26866     if (C->getValueAPF().isPosZero())
26867       return N->getOperand(1);
26868
26869   return lowerX86FPLogicOp(N, DAG, Subtarget);
26870 }
26871
26872 /// Do target-specific dag combines on X86ISD::FANDN nodes
26873 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
26874                                    const X86Subtarget *Subtarget) {
26875   // FANDN(0.0, x) -> x
26876   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26877     if (C->getValueAPF().isPosZero())
26878       return N->getOperand(1);
26879
26880   // FANDN(x, 0.0) -> 0.0
26881   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26882     if (C->getValueAPF().isPosZero())
26883       return N->getOperand(1);
26884
26885   return lowerX86FPLogicOp(N, DAG, Subtarget);
26886 }
26887
26888 static SDValue PerformBTCombine(SDNode *N,
26889                                 SelectionDAG &DAG,
26890                                 TargetLowering::DAGCombinerInfo &DCI) {
26891   // BT ignores high bits in the bit index operand.
26892   SDValue Op1 = N->getOperand(1);
26893   if (Op1.hasOneUse()) {
26894     unsigned BitWidth = Op1.getValueSizeInBits();
26895     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
26896     APInt KnownZero, KnownOne;
26897     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
26898                                           !DCI.isBeforeLegalizeOps());
26899     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26900     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
26901         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
26902       DCI.CommitTargetLoweringOpt(TLO);
26903   }
26904   return SDValue();
26905 }
26906
26907 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
26908   SDValue Op = N->getOperand(0);
26909   if (Op.getOpcode() == ISD::BITCAST)
26910     Op = Op.getOperand(0);
26911   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
26912   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
26913       VT.getVectorElementType().getSizeInBits() ==
26914       OpVT.getVectorElementType().getSizeInBits()) {
26915     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
26916   }
26917   return SDValue();
26918 }
26919
26920 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
26921                                                const X86Subtarget *Subtarget) {
26922   EVT VT = N->getValueType(0);
26923   if (!VT.isVector())
26924     return SDValue();
26925
26926   SDValue N0 = N->getOperand(0);
26927   SDValue N1 = N->getOperand(1);
26928   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
26929   SDLoc dl(N);
26930
26931   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
26932   // both SSE and AVX2 since there is no sign-extended shift right
26933   // operation on a vector with 64-bit elements.
26934   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
26935   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
26936   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
26937       N0.getOpcode() == ISD::SIGN_EXTEND)) {
26938     SDValue N00 = N0.getOperand(0);
26939
26940     // EXTLOAD has a better solution on AVX2,
26941     // it may be replaced with X86ISD::VSEXT node.
26942     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
26943       if (!ISD::isNormalLoad(N00.getNode()))
26944         return SDValue();
26945
26946     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
26947         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
26948                                   N00, N1);
26949       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
26950     }
26951   }
26952   return SDValue();
26953 }
26954
26955 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
26956 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
26957 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
26958 /// eliminate extend, add, and shift instructions.
26959 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
26960                                        const X86Subtarget *Subtarget) {
26961   // TODO: This should be valid for other integer types.
26962   EVT VT = Sext->getValueType(0);
26963   if (VT != MVT::i64)
26964     return SDValue();
26965
26966   // We need an 'add nsw' feeding into the 'sext'.
26967   SDValue Add = Sext->getOperand(0);
26968   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
26969     return SDValue();
26970
26971   // Having a constant operand to the 'add' ensures that we are not increasing
26972   // the instruction count because the constant is extended for free below.
26973   // A constant operand can also become the displacement field of an LEA.
26974   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
26975   if (!AddOp1)
26976     return SDValue();
26977
26978   // Don't make the 'add' bigger if there's no hope of combining it with some
26979   // other 'add' or 'shl' instruction.
26980   // TODO: It may be profitable to generate simpler LEA instructions in place
26981   // of single 'add' instructions, but the cost model for selecting an LEA
26982   // currently has a high threshold.
26983   bool HasLEAPotential = false;
26984   for (auto *User : Sext->uses()) {
26985     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
26986       HasLEAPotential = true;
26987       break;
26988     }
26989   }
26990   if (!HasLEAPotential)
26991     return SDValue();
26992
26993   // Everything looks good, so pull the 'sext' ahead of the 'add'.
26994   int64_t AddConstant = AddOp1->getSExtValue();
26995   SDValue AddOp0 = Add.getOperand(0);
26996   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
26997   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
26998
26999   // The wider add is guaranteed to not wrap because both operands are
27000   // sign-extended.
27001   SDNodeFlags Flags;
27002   Flags.setNoSignedWrap(true);
27003   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27004 }
27005
27006 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27007                                   TargetLowering::DAGCombinerInfo &DCI,
27008                                   const X86Subtarget *Subtarget) {
27009   SDValue N0 = N->getOperand(0);
27010   EVT VT = N->getValueType(0);
27011   EVT SVT = VT.getScalarType();
27012   EVT InVT = N0.getValueType();
27013   EVT InSVT = InVT.getScalarType();
27014   SDLoc DL(N);
27015
27016   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
27017   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
27018   // This exposes the sext to the sdivrem lowering, so that it directly extends
27019   // from AH (which we otherwise need to do contortions to access).
27020   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
27021       InVT == MVT::i8 && VT == MVT::i32) {
27022     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27023     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
27024                             N0.getOperand(0), N0.getOperand(1));
27025     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27026     return R.getValue(1);
27027   }
27028
27029   if (!DCI.isBeforeLegalizeOps()) {
27030     if (InVT == MVT::i1) {
27031       SDValue Zero = DAG.getConstant(0, DL, VT);
27032       SDValue AllOnes =
27033         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27034       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27035     }
27036     return SDValue();
27037   }
27038
27039   if (VT.isVector() && Subtarget->hasSSE2()) {
27040     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27041       EVT InVT = N.getValueType();
27042       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27043                                    Size / InVT.getScalarSizeInBits());
27044       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27045                                     DAG.getUNDEF(InVT));
27046       Opnds[0] = N;
27047       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27048     };
27049
27050     // If target-size is less than 128-bits, extend to a type that would extend
27051     // to 128 bits, extend that and extract the original target vector.
27052     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27053         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27054         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27055       unsigned Scale = 128 / VT.getSizeInBits();
27056       EVT ExVT =
27057           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27058       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27059       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27060       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27061                          DAG.getIntPtrConstant(0, DL));
27062     }
27063
27064     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27065     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27066     if (VT.getSizeInBits() == 128 &&
27067         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27068         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27069       SDValue ExOp = ExtendVecSize(DL, N0, 128);
27070       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27071     }
27072
27073     // On pre-AVX2 targets, split into 128-bit nodes of
27074     // ISD::SIGN_EXTEND_VECTOR_INREG.
27075     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27076         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27077         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27078       unsigned NumVecs = VT.getSizeInBits() / 128;
27079       unsigned NumSubElts = 128 / SVT.getSizeInBits();
27080       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27081       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27082
27083       SmallVector<SDValue, 8> Opnds;
27084       for (unsigned i = 0, Offset = 0; i != NumVecs;
27085            ++i, Offset += NumSubElts) {
27086         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27087                                      DAG.getIntPtrConstant(Offset, DL));
27088         SrcVec = ExtendVecSize(DL, SrcVec, 128);
27089         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27090         Opnds.push_back(SrcVec);
27091       }
27092       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27093     }
27094   }
27095
27096   if (Subtarget->hasAVX() && VT.is256BitVector())
27097     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27098       return R;
27099
27100   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27101     return NewAdd;
27102
27103   return SDValue();
27104 }
27105
27106 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27107                                  const X86Subtarget* Subtarget) {
27108   SDLoc dl(N);
27109   EVT VT = N->getValueType(0);
27110
27111   // Let legalize expand this if it isn't a legal type yet.
27112   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27113     return SDValue();
27114
27115   EVT ScalarVT = VT.getScalarType();
27116   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27117     return SDValue();
27118
27119   SDValue A = N->getOperand(0);
27120   SDValue B = N->getOperand(1);
27121   SDValue C = N->getOperand(2);
27122
27123   bool NegA = (A.getOpcode() == ISD::FNEG);
27124   bool NegB = (B.getOpcode() == ISD::FNEG);
27125   bool NegC = (C.getOpcode() == ISD::FNEG);
27126
27127   // Negative multiplication when NegA xor NegB
27128   bool NegMul = (NegA != NegB);
27129   if (NegA)
27130     A = A.getOperand(0);
27131   if (NegB)
27132     B = B.getOperand(0);
27133   if (NegC)
27134     C = C.getOperand(0);
27135
27136   unsigned Opcode;
27137   if (!NegMul)
27138     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27139   else
27140     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27141
27142   return DAG.getNode(Opcode, dl, VT, A, B, C);
27143 }
27144
27145 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27146                                   TargetLowering::DAGCombinerInfo &DCI,
27147                                   const X86Subtarget *Subtarget) {
27148   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
27149   //           (and (i32 x86isd::setcc_carry), 1)
27150   // This eliminates the zext. This transformation is necessary because
27151   // ISD::SETCC is always legalized to i8.
27152   SDLoc dl(N);
27153   SDValue N0 = N->getOperand(0);
27154   EVT VT = N->getValueType(0);
27155
27156   if (N0.getOpcode() == ISD::AND &&
27157       N0.hasOneUse() &&
27158       N0.getOperand(0).hasOneUse()) {
27159     SDValue N00 = N0.getOperand(0);
27160     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27161       if (!isOneConstant(N0.getOperand(1)))
27162         return SDValue();
27163       return DAG.getNode(ISD::AND, dl, VT,
27164                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27165                                      N00.getOperand(0), N00.getOperand(1)),
27166                          DAG.getConstant(1, dl, VT));
27167     }
27168   }
27169
27170   if (N0.getOpcode() == ISD::TRUNCATE &&
27171       N0.hasOneUse() &&
27172       N0.getOperand(0).hasOneUse()) {
27173     SDValue N00 = N0.getOperand(0);
27174     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27175       return DAG.getNode(ISD::AND, dl, VT,
27176                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27177                                      N00.getOperand(0), N00.getOperand(1)),
27178                          DAG.getConstant(1, dl, VT));
27179     }
27180   }
27181
27182   if (VT.is256BitVector())
27183     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27184       return R;
27185
27186   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
27187   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
27188   // This exposes the zext to the udivrem lowering, so that it directly extends
27189   // from AH (which we otherwise need to do contortions to access).
27190   if (N0.getOpcode() == ISD::UDIVREM &&
27191       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
27192       (VT == MVT::i32 || VT == MVT::i64)) {
27193     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27194     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
27195                             N0.getOperand(0), N0.getOperand(1));
27196     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27197     return R.getValue(1);
27198   }
27199
27200   return SDValue();
27201 }
27202
27203 // Optimize x == -y --> x+y == 0
27204 //          x != -y --> x+y != 0
27205 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27206                                       const X86Subtarget* Subtarget) {
27207   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27208   SDValue LHS = N->getOperand(0);
27209   SDValue RHS = N->getOperand(1);
27210   EVT VT = N->getValueType(0);
27211   SDLoc DL(N);
27212
27213   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27214     if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27215       SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27216                                  LHS.getOperand(1));
27217       return DAG.getSetCC(DL, N->getValueType(0), addV,
27218                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27219     }
27220   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27221     if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27222       SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27223                                  RHS.getOperand(1));
27224       return DAG.getSetCC(DL, N->getValueType(0), addV,
27225                           DAG.getConstant(0, DL, addV.getValueType()), CC);
27226     }
27227
27228   if (VT.getScalarType() == MVT::i1 &&
27229       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27230     bool IsSEXT0 =
27231         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27232         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27233     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27234
27235     if (!IsSEXT0 || !IsVZero1) {
27236       // Swap the operands and update the condition code.
27237       std::swap(LHS, RHS);
27238       CC = ISD::getSetCCSwappedOperands(CC);
27239
27240       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27241                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27242       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27243     }
27244
27245     if (IsSEXT0 && IsVZero1) {
27246       assert(VT == LHS.getOperand(0).getValueType() &&
27247              "Uexpected operand type");
27248       if (CC == ISD::SETGT)
27249         return DAG.getConstant(0, DL, VT);
27250       if (CC == ISD::SETLE)
27251         return DAG.getConstant(1, DL, VT);
27252       if (CC == ISD::SETEQ || CC == ISD::SETGE)
27253         return DAG.getNOT(DL, LHS.getOperand(0), VT);
27254
27255       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27256              "Unexpected condition code!");
27257       return LHS.getOperand(0);
27258     }
27259   }
27260
27261   return SDValue();
27262 }
27263
27264 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
27265   SDValue V0 = N->getOperand(0);
27266   SDValue V1 = N->getOperand(1);
27267   SDLoc DL(N);
27268   EVT VT = N->getValueType(0);
27269
27270   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
27271   // operands and changing the mask to 1. This saves us a bunch of
27272   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
27273   // x86InstrInfo knows how to commute this back after instruction selection
27274   // if it would help register allocation.
27275
27276   // TODO: If optimizing for size or a processor that doesn't suffer from
27277   // partial register update stalls, this should be transformed into a MOVSD
27278   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
27279
27280   if (VT == MVT::v2f64)
27281     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
27282       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
27283         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
27284         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
27285       }
27286
27287   return SDValue();
27288 }
27289
27290 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27291   SDLoc DL(N);
27292   // Gather and Scatter instructions use k-registers for masks. The type of
27293   // the masks is v*i1. So the mask will be truncated anyway.
27294   // The SIGN_EXTEND_INREG my be dropped.
27295   SDValue Mask = N->getOperand(2);
27296   if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27297     SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27298     NewOps[2] = Mask.getOperand(0);
27299     DAG.UpdateNodeOperands(N, NewOps);
27300   }
27301   return SDValue();
27302 }
27303
27304 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27305 // as "sbb reg,reg", since it can be extended without zext and produces
27306 // an all-ones bit which is more useful than 0/1 in some cases.
27307 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27308                                MVT VT) {
27309   if (VT == MVT::i8)
27310     return DAG.getNode(ISD::AND, DL, VT,
27311                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27312                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
27313                                    EFLAGS),
27314                        DAG.getConstant(1, DL, VT));
27315   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27316   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27317                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27318                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
27319                                  EFLAGS));
27320 }
27321
27322 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27323 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27324                                    TargetLowering::DAGCombinerInfo &DCI,
27325                                    const X86Subtarget *Subtarget) {
27326   SDLoc DL(N);
27327   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27328   SDValue EFLAGS = N->getOperand(1);
27329
27330   if (CC == X86::COND_A) {
27331     // Try to convert COND_A into COND_B in an attempt to facilitate
27332     // materializing "setb reg".
27333     //
27334     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27335     // cannot take an immediate as its first operand.
27336     //
27337     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27338         EFLAGS.getValueType().isInteger() &&
27339         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27340       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27341                                    EFLAGS.getNode()->getVTList(),
27342                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27343       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27344       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27345     }
27346   }
27347
27348   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27349   // a zext and produces an all-ones bit which is more useful than 0/1 in some
27350   // cases.
27351   if (CC == X86::COND_B)
27352     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27353
27354   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27355     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27356     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27357   }
27358
27359   return SDValue();
27360 }
27361
27362 // Optimize branch condition evaluation.
27363 //
27364 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27365                                     TargetLowering::DAGCombinerInfo &DCI,
27366                                     const X86Subtarget *Subtarget) {
27367   SDLoc DL(N);
27368   SDValue Chain = N->getOperand(0);
27369   SDValue Dest = N->getOperand(1);
27370   SDValue EFLAGS = N->getOperand(3);
27371   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27372
27373   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27374     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27375     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27376                        Flags);
27377   }
27378
27379   return SDValue();
27380 }
27381
27382 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27383                                                          SelectionDAG &DAG) {
27384   // Take advantage of vector comparisons producing 0 or -1 in each lane to
27385   // optimize away operation when it's from a constant.
27386   //
27387   // The general transformation is:
27388   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27389   //       AND(VECTOR_CMP(x,y), constant2)
27390   //    constant2 = UNARYOP(constant)
27391
27392   // Early exit if this isn't a vector operation, the operand of the
27393   // unary operation isn't a bitwise AND, or if the sizes of the operations
27394   // aren't the same.
27395   EVT VT = N->getValueType(0);
27396   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27397       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27398       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27399     return SDValue();
27400
27401   // Now check that the other operand of the AND is a constant. We could
27402   // make the transformation for non-constant splats as well, but it's unclear
27403   // that would be a benefit as it would not eliminate any operations, just
27404   // perform one more step in scalar code before moving to the vector unit.
27405   if (BuildVectorSDNode *BV =
27406           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27407     // Bail out if the vector isn't a constant.
27408     if (!BV->isConstant())
27409       return SDValue();
27410
27411     // Everything checks out. Build up the new and improved node.
27412     SDLoc DL(N);
27413     EVT IntVT = BV->getValueType(0);
27414     // Create a new constant of the appropriate type for the transformed
27415     // DAG.
27416     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27417     // The AND node needs bitcasts to/from an integer vector type around it.
27418     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27419     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27420                                  N->getOperand(0)->getOperand(0), MaskConst);
27421     SDValue Res = DAG.getBitcast(VT, NewAnd);
27422     return Res;
27423   }
27424
27425   return SDValue();
27426 }
27427
27428 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27429                                         const X86Subtarget *Subtarget) {
27430   SDValue Op0 = N->getOperand(0);
27431   EVT VT = N->getValueType(0);
27432   EVT InVT = Op0.getValueType();
27433   EVT InSVT = InVT.getScalarType();
27434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27435
27436   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27437   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27438   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27439     SDLoc dl(N);
27440     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27441                                  InVT.getVectorNumElements());
27442     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27443
27444     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27445       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27446
27447     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27448   }
27449
27450   return SDValue();
27451 }
27452
27453 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27454                                         const X86Subtarget *Subtarget) {
27455   // First try to optimize away the conversion entirely when it's
27456   // conditionally from a constant. Vectors only.
27457   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27458     return Res;
27459
27460   // Now move on to more general possibilities.
27461   SDValue Op0 = N->getOperand(0);
27462   EVT VT = N->getValueType(0);
27463   EVT InVT = Op0.getValueType();
27464   EVT InSVT = InVT.getScalarType();
27465
27466   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27467   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27468   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27469     SDLoc dl(N);
27470     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27471                                  InVT.getVectorNumElements());
27472     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27473     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27474   }
27475
27476   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27477   // a 32-bit target where SSE doesn't support i64->FP operations.
27478   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27479     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27480     EVT LdVT = Ld->getValueType(0);
27481
27482     // This transformation is not supported if the result type is f16
27483     if (VT == MVT::f16)
27484       return SDValue();
27485
27486     if (!Ld->isVolatile() && !VT.isVector() &&
27487         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27488         !Subtarget->is64Bit() && LdVT == MVT::i64) {
27489       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27490           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27491       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27492       return FILDChain;
27493     }
27494   }
27495   return SDValue();
27496 }
27497
27498 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27499 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27500                                  X86TargetLowering::DAGCombinerInfo &DCI) {
27501   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27502   // the result is either zero or one (depending on the input carry bit).
27503   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27504   if (X86::isZeroNode(N->getOperand(0)) &&
27505       X86::isZeroNode(N->getOperand(1)) &&
27506       // We don't have a good way to replace an EFLAGS use, so only do this when
27507       // dead right now.
27508       SDValue(N, 1).use_empty()) {
27509     SDLoc DL(N);
27510     EVT VT = N->getValueType(0);
27511     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27512     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27513                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27514                                            DAG.getConstant(X86::COND_B, DL,
27515                                                            MVT::i8),
27516                                            N->getOperand(2)),
27517                                DAG.getConstant(1, DL, VT));
27518     return DCI.CombineTo(N, Res1, CarryOut);
27519   }
27520
27521   return SDValue();
27522 }
27523
27524 // fold (add Y, (sete  X, 0)) -> adc  0, Y
27525 //      (add Y, (setne X, 0)) -> sbb -1, Y
27526 //      (sub (sete  X, 0), Y) -> sbb  0, Y
27527 //      (sub (setne X, 0), Y) -> adc -1, Y
27528 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27529   SDLoc DL(N);
27530
27531   // Look through ZExts.
27532   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27533   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27534     return SDValue();
27535
27536   SDValue SetCC = Ext.getOperand(0);
27537   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27538     return SDValue();
27539
27540   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27541   if (CC != X86::COND_E && CC != X86::COND_NE)
27542     return SDValue();
27543
27544   SDValue Cmp = SetCC.getOperand(1);
27545   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27546       !X86::isZeroNode(Cmp.getOperand(1)) ||
27547       !Cmp.getOperand(0).getValueType().isInteger())
27548     return SDValue();
27549
27550   SDValue CmpOp0 = Cmp.getOperand(0);
27551   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27552                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
27553
27554   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27555   if (CC == X86::COND_NE)
27556     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27557                        DL, OtherVal.getValueType(), OtherVal,
27558                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27559                        NewCmp);
27560   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27561                      DL, OtherVal.getValueType(), OtherVal,
27562                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27563 }
27564
27565 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27566 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27567                                  const X86Subtarget *Subtarget) {
27568   EVT VT = N->getValueType(0);
27569   SDValue Op0 = N->getOperand(0);
27570   SDValue Op1 = N->getOperand(1);
27571
27572   // Try to synthesize horizontal adds from adds of shuffles.
27573   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27574        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27575       isHorizontalBinOp(Op0, Op1, true))
27576     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27577
27578   return OptimizeConditionalInDecrement(N, DAG);
27579 }
27580
27581 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27582                                  const X86Subtarget *Subtarget) {
27583   SDValue Op0 = N->getOperand(0);
27584   SDValue Op1 = N->getOperand(1);
27585
27586   // X86 can't encode an immediate LHS of a sub. See if we can push the
27587   // negation into a preceding instruction.
27588   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27589     // If the RHS of the sub is a XOR with one use and a constant, invert the
27590     // immediate. Then add one to the LHS of the sub so we can turn
27591     // X-Y -> X+~Y+1, saving one register.
27592     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27593         isa<ConstantSDNode>(Op1.getOperand(1))) {
27594       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27595       EVT VT = Op0.getValueType();
27596       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27597                                    Op1.getOperand(0),
27598                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
27599       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27600                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27601     }
27602   }
27603
27604   // Try to synthesize horizontal adds from adds of shuffles.
27605   EVT VT = N->getValueType(0);
27606   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27607        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27608       isHorizontalBinOp(Op0, Op1, true))
27609     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27610
27611   return OptimizeConditionalInDecrement(N, DAG);
27612 }
27613
27614 /// performVZEXTCombine - Performs build vector combines
27615 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27616                                    TargetLowering::DAGCombinerInfo &DCI,
27617                                    const X86Subtarget *Subtarget) {
27618   SDLoc DL(N);
27619   MVT VT = N->getSimpleValueType(0);
27620   SDValue Op = N->getOperand(0);
27621   MVT OpVT = Op.getSimpleValueType();
27622   MVT OpEltVT = OpVT.getVectorElementType();
27623   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27624
27625   // (vzext (bitcast (vzext (x)) -> (vzext x)
27626   SDValue V = Op;
27627   while (V.getOpcode() == ISD::BITCAST)
27628     V = V.getOperand(0);
27629
27630   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27631     MVT InnerVT = V.getSimpleValueType();
27632     MVT InnerEltVT = InnerVT.getVectorElementType();
27633
27634     // If the element sizes match exactly, we can just do one larger vzext. This
27635     // is always an exact type match as vzext operates on integer types.
27636     if (OpEltVT == InnerEltVT) {
27637       assert(OpVT == InnerVT && "Types must match for vzext!");
27638       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27639     }
27640
27641     // The only other way we can combine them is if only a single element of the
27642     // inner vzext is used in the input to the outer vzext.
27643     if (InnerEltVT.getSizeInBits() < InputBits)
27644       return SDValue();
27645
27646     // In this case, the inner vzext is completely dead because we're going to
27647     // only look at bits inside of the low element. Just do the outer vzext on
27648     // a bitcast of the input to the inner.
27649     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27650   }
27651
27652   // Check if we can bypass extracting and re-inserting an element of an input
27653   // vector. Essentially:
27654   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27655   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27656       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27657       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27658     SDValue ExtractedV = V.getOperand(0);
27659     SDValue OrigV = ExtractedV.getOperand(0);
27660     if (isNullConstant(ExtractedV.getOperand(1))) {
27661         MVT OrigVT = OrigV.getSimpleValueType();
27662         // Extract a subvector if necessary...
27663         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27664           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27665           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27666                                     OrigVT.getVectorNumElements() / Ratio);
27667           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27668                               DAG.getIntPtrConstant(0, DL));
27669         }
27670         Op = DAG.getBitcast(OpVT, OrigV);
27671         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27672       }
27673   }
27674
27675   return SDValue();
27676 }
27677
27678 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27679                                              DAGCombinerInfo &DCI) const {
27680   SelectionDAG &DAG = DCI.DAG;
27681   switch (N->getOpcode()) {
27682   default: break;
27683   case ISD::EXTRACT_VECTOR_ELT:
27684     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27685   case ISD::VSELECT:
27686   case ISD::SELECT:
27687   case X86ISD::SHRUNKBLEND:
27688     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27689   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
27690   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27691   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
27692   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
27693   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
27694   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
27695   case ISD::SHL:
27696   case ISD::SRA:
27697   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
27698   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
27699   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
27700   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
27701   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
27702   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27703   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
27704   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
27705   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27706   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27707   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
27708   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
27709   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
27710   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
27711   case X86ISD::FXOR:
27712   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
27713   case X86ISD::FMIN:
27714   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
27715   case ISD::FMAXNUM:        return performFMaxNumCombine(N, DAG, Subtarget);
27716   case X86ISD::FAND:        return PerformFANDCombine(N, DAG, Subtarget);
27717   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG, Subtarget);
27718   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
27719   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
27720   case ISD::ANY_EXTEND:
27721   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
27722   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
27723   case ISD::SIGN_EXTEND_INREG:
27724     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27725   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
27726   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27727   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27728   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
27729   case X86ISD::SHUFP:       // Handle all target specific shuffles
27730   case X86ISD::PALIGNR:
27731   case X86ISD::UNPCKH:
27732   case X86ISD::UNPCKL:
27733   case X86ISD::MOVHLPS:
27734   case X86ISD::MOVLHPS:
27735   case X86ISD::PSHUFB:
27736   case X86ISD::PSHUFD:
27737   case X86ISD::PSHUFHW:
27738   case X86ISD::PSHUFLW:
27739   case X86ISD::MOVSS:
27740   case X86ISD::MOVSD:
27741   case X86ISD::VPERMILPI:
27742   case X86ISD::VPERM2X128:
27743   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
27744   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
27745   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
27746   case ISD::MGATHER:
27747   case ISD::MSCATTER:       return PerformGatherScatterCombine(N, DAG);
27748   }
27749
27750   return SDValue();
27751 }
27752
27753 /// isTypeDesirableForOp - Return true if the target has native support for
27754 /// the specified value type and it is 'desirable' to use the type for the
27755 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
27756 /// instruction encodings are longer and some i16 instructions are slow.
27757 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
27758   if (!isTypeLegal(VT))
27759     return false;
27760   if (VT != MVT::i16)
27761     return true;
27762
27763   switch (Opc) {
27764   default:
27765     return true;
27766   case ISD::LOAD:
27767   case ISD::SIGN_EXTEND:
27768   case ISD::ZERO_EXTEND:
27769   case ISD::ANY_EXTEND:
27770   case ISD::SHL:
27771   case ISD::SRL:
27772   case ISD::SUB:
27773   case ISD::ADD:
27774   case ISD::MUL:
27775   case ISD::AND:
27776   case ISD::OR:
27777   case ISD::XOR:
27778     return false;
27779   }
27780 }
27781
27782 /// IsDesirableToPromoteOp - This method query the target whether it is
27783 /// beneficial for dag combiner to promote the specified node. If true, it
27784 /// should return the desired promotion type by reference.
27785 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
27786   EVT VT = Op.getValueType();
27787   if (VT != MVT::i16)
27788     return false;
27789
27790   bool Promote = false;
27791   bool Commute = false;
27792   switch (Op.getOpcode()) {
27793   default: break;
27794   case ISD::LOAD: {
27795     LoadSDNode *LD = cast<LoadSDNode>(Op);
27796     // If the non-extending load has a single use and it's not live out, then it
27797     // might be folded.
27798     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
27799                                                      Op.hasOneUse()*/) {
27800       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
27801              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
27802         // The only case where we'd want to promote LOAD (rather then it being
27803         // promoted as an operand is when it's only use is liveout.
27804         if (UI->getOpcode() != ISD::CopyToReg)
27805           return false;
27806       }
27807     }
27808     Promote = true;
27809     break;
27810   }
27811   case ISD::SIGN_EXTEND:
27812   case ISD::ZERO_EXTEND:
27813   case ISD::ANY_EXTEND:
27814     Promote = true;
27815     break;
27816   case ISD::SHL:
27817   case ISD::SRL: {
27818     SDValue N0 = Op.getOperand(0);
27819     // Look out for (store (shl (load), x)).
27820     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
27821       return false;
27822     Promote = true;
27823     break;
27824   }
27825   case ISD::ADD:
27826   case ISD::MUL:
27827   case ISD::AND:
27828   case ISD::OR:
27829   case ISD::XOR:
27830     Commute = true;
27831     // fallthrough
27832   case ISD::SUB: {
27833     SDValue N0 = Op.getOperand(0);
27834     SDValue N1 = Op.getOperand(1);
27835     if (!Commute && MayFoldLoad(N1))
27836       return false;
27837     // Avoid disabling potential load folding opportunities.
27838     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
27839       return false;
27840     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
27841       return false;
27842     Promote = true;
27843   }
27844   }
27845
27846   PVT = MVT::i32;
27847   return Promote;
27848 }
27849
27850 //===----------------------------------------------------------------------===//
27851 //                           X86 Inline Assembly Support
27852 //===----------------------------------------------------------------------===//
27853
27854 // Helper to match a string separated by whitespace.
27855 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
27856   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
27857
27858   for (StringRef Piece : Pieces) {
27859     if (!S.startswith(Piece)) // Check if the piece matches.
27860       return false;
27861
27862     S = S.substr(Piece.size());
27863     StringRef::size_type Pos = S.find_first_not_of(" \t");
27864     if (Pos == 0) // We matched a prefix.
27865       return false;
27866
27867     S = S.substr(Pos);
27868   }
27869
27870   return S.empty();
27871 }
27872
27873 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
27874
27875   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
27876     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
27877         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
27878         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
27879
27880       if (AsmPieces.size() == 3)
27881         return true;
27882       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
27883         return true;
27884     }
27885   }
27886   return false;
27887 }
27888
27889 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
27890   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
27891
27892   std::string AsmStr = IA->getAsmString();
27893
27894   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
27895   if (!Ty || Ty->getBitWidth() % 16 != 0)
27896     return false;
27897
27898   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
27899   SmallVector<StringRef, 4> AsmPieces;
27900   SplitString(AsmStr, AsmPieces, ";\n");
27901
27902   switch (AsmPieces.size()) {
27903   default: return false;
27904   case 1:
27905     // FIXME: this should verify that we are targeting a 486 or better.  If not,
27906     // we will turn this bswap into something that will be lowered to logical
27907     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
27908     // lower so don't worry about this.
27909     // bswap $0
27910     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
27911         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
27912         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
27913         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
27914         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
27915         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
27916       // No need to check constraints, nothing other than the equivalent of
27917       // "=r,0" would be valid here.
27918       return IntrinsicLowering::LowerToByteSwap(CI);
27919     }
27920
27921     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
27922     if (CI->getType()->isIntegerTy(16) &&
27923         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27924         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
27925          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
27926       AsmPieces.clear();
27927       StringRef ConstraintsStr = IA->getConstraintString();
27928       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27929       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27930       if (clobbersFlagRegisters(AsmPieces))
27931         return IntrinsicLowering::LowerToByteSwap(CI);
27932     }
27933     break;
27934   case 3:
27935     if (CI->getType()->isIntegerTy(32) &&
27936         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27937         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
27938         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
27939         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
27940       AsmPieces.clear();
27941       StringRef ConstraintsStr = IA->getConstraintString();
27942       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27943       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27944       if (clobbersFlagRegisters(AsmPieces))
27945         return IntrinsicLowering::LowerToByteSwap(CI);
27946     }
27947
27948     if (CI->getType()->isIntegerTy(64)) {
27949       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
27950       if (Constraints.size() >= 2 &&
27951           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
27952           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
27953         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
27954         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
27955             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
27956             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
27957           return IntrinsicLowering::LowerToByteSwap(CI);
27958       }
27959     }
27960     break;
27961   }
27962   return false;
27963 }
27964
27965 /// getConstraintType - Given a constraint letter, return the type of
27966 /// constraint it is for this target.
27967 X86TargetLowering::ConstraintType
27968 X86TargetLowering::getConstraintType(StringRef Constraint) const {
27969   if (Constraint.size() == 1) {
27970     switch (Constraint[0]) {
27971     case 'R':
27972     case 'q':
27973     case 'Q':
27974     case 'f':
27975     case 't':
27976     case 'u':
27977     case 'y':
27978     case 'x':
27979     case 'Y':
27980     case 'l':
27981       return C_RegisterClass;
27982     case 'a':
27983     case 'b':
27984     case 'c':
27985     case 'd':
27986     case 'S':
27987     case 'D':
27988     case 'A':
27989       return C_Register;
27990     case 'I':
27991     case 'J':
27992     case 'K':
27993     case 'L':
27994     case 'M':
27995     case 'N':
27996     case 'G':
27997     case 'C':
27998     case 'e':
27999     case 'Z':
28000       return C_Other;
28001     default:
28002       break;
28003     }
28004   }
28005   return TargetLowering::getConstraintType(Constraint);
28006 }
28007
28008 /// Examine constraint type and operand type and determine a weight value.
28009 /// This object must already have been set up with the operand type
28010 /// and the current alternative constraint selected.
28011 TargetLowering::ConstraintWeight
28012   X86TargetLowering::getSingleConstraintMatchWeight(
28013     AsmOperandInfo &info, const char *constraint) const {
28014   ConstraintWeight weight = CW_Invalid;
28015   Value *CallOperandVal = info.CallOperandVal;
28016     // If we don't have a value, we can't do a match,
28017     // but allow it at the lowest weight.
28018   if (!CallOperandVal)
28019     return CW_Default;
28020   Type *type = CallOperandVal->getType();
28021   // Look at the constraint type.
28022   switch (*constraint) {
28023   default:
28024     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28025   case 'R':
28026   case 'q':
28027   case 'Q':
28028   case 'a':
28029   case 'b':
28030   case 'c':
28031   case 'd':
28032   case 'S':
28033   case 'D':
28034   case 'A':
28035     if (CallOperandVal->getType()->isIntegerTy())
28036       weight = CW_SpecificReg;
28037     break;
28038   case 'f':
28039   case 't':
28040   case 'u':
28041     if (type->isFloatingPointTy())
28042       weight = CW_SpecificReg;
28043     break;
28044   case 'y':
28045     if (type->isX86_MMXTy() && Subtarget->hasMMX())
28046       weight = CW_SpecificReg;
28047     break;
28048   case 'x':
28049   case 'Y':
28050     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28051         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28052       weight = CW_Register;
28053     break;
28054   case 'I':
28055     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28056       if (C->getZExtValue() <= 31)
28057         weight = CW_Constant;
28058     }
28059     break;
28060   case 'J':
28061     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28062       if (C->getZExtValue() <= 63)
28063         weight = CW_Constant;
28064     }
28065     break;
28066   case 'K':
28067     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28068       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28069         weight = CW_Constant;
28070     }
28071     break;
28072   case 'L':
28073     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28074       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28075         weight = CW_Constant;
28076     }
28077     break;
28078   case 'M':
28079     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28080       if (C->getZExtValue() <= 3)
28081         weight = CW_Constant;
28082     }
28083     break;
28084   case 'N':
28085     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28086       if (C->getZExtValue() <= 0xff)
28087         weight = CW_Constant;
28088     }
28089     break;
28090   case 'G':
28091   case 'C':
28092     if (isa<ConstantFP>(CallOperandVal)) {
28093       weight = CW_Constant;
28094     }
28095     break;
28096   case 'e':
28097     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28098       if ((C->getSExtValue() >= -0x80000000LL) &&
28099           (C->getSExtValue() <= 0x7fffffffLL))
28100         weight = CW_Constant;
28101     }
28102     break;
28103   case 'Z':
28104     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28105       if (C->getZExtValue() <= 0xffffffff)
28106         weight = CW_Constant;
28107     }
28108     break;
28109   }
28110   return weight;
28111 }
28112
28113 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28114 /// with another that has more specific requirements based on the type of the
28115 /// corresponding operand.
28116 const char *X86TargetLowering::
28117 LowerXConstraint(EVT ConstraintVT) const {
28118   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28119   // 'f' like normal targets.
28120   if (ConstraintVT.isFloatingPoint()) {
28121     if (Subtarget->hasSSE2())
28122       return "Y";
28123     if (Subtarget->hasSSE1())
28124       return "x";
28125   }
28126
28127   return TargetLowering::LowerXConstraint(ConstraintVT);
28128 }
28129
28130 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28131 /// vector.  If it is invalid, don't add anything to Ops.
28132 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28133                                                      std::string &Constraint,
28134                                                      std::vector<SDValue>&Ops,
28135                                                      SelectionDAG &DAG) const {
28136   SDValue Result;
28137
28138   // Only support length 1 constraints for now.
28139   if (Constraint.length() > 1) return;
28140
28141   char ConstraintLetter = Constraint[0];
28142   switch (ConstraintLetter) {
28143   default: break;
28144   case 'I':
28145     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28146       if (C->getZExtValue() <= 31) {
28147         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28148                                        Op.getValueType());
28149         break;
28150       }
28151     }
28152     return;
28153   case 'J':
28154     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28155       if (C->getZExtValue() <= 63) {
28156         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28157                                        Op.getValueType());
28158         break;
28159       }
28160     }
28161     return;
28162   case 'K':
28163     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28164       if (isInt<8>(C->getSExtValue())) {
28165         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28166                                        Op.getValueType());
28167         break;
28168       }
28169     }
28170     return;
28171   case 'L':
28172     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28173       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28174           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28175         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28176                                        Op.getValueType());
28177         break;
28178       }
28179     }
28180     return;
28181   case 'M':
28182     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28183       if (C->getZExtValue() <= 3) {
28184         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28185                                        Op.getValueType());
28186         break;
28187       }
28188     }
28189     return;
28190   case 'N':
28191     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28192       if (C->getZExtValue() <= 255) {
28193         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28194                                        Op.getValueType());
28195         break;
28196       }
28197     }
28198     return;
28199   case 'O':
28200     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28201       if (C->getZExtValue() <= 127) {
28202         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28203                                        Op.getValueType());
28204         break;
28205       }
28206     }
28207     return;
28208   case 'e': {
28209     // 32-bit signed value
28210     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28211       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28212                                            C->getSExtValue())) {
28213         // Widen to 64 bits here to get it sign extended.
28214         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28215         break;
28216       }
28217     // FIXME gcc accepts some relocatable values here too, but only in certain
28218     // memory models; it's complicated.
28219     }
28220     return;
28221   }
28222   case 'Z': {
28223     // 32-bit unsigned value
28224     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28225       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28226                                            C->getZExtValue())) {
28227         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28228                                        Op.getValueType());
28229         break;
28230       }
28231     }
28232     // FIXME gcc accepts some relocatable values here too, but only in certain
28233     // memory models; it's complicated.
28234     return;
28235   }
28236   case 'i': {
28237     // Literal immediates are always ok.
28238     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28239       // Widen to 64 bits here to get it sign extended.
28240       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28241       break;
28242     }
28243
28244     // In any sort of PIC mode addresses need to be computed at runtime by
28245     // adding in a register or some sort of table lookup.  These can't
28246     // be used as immediates.
28247     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28248       return;
28249
28250     // If we are in non-pic codegen mode, we allow the address of a global (with
28251     // an optional displacement) to be used with 'i'.
28252     GlobalAddressSDNode *GA = nullptr;
28253     int64_t Offset = 0;
28254
28255     // Match either (GA), (GA+C), (GA+C1+C2), etc.
28256     while (1) {
28257       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28258         Offset += GA->getOffset();
28259         break;
28260       } else if (Op.getOpcode() == ISD::ADD) {
28261         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28262           Offset += C->getZExtValue();
28263           Op = Op.getOperand(0);
28264           continue;
28265         }
28266       } else if (Op.getOpcode() == ISD::SUB) {
28267         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28268           Offset += -C->getZExtValue();
28269           Op = Op.getOperand(0);
28270           continue;
28271         }
28272       }
28273
28274       // Otherwise, this isn't something we can handle, reject it.
28275       return;
28276     }
28277
28278     const GlobalValue *GV = GA->getGlobal();
28279     // If we require an extra load to get this address, as in PIC mode, we
28280     // can't accept it.
28281     if (isGlobalStubReference(
28282             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28283       return;
28284
28285     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28286                                         GA->getValueType(0), Offset);
28287     break;
28288   }
28289   }
28290
28291   if (Result.getNode()) {
28292     Ops.push_back(Result);
28293     return;
28294   }
28295   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28296 }
28297
28298 std::pair<unsigned, const TargetRegisterClass *>
28299 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28300                                                 StringRef Constraint,
28301                                                 MVT VT) const {
28302   // First, see if this is a constraint that directly corresponds to an LLVM
28303   // register class.
28304   if (Constraint.size() == 1) {
28305     // GCC Constraint Letters
28306     switch (Constraint[0]) {
28307     default: break;
28308       // TODO: Slight differences here in allocation order and leaving
28309       // RIP in the class. Do they matter any more here than they do
28310       // in the normal allocation?
28311     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28312       if (Subtarget->is64Bit()) {
28313         if (VT == MVT::i32 || VT == MVT::f32)
28314           return std::make_pair(0U, &X86::GR32RegClass);
28315         if (VT == MVT::i16)
28316           return std::make_pair(0U, &X86::GR16RegClass);
28317         if (VT == MVT::i8 || VT == MVT::i1)
28318           return std::make_pair(0U, &X86::GR8RegClass);
28319         if (VT == MVT::i64 || VT == MVT::f64)
28320           return std::make_pair(0U, &X86::GR64RegClass);
28321         break;
28322       }
28323       // 32-bit fallthrough
28324     case 'Q':   // Q_REGS
28325       if (VT == MVT::i32 || VT == MVT::f32)
28326         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28327       if (VT == MVT::i16)
28328         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28329       if (VT == MVT::i8 || VT == MVT::i1)
28330         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28331       if (VT == MVT::i64)
28332         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28333       break;
28334     case 'r':   // GENERAL_REGS
28335     case 'l':   // INDEX_REGS
28336       if (VT == MVT::i8 || VT == MVT::i1)
28337         return std::make_pair(0U, &X86::GR8RegClass);
28338       if (VT == MVT::i16)
28339         return std::make_pair(0U, &X86::GR16RegClass);
28340       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28341         return std::make_pair(0U, &X86::GR32RegClass);
28342       return std::make_pair(0U, &X86::GR64RegClass);
28343     case 'R':   // LEGACY_REGS
28344       if (VT == MVT::i8 || VT == MVT::i1)
28345         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28346       if (VT == MVT::i16)
28347         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28348       if (VT == MVT::i32 || !Subtarget->is64Bit())
28349         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28350       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28351     case 'f':  // FP Stack registers.
28352       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28353       // value to the correct fpstack register class.
28354       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28355         return std::make_pair(0U, &X86::RFP32RegClass);
28356       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28357         return std::make_pair(0U, &X86::RFP64RegClass);
28358       return std::make_pair(0U, &X86::RFP80RegClass);
28359     case 'y':   // MMX_REGS if MMX allowed.
28360       if (!Subtarget->hasMMX()) break;
28361       return std::make_pair(0U, &X86::VR64RegClass);
28362     case 'Y':   // SSE_REGS if SSE2 allowed
28363       if (!Subtarget->hasSSE2()) break;
28364       // FALL THROUGH.
28365     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28366       if (!Subtarget->hasSSE1()) break;
28367
28368       switch (VT.SimpleTy) {
28369       default: break;
28370       // Scalar SSE types.
28371       case MVT::f32:
28372       case MVT::i32:
28373         return std::make_pair(0U, &X86::FR32RegClass);
28374       case MVT::f64:
28375       case MVT::i64:
28376         return std::make_pair(0U, &X86::FR64RegClass);
28377       // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28378       // Vector types.
28379       case MVT::v16i8:
28380       case MVT::v8i16:
28381       case MVT::v4i32:
28382       case MVT::v2i64:
28383       case MVT::v4f32:
28384       case MVT::v2f64:
28385         return std::make_pair(0U, &X86::VR128RegClass);
28386       // AVX types.
28387       case MVT::v32i8:
28388       case MVT::v16i16:
28389       case MVT::v8i32:
28390       case MVT::v4i64:
28391       case MVT::v8f32:
28392       case MVT::v4f64:
28393         return std::make_pair(0U, &X86::VR256RegClass);
28394       case MVT::v8f64:
28395       case MVT::v16f32:
28396       case MVT::v16i32:
28397       case MVT::v8i64:
28398         return std::make_pair(0U, &X86::VR512RegClass);
28399       }
28400       break;
28401     }
28402   }
28403
28404   // Use the default implementation in TargetLowering to convert the register
28405   // constraint into a member of a register class.
28406   std::pair<unsigned, const TargetRegisterClass*> Res;
28407   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28408
28409   // Not found as a standard register?
28410   if (!Res.second) {
28411     // Map st(0) -> st(7) -> ST0
28412     if (Constraint.size() == 7 && Constraint[0] == '{' &&
28413         tolower(Constraint[1]) == 's' &&
28414         tolower(Constraint[2]) == 't' &&
28415         Constraint[3] == '(' &&
28416         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28417         Constraint[5] == ')' &&
28418         Constraint[6] == '}') {
28419
28420       Res.first = X86::FP0+Constraint[4]-'0';
28421       Res.second = &X86::RFP80RegClass;
28422       return Res;
28423     }
28424
28425     // GCC allows "st(0)" to be called just plain "st".
28426     if (StringRef("{st}").equals_lower(Constraint)) {
28427       Res.first = X86::FP0;
28428       Res.second = &X86::RFP80RegClass;
28429       return Res;
28430     }
28431
28432     // flags -> EFLAGS
28433     if (StringRef("{flags}").equals_lower(Constraint)) {
28434       Res.first = X86::EFLAGS;
28435       Res.second = &X86::CCRRegClass;
28436       return Res;
28437     }
28438
28439     // 'A' means EAX + EDX.
28440     if (Constraint == "A") {
28441       Res.first = X86::EAX;
28442       Res.second = &X86::GR32_ADRegClass;
28443       return Res;
28444     }
28445     return Res;
28446   }
28447
28448   // Otherwise, check to see if this is a register class of the wrong value
28449   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28450   // turn into {ax},{dx}.
28451   // MVT::Other is used to specify clobber names.
28452   if (Res.second->hasType(VT) || VT == MVT::Other)
28453     return Res;   // Correct type already, nothing to do.
28454
28455   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28456   // return "eax". This should even work for things like getting 64bit integer
28457   // registers when given an f64 type.
28458   const TargetRegisterClass *Class = Res.second;
28459   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28460       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28461     unsigned Size = VT.getSizeInBits();
28462     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
28463                                   : Size == 16 ? MVT::i16
28464                                   : Size == 32 ? MVT::i32
28465                                   : Size == 64 ? MVT::i64
28466                                   : MVT::Other;
28467     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
28468     if (DestReg > 0) {
28469       Res.first = DestReg;
28470       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
28471                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
28472                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
28473                  : &X86::GR64RegClass;
28474       assert(Res.second->contains(Res.first) && "Register in register class");
28475     } else {
28476       // No register found/type mismatch.
28477       Res.first = 0;
28478       Res.second = nullptr;
28479     }
28480   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28481              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28482              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28483              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28484              Class == &X86::VR512RegClass) {
28485     // Handle references to XMM physical registers that got mapped into the
28486     // wrong class.  This can happen with constraints like {xmm0} where the
28487     // target independent register mapper will just pick the first match it can
28488     // find, ignoring the required type.
28489
28490     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28491     if (VT == MVT::f32 || VT == MVT::i32)
28492       Res.second = &X86::FR32RegClass;
28493     else if (VT == MVT::f64 || VT == MVT::i64)
28494       Res.second = &X86::FR64RegClass;
28495     else if (X86::VR128RegClass.hasType(VT))
28496       Res.second = &X86::VR128RegClass;
28497     else if (X86::VR256RegClass.hasType(VT))
28498       Res.second = &X86::VR256RegClass;
28499     else if (X86::VR512RegClass.hasType(VT))
28500       Res.second = &X86::VR512RegClass;
28501     else {
28502       // Type mismatch and not a clobber: Return an error;
28503       Res.first = 0;
28504       Res.second = nullptr;
28505     }
28506   }
28507
28508   return Res;
28509 }
28510
28511 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28512                                             const AddrMode &AM, Type *Ty,
28513                                             unsigned AS) const {
28514   // Scaling factors are not free at all.
28515   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28516   // will take 2 allocations in the out of order engine instead of 1
28517   // for plain addressing mode, i.e. inst (reg1).
28518   // E.g.,
28519   // vaddps (%rsi,%drx), %ymm0, %ymm1
28520   // Requires two allocations (one for the load, one for the computation)
28521   // whereas:
28522   // vaddps (%rsi), %ymm0, %ymm1
28523   // Requires just 1 allocation, i.e., freeing allocations for other operations
28524   // and having less micro operations to execute.
28525   //
28526   // For some X86 architectures, this is even worse because for instance for
28527   // stores, the complex addressing mode forces the instruction to use the
28528   // "load" ports instead of the dedicated "store" port.
28529   // E.g., on Haswell:
28530   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28531   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28532   if (isLegalAddressingMode(DL, AM, Ty, AS))
28533     // Scale represents reg2 * scale, thus account for 1
28534     // as soon as we use a second register.
28535     return AM.Scale != 0;
28536   return -1;
28537 }
28538
28539 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28540   // Integer division on x86 is expensive. However, when aggressively optimizing
28541   // for code size, we prefer to use a div instruction, as it is usually smaller
28542   // than the alternative sequence.
28543   // The exception to this is vector division. Since x86 doesn't have vector
28544   // integer division, leaving the division as-is is a loss even in terms of
28545   // size, because it will have to be scalarized, while the alternative code
28546   // sequence can be performed in vector form.
28547   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28548                                    Attribute::MinSize);
28549   return OptSize && !VT.isVector();
28550 }
28551
28552 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
28553        TargetLowering::ArgListTy& Args) const {
28554   // The MCU psABI requires some arguments to be passed in-register.
28555   // For regular calls, the inreg arguments are marked by the front-end.
28556   // However, for compiler generated library calls, we have to patch this
28557   // up here.
28558   if (!Subtarget->isTargetMCU() || !Args.size())
28559     return;
28560
28561   unsigned FreeRegs = 3;
28562   for (auto &Arg : Args) {
28563     // For library functions, we do not expect any fancy types.
28564     unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
28565     unsigned SizeInRegs = (Size + 31) / 32;
28566     if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
28567       continue;
28568
28569     Arg.isInReg = true;
28570     FreeRegs -= SizeInRegs;
28571     if (!FreeRegs)
28572       break;
28573   }
28574 }