]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/X86/X86ISelLowering.cpp
Merge OpenSSL 1.0.2d.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
72                        SDValue V2);
73
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75                                      const X86Subtarget &STI)
76     : TargetLowering(TM), Subtarget(&STI) {
77   X86ScalarSSEf64 = Subtarget->hasSSE2();
78   X86ScalarSSEf32 = Subtarget->hasSSE1();
79   TD = TM.getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
209   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210   // are Legal, f80 is custom lowered.
211   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248   }
249
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(*TD), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1037   }
1038
1039   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1061     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1062     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1076
1077     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078     // even though v8i16 is a legal type.
1079     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1082
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1085     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1086
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1088     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1089
1090     for (MVT VT : MVT::fp_vector_valuetypes())
1091       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1092
1093     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1106
1107     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1109     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1110
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1128
1129     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1136     }
1137
1138     if (Subtarget->hasInt256()) {
1139       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1143
1144       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1148
1149       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1150       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1153
1154       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1156       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1157       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1158
1159       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1161       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1171
1172       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173       // when we have a 256bit-wide blend with immediate.
1174       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1175
1176       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1183
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1190     } else {
1191       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1195
1196       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1200
1201       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1205     }
1206
1207     // In the customized shift lowering, the legal cases in AVX2 will be
1208     // recognized.
1209     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1210     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1211
1212     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (MVT VT : MVT::vector_valuetypes()) {
1220       if (VT.getScalarSizeInBits() >= 32) {
1221         setOperationAction(ISD::MLOAD,  VT, Legal);
1222         setOperationAction(ISD::MSTORE, VT, Legal);
1223       }
1224       // Extract subvector is special because the value type
1225       // (result) is 128-bit but the source is 256-bit wide.
1226       if (VT.is128BitVector()) {
1227         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228       }
1229       // Do not attempt to custom lower other non-256-bit vectors
1230       if (!VT.is256BitVector())
1231         continue;
1232
1233       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1234       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1235       setOperationAction(ISD::VSELECT,            VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     if (Subtarget->hasInt256())
1244       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1245
1246
1247     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249       MVT VT = (MVT::SimpleValueType)i;
1250
1251       // Do not attempt to promote non-256-bit vectors
1252       if (!VT.is256BitVector())
1253         continue;
1254
1255       setOperationAction(ISD::AND,    VT, Promote);
1256       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1257       setOperationAction(ISD::OR,     VT, Promote);
1258       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1259       setOperationAction(ISD::XOR,    VT, Promote);
1260       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1261       setOperationAction(ISD::LOAD,   VT, Promote);
1262       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1263       setOperationAction(ISD::SELECT, VT, Promote);
1264       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265     }
1266   }
1267
1268   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1272     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1273
1274     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1275     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1276     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1277
1278     for (MVT VT : MVT::fp_vector_valuetypes())
1279       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1280
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1291     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1292     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1293
1294     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1295     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1296     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1297     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1298     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1299     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1300     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1301     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1302     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1305     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1306     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1307
1308     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1313     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1314
1315     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1321     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1323
1324     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1325     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1326     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1328     if (Subtarget->is64Bit()) {
1329       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1330       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1331       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1332       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1333     }
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1348     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1349     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1350
1351     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1352     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1353     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1354     if (Subtarget->hasDQI()) {
1355       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1356       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1357     }
1358     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1359     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1360     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1361     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1362     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1363     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1364     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1365     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1366     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1367     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1368     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1369     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1370     if (Subtarget->hasDQI()) {
1371       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1372       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1373     }
1374     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1375     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1376     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1377     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1378     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1379     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1380     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1381     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1382     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1383     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1384
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1390
1391     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1392     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1393
1394     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1395
1396     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1397     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1399     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1400     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1401     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1402     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1403     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1404     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1405     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1406     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1407
1408     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1409     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1410     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1411     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1412     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1413     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1414     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1415     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1416
1417     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1418     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1419
1420     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1421     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1422
1423     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1424
1425     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1426     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1427
1428     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1429     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1430
1431     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1432     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1433
1434     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1435     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1436     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1437     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1438     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1439     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1440
1441     if (Subtarget->hasCDI()) {
1442       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1443       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1444     }
1445     if (Subtarget->hasDQI()) {
1446       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1447       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1448       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1449     }
1450     // Custom lower several nodes.
1451     for (MVT VT : MVT::vector_valuetypes()) {
1452       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453       if (EltSize == 1) {
1454         setOperationAction(ISD::AND, VT, Legal);
1455         setOperationAction(ISD::OR,  VT, Legal);
1456         setOperationAction(ISD::XOR,  VT, Legal);
1457       }
1458       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1459         setOperationAction(ISD::MGATHER,  VT, Custom);
1460         setOperationAction(ISD::MSCATTER, VT, Custom);
1461       }
1462       // Extract subvector is special because the value type
1463       // (result) is 256/128-bit but the source is 512-bit wide.
1464       if (VT.is128BitVector() || VT.is256BitVector()) {
1465         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1466       }
1467       if (VT.getVectorElementType() == MVT::i1)
1468         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1469
1470       // Do not attempt to custom lower other non-512-bit vectors
1471       if (!VT.is512BitVector())
1472         continue;
1473
1474       if (EltSize >= 32) {
1475         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1476         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1477         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1478         setOperationAction(ISD::VSELECT,             VT, Legal);
1479         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1480         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1481         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1482         setOperationAction(ISD::MLOAD,               VT, Legal);
1483         setOperationAction(ISD::MSTORE,              VT, Legal);
1484       }
1485     }
1486     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1487       MVT VT = (MVT::SimpleValueType)i;
1488
1489       // Do not attempt to promote non-512-bit vectors.
1490       if (!VT.is512BitVector())
1491         continue;
1492
1493       setOperationAction(ISD::SELECT, VT, Promote);
1494       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1495     }
1496   }// has  AVX-512
1497
1498   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1499     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1500     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1501
1502     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1503     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1504
1505     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1506     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1507     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1508     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1509     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1510     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1511     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1512     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1513     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1514     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1515     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1516     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1517     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1518     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1519     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1520     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1521     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1522     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1523     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1524     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1525     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1526     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1527     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1528     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1529     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1530     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1531     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1532     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1533     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1534
1535     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1536     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1537     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1538     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1539     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1540     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1541     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1542     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1543
1544     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1545       const MVT VT = (MVT::SimpleValueType)i;
1546
1547       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1548
1549       // Do not attempt to promote non-512-bit vectors.
1550       if (!VT.is512BitVector())
1551         continue;
1552
1553       if (EltSize < 32) {
1554         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1555         setOperationAction(ISD::VSELECT,             VT, Legal);
1556       }
1557     }
1558   }
1559
1560   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1561     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1562     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1563
1564     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1565     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1566     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1567     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1568     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1569     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1570     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1571     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1572     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1573     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1574
1575     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1576     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1577     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1578     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1579     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1580     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1581     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1582     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1583
1584     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1585     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1586     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1587     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1588     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1589     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1590     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1591     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1592   }
1593
1594   // We want to custom lower some of our intrinsics.
1595   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1596   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1597   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1598   if (!Subtarget->is64Bit())
1599     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1600
1601   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1602   // handle type legalization for these operations here.
1603   //
1604   // FIXME: We really should do custom legalization for addition and
1605   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1606   // than generic legalization for 64-bit multiplication-with-overflow, though.
1607   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1608     // Add/Sub/Mul with overflow operations are custom lowered.
1609     MVT VT = IntVTs[i];
1610     setOperationAction(ISD::SADDO, VT, Custom);
1611     setOperationAction(ISD::UADDO, VT, Custom);
1612     setOperationAction(ISD::SSUBO, VT, Custom);
1613     setOperationAction(ISD::USUBO, VT, Custom);
1614     setOperationAction(ISD::SMULO, VT, Custom);
1615     setOperationAction(ISD::UMULO, VT, Custom);
1616   }
1617
1618
1619   if (!Subtarget->is64Bit()) {
1620     // These libcalls are not available in 32-bit.
1621     setLibcallName(RTLIB::SHL_I128, nullptr);
1622     setLibcallName(RTLIB::SRL_I128, nullptr);
1623     setLibcallName(RTLIB::SRA_I128, nullptr);
1624   }
1625
1626   // Combine sin / cos into one node or libcall if possible.
1627   if (Subtarget->hasSinCos()) {
1628     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1629     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1630     if (Subtarget->isTargetDarwin()) {
1631       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1632       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1633       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1634       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1635     }
1636   }
1637
1638   if (Subtarget->isTargetWin64()) {
1639     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1640     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1641     setOperationAction(ISD::SREM, MVT::i128, Custom);
1642     setOperationAction(ISD::UREM, MVT::i128, Custom);
1643     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1644     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1645   }
1646
1647   // We have target-specific dag combine patterns for the following nodes:
1648   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1649   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1650   setTargetDAGCombine(ISD::BITCAST);
1651   setTargetDAGCombine(ISD::VSELECT);
1652   setTargetDAGCombine(ISD::SELECT);
1653   setTargetDAGCombine(ISD::SHL);
1654   setTargetDAGCombine(ISD::SRA);
1655   setTargetDAGCombine(ISD::SRL);
1656   setTargetDAGCombine(ISD::OR);
1657   setTargetDAGCombine(ISD::AND);
1658   setTargetDAGCombine(ISD::ADD);
1659   setTargetDAGCombine(ISD::FADD);
1660   setTargetDAGCombine(ISD::FSUB);
1661   setTargetDAGCombine(ISD::FMA);
1662   setTargetDAGCombine(ISD::SUB);
1663   setTargetDAGCombine(ISD::LOAD);
1664   setTargetDAGCombine(ISD::MLOAD);
1665   setTargetDAGCombine(ISD::STORE);
1666   setTargetDAGCombine(ISD::MSTORE);
1667   setTargetDAGCombine(ISD::ZERO_EXTEND);
1668   setTargetDAGCombine(ISD::ANY_EXTEND);
1669   setTargetDAGCombine(ISD::SIGN_EXTEND);
1670   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1671   setTargetDAGCombine(ISD::SINT_TO_FP);
1672   setTargetDAGCombine(ISD::UINT_TO_FP);
1673   setTargetDAGCombine(ISD::SETCC);
1674   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1675   setTargetDAGCombine(ISD::BUILD_VECTOR);
1676   setTargetDAGCombine(ISD::MUL);
1677   setTargetDAGCombine(ISD::XOR);
1678
1679   computeRegisterProperties(Subtarget->getRegisterInfo());
1680
1681   // On Darwin, -Os means optimize for size without hurting performance,
1682   // do not reduce the limit.
1683   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1684   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1685   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1686   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1687   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1688   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1689   setPrefLoopAlignment(4); // 2^4 bytes.
1690
1691   // Predictable cmov don't hurt on atom because it's in-order.
1692   PredictableSelectIsExpensive = !Subtarget->isAtom();
1693   EnableExtLdPromotion = true;
1694   setPrefFunctionAlignment(4); // 2^4 bytes.
1695
1696   verifyIntrinsicTables();
1697 }
1698
1699 // This has so far only been implemented for 64-bit MachO.
1700 bool X86TargetLowering::useLoadStackGuardNode() const {
1701   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1702 }
1703
1704 TargetLoweringBase::LegalizeTypeAction
1705 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1706   if (ExperimentalVectorWideningLegalization &&
1707       VT.getVectorNumElements() != 1 &&
1708       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1709     return TypeWidenVector;
1710
1711   return TargetLoweringBase::getPreferredVectorAction(VT);
1712 }
1713
1714 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1715                                           EVT VT) const {
1716   if (!VT.isVector())
1717     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1718
1719   const unsigned NumElts = VT.getVectorNumElements();
1720   const EVT EltVT = VT.getVectorElementType();
1721   if (VT.is512BitVector()) {
1722     if (Subtarget->hasAVX512())
1723       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1724           EltVT == MVT::f32 || EltVT == MVT::f64)
1725         switch(NumElts) {
1726         case  8: return MVT::v8i1;
1727         case 16: return MVT::v16i1;
1728       }
1729     if (Subtarget->hasBWI())
1730       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1731         switch(NumElts) {
1732         case 32: return MVT::v32i1;
1733         case 64: return MVT::v64i1;
1734       }
1735   }
1736
1737   if (VT.is256BitVector() || VT.is128BitVector()) {
1738     if (Subtarget->hasVLX())
1739       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1740           EltVT == MVT::f32 || EltVT == MVT::f64)
1741         switch(NumElts) {
1742         case 2: return MVT::v2i1;
1743         case 4: return MVT::v4i1;
1744         case 8: return MVT::v8i1;
1745       }
1746     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1747       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1748         switch(NumElts) {
1749         case  8: return MVT::v8i1;
1750         case 16: return MVT::v16i1;
1751         case 32: return MVT::v32i1;
1752       }
1753   }
1754
1755   return VT.changeVectorElementTypeToInteger();
1756 }
1757
1758 /// Helper for getByValTypeAlignment to determine
1759 /// the desired ByVal argument alignment.
1760 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1761   if (MaxAlign == 16)
1762     return;
1763   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1764     if (VTy->getBitWidth() == 128)
1765       MaxAlign = 16;
1766   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1767     unsigned EltAlign = 0;
1768     getMaxByValAlign(ATy->getElementType(), EltAlign);
1769     if (EltAlign > MaxAlign)
1770       MaxAlign = EltAlign;
1771   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1772     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1773       unsigned EltAlign = 0;
1774       getMaxByValAlign(STy->getElementType(i), EltAlign);
1775       if (EltAlign > MaxAlign)
1776         MaxAlign = EltAlign;
1777       if (MaxAlign == 16)
1778         break;
1779     }
1780   }
1781 }
1782
1783 /// Return the desired alignment for ByVal aggregate
1784 /// function arguments in the caller parameter area. For X86, aggregates
1785 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1786 /// are at 4-byte boundaries.
1787 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1788                                                   const DataLayout &DL) const {
1789   if (Subtarget->is64Bit()) {
1790     // Max of 8 and alignment of type.
1791     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1792     if (TyAlign > 8)
1793       return TyAlign;
1794     return 8;
1795   }
1796
1797   unsigned Align = 4;
1798   if (Subtarget->hasSSE1())
1799     getMaxByValAlign(Ty, Align);
1800   return Align;
1801 }
1802
1803 /// Returns the target specific optimal type for load
1804 /// and store operations as a result of memset, memcpy, and memmove
1805 /// lowering. If DstAlign is zero that means it's safe to destination
1806 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1807 /// means there isn't a need to check it against alignment requirement,
1808 /// probably because the source does not need to be loaded. If 'IsMemset' is
1809 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1810 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1811 /// source is constant so it does not need to be loaded.
1812 /// It returns EVT::Other if the type should be determined using generic
1813 /// target-independent logic.
1814 EVT
1815 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1816                                        unsigned DstAlign, unsigned SrcAlign,
1817                                        bool IsMemset, bool ZeroMemset,
1818                                        bool MemcpyStrSrc,
1819                                        MachineFunction &MF) const {
1820   const Function *F = MF.getFunction();
1821   if ((!IsMemset || ZeroMemset) &&
1822       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1823     if (Size >= 16 &&
1824         (Subtarget->isUnalignedMemAccessFast() ||
1825          ((DstAlign == 0 || DstAlign >= 16) &&
1826           (SrcAlign == 0 || SrcAlign >= 16)))) {
1827       if (Size >= 32) {
1828         if (Subtarget->hasInt256())
1829           return MVT::v8i32;
1830         if (Subtarget->hasFp256())
1831           return MVT::v8f32;
1832       }
1833       if (Subtarget->hasSSE2())
1834         return MVT::v4i32;
1835       if (Subtarget->hasSSE1())
1836         return MVT::v4f32;
1837     } else if (!MemcpyStrSrc && Size >= 8 &&
1838                !Subtarget->is64Bit() &&
1839                Subtarget->hasSSE2()) {
1840       // Do not use f64 to lower memcpy if source is string constant. It's
1841       // better to use i32 to avoid the loads.
1842       return MVT::f64;
1843     }
1844   }
1845   if (Subtarget->is64Bit() && Size >= 8)
1846     return MVT::i64;
1847   return MVT::i32;
1848 }
1849
1850 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1851   if (VT == MVT::f32)
1852     return X86ScalarSSEf32;
1853   else if (VT == MVT::f64)
1854     return X86ScalarSSEf64;
1855   return true;
1856 }
1857
1858 bool
1859 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1860                                                   unsigned,
1861                                                   unsigned,
1862                                                   bool *Fast) const {
1863   if (Fast)
1864     *Fast = Subtarget->isUnalignedMemAccessFast();
1865   return true;
1866 }
1867
1868 /// Return the entry encoding for a jump table in the
1869 /// current function.  The returned value is a member of the
1870 /// MachineJumpTableInfo::JTEntryKind enum.
1871 unsigned X86TargetLowering::getJumpTableEncoding() const {
1872   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1873   // symbol.
1874   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1875       Subtarget->isPICStyleGOT())
1876     return MachineJumpTableInfo::EK_Custom32;
1877
1878   // Otherwise, use the normal jump table encoding heuristics.
1879   return TargetLowering::getJumpTableEncoding();
1880 }
1881
1882 bool X86TargetLowering::useSoftFloat() const {
1883   return Subtarget->useSoftFloat();
1884 }
1885
1886 const MCExpr *
1887 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1888                                              const MachineBasicBlock *MBB,
1889                                              unsigned uid,MCContext &Ctx) const{
1890   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1891          Subtarget->isPICStyleGOT());
1892   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1893   // entries.
1894   return MCSymbolRefExpr::create(MBB->getSymbol(),
1895                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1896 }
1897
1898 /// Returns relocation base for the given PIC jumptable.
1899 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1900                                                     SelectionDAG &DAG) const {
1901   if (!Subtarget->is64Bit())
1902     // This doesn't have SDLoc associated with it, but is not really the
1903     // same as a Register.
1904     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1905                        getPointerTy(DAG.getDataLayout()));
1906   return Table;
1907 }
1908
1909 /// This returns the relocation base for the given PIC jumptable,
1910 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1911 const MCExpr *X86TargetLowering::
1912 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1913                              MCContext &Ctx) const {
1914   // X86-64 uses RIP relative addressing based on the jump table label.
1915   if (Subtarget->isPICStyleRIPRel())
1916     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1917
1918   // Otherwise, the reference is relative to the PIC base.
1919   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1920 }
1921
1922 std::pair<const TargetRegisterClass *, uint8_t>
1923 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1924                                            MVT VT) const {
1925   const TargetRegisterClass *RRC = nullptr;
1926   uint8_t Cost = 1;
1927   switch (VT.SimpleTy) {
1928   default:
1929     return TargetLowering::findRepresentativeClass(TRI, VT);
1930   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1931     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1932     break;
1933   case MVT::x86mmx:
1934     RRC = &X86::VR64RegClass;
1935     break;
1936   case MVT::f32: case MVT::f64:
1937   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1938   case MVT::v4f32: case MVT::v2f64:
1939   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1940   case MVT::v4f64:
1941     RRC = &X86::VR128RegClass;
1942     break;
1943   }
1944   return std::make_pair(RRC, Cost);
1945 }
1946
1947 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1948                                                unsigned &Offset) const {
1949   if (!Subtarget->isTargetLinux())
1950     return false;
1951
1952   if (Subtarget->is64Bit()) {
1953     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1954     Offset = 0x28;
1955     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1956       AddressSpace = 256;
1957     else
1958       AddressSpace = 257;
1959   } else {
1960     // %gs:0x14 on i386
1961     Offset = 0x14;
1962     AddressSpace = 256;
1963   }
1964   return true;
1965 }
1966
1967 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1968                                             unsigned DestAS) const {
1969   assert(SrcAS != DestAS && "Expected different address spaces!");
1970
1971   return SrcAS < 256 && DestAS < 256;
1972 }
1973
1974 //===----------------------------------------------------------------------===//
1975 //               Return Value Calling Convention Implementation
1976 //===----------------------------------------------------------------------===//
1977
1978 #include "X86GenCallingConv.inc"
1979
1980 bool
1981 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1982                                   MachineFunction &MF, bool isVarArg,
1983                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1984                         LLVMContext &Context) const {
1985   SmallVector<CCValAssign, 16> RVLocs;
1986   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1987   return CCInfo.CheckReturn(Outs, RetCC_X86);
1988 }
1989
1990 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1991   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1992   return ScratchRegs;
1993 }
1994
1995 SDValue
1996 X86TargetLowering::LowerReturn(SDValue Chain,
1997                                CallingConv::ID CallConv, bool isVarArg,
1998                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1999                                const SmallVectorImpl<SDValue> &OutVals,
2000                                SDLoc dl, SelectionDAG &DAG) const {
2001   MachineFunction &MF = DAG.getMachineFunction();
2002   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2003
2004   SmallVector<CCValAssign, 16> RVLocs;
2005   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2006   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2007
2008   SDValue Flag;
2009   SmallVector<SDValue, 6> RetOps;
2010   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2011   // Operand #1 = Bytes To Pop
2012   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2013                    MVT::i16));
2014
2015   // Copy the result values into the output registers.
2016   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2017     CCValAssign &VA = RVLocs[i];
2018     assert(VA.isRegLoc() && "Can only return in registers!");
2019     SDValue ValToCopy = OutVals[i];
2020     EVT ValVT = ValToCopy.getValueType();
2021
2022     // Promote values to the appropriate types.
2023     if (VA.getLocInfo() == CCValAssign::SExt)
2024       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2025     else if (VA.getLocInfo() == CCValAssign::ZExt)
2026       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2027     else if (VA.getLocInfo() == CCValAssign::AExt) {
2028       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2029         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2030       else
2031         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2032     }
2033     else if (VA.getLocInfo() == CCValAssign::BCvt)
2034       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2035
2036     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2037            "Unexpected FP-extend for return value.");
2038
2039     // If this is x86-64, and we disabled SSE, we can't return FP values,
2040     // or SSE or MMX vectors.
2041     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2042          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2043           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2044       report_fatal_error("SSE register return with SSE disabled");
2045     }
2046     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2047     // llvm-gcc has never done it right and no one has noticed, so this
2048     // should be OK for now.
2049     if (ValVT == MVT::f64 &&
2050         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2051       report_fatal_error("SSE2 register return with SSE2 disabled");
2052
2053     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2054     // the RET instruction and handled by the FP Stackifier.
2055     if (VA.getLocReg() == X86::FP0 ||
2056         VA.getLocReg() == X86::FP1) {
2057       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2058       // change the value to the FP stack register class.
2059       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2060         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2061       RetOps.push_back(ValToCopy);
2062       // Don't emit a copytoreg.
2063       continue;
2064     }
2065
2066     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2067     // which is returned in RAX / RDX.
2068     if (Subtarget->is64Bit()) {
2069       if (ValVT == MVT::x86mmx) {
2070         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2071           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2072           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2073                                   ValToCopy);
2074           // If we don't have SSE2 available, convert to v4f32 so the generated
2075           // register is legal.
2076           if (!Subtarget->hasSSE2())
2077             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2078         }
2079       }
2080     }
2081
2082     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2083     Flag = Chain.getValue(1);
2084     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2085   }
2086
2087   // All x86 ABIs require that for returning structs by value we copy
2088   // the sret argument into %rax/%eax (depending on ABI) for the return.
2089   // We saved the argument into a virtual register in the entry block,
2090   // so now we copy the value out and into %rax/%eax.
2091   //
2092   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2093   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2094   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2095   // either case FuncInfo->setSRetReturnReg() will have been called.
2096   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2097     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2098                                      getPointerTy(MF.getDataLayout()));
2099
2100     unsigned RetValReg
2101         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2102           X86::RAX : X86::EAX;
2103     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2104     Flag = Chain.getValue(1);
2105
2106     // RAX/EAX now acts like a return value.
2107     RetOps.push_back(
2108         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2109   }
2110
2111   RetOps[0] = Chain;  // Update chain.
2112
2113   // Add the flag if we have it.
2114   if (Flag.getNode())
2115     RetOps.push_back(Flag);
2116
2117   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2118 }
2119
2120 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2121   if (N->getNumValues() != 1)
2122     return false;
2123   if (!N->hasNUsesOfValue(1, 0))
2124     return false;
2125
2126   SDValue TCChain = Chain;
2127   SDNode *Copy = *N->use_begin();
2128   if (Copy->getOpcode() == ISD::CopyToReg) {
2129     // If the copy has a glue operand, we conservatively assume it isn't safe to
2130     // perform a tail call.
2131     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2132       return false;
2133     TCChain = Copy->getOperand(0);
2134   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2135     return false;
2136
2137   bool HasRet = false;
2138   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2139        UI != UE; ++UI) {
2140     if (UI->getOpcode() != X86ISD::RET_FLAG)
2141       return false;
2142     // If we are returning more than one value, we can definitely
2143     // not make a tail call see PR19530
2144     if (UI->getNumOperands() > 4)
2145       return false;
2146     if (UI->getNumOperands() == 4 &&
2147         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2148       return false;
2149     HasRet = true;
2150   }
2151
2152   if (!HasRet)
2153     return false;
2154
2155   Chain = TCChain;
2156   return true;
2157 }
2158
2159 EVT
2160 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2161                                             ISD::NodeType ExtendKind) const {
2162   MVT ReturnMVT;
2163   // TODO: Is this also valid on 32-bit?
2164   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2165     ReturnMVT = MVT::i8;
2166   else
2167     ReturnMVT = MVT::i32;
2168
2169   EVT MinVT = getRegisterType(Context, ReturnMVT);
2170   return VT.bitsLT(MinVT) ? MinVT : VT;
2171 }
2172
2173 /// Lower the result values of a call into the
2174 /// appropriate copies out of appropriate physical registers.
2175 ///
2176 SDValue
2177 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2178                                    CallingConv::ID CallConv, bool isVarArg,
2179                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2180                                    SDLoc dl, SelectionDAG &DAG,
2181                                    SmallVectorImpl<SDValue> &InVals) const {
2182
2183   // Assign locations to each value returned by this call.
2184   SmallVector<CCValAssign, 16> RVLocs;
2185   bool Is64Bit = Subtarget->is64Bit();
2186   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2187                  *DAG.getContext());
2188   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2189
2190   // Copy all of the result registers out of their specified physreg.
2191   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2192     CCValAssign &VA = RVLocs[i];
2193     EVT CopyVT = VA.getLocVT();
2194
2195     // If this is x86-64, and we disabled SSE, we can't return FP values
2196     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2197         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2198       report_fatal_error("SSE register return with SSE disabled");
2199     }
2200
2201     // If we prefer to use the value in xmm registers, copy it out as f80 and
2202     // use a truncate to move it from fp stack reg to xmm reg.
2203     bool RoundAfterCopy = false;
2204     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2205         isScalarFPTypeInSSEReg(VA.getValVT())) {
2206       CopyVT = MVT::f80;
2207       RoundAfterCopy = (CopyVT != VA.getLocVT());
2208     }
2209
2210     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2211                                CopyVT, InFlag).getValue(1);
2212     SDValue Val = Chain.getValue(0);
2213
2214     if (RoundAfterCopy)
2215       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2216                         // This truncation won't change the value.
2217                         DAG.getIntPtrConstant(1, dl));
2218
2219     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2220       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2221
2222     InFlag = Chain.getValue(2);
2223     InVals.push_back(Val);
2224   }
2225
2226   return Chain;
2227 }
2228
2229 //===----------------------------------------------------------------------===//
2230 //                C & StdCall & Fast Calling Convention implementation
2231 //===----------------------------------------------------------------------===//
2232 //  StdCall calling convention seems to be standard for many Windows' API
2233 //  routines and around. It differs from C calling convention just a little:
2234 //  callee should clean up the stack, not caller. Symbols should be also
2235 //  decorated in some fancy way :) It doesn't support any vector arguments.
2236 //  For info on fast calling convention see Fast Calling Convention (tail call)
2237 //  implementation LowerX86_32FastCCCallTo.
2238
2239 /// CallIsStructReturn - Determines whether a call uses struct return
2240 /// semantics.
2241 enum StructReturnType {
2242   NotStructReturn,
2243   RegStructReturn,
2244   StackStructReturn
2245 };
2246 static StructReturnType
2247 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2248   if (Outs.empty())
2249     return NotStructReturn;
2250
2251   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2252   if (!Flags.isSRet())
2253     return NotStructReturn;
2254   if (Flags.isInReg())
2255     return RegStructReturn;
2256   return StackStructReturn;
2257 }
2258
2259 /// Determines whether a function uses struct return semantics.
2260 static StructReturnType
2261 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2262   if (Ins.empty())
2263     return NotStructReturn;
2264
2265   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2266   if (!Flags.isSRet())
2267     return NotStructReturn;
2268   if (Flags.isInReg())
2269     return RegStructReturn;
2270   return StackStructReturn;
2271 }
2272
2273 /// Make a copy of an aggregate at address specified by "Src" to address
2274 /// "Dst" with size and alignment information specified by the specific
2275 /// parameter attribute. The copy will be passed as a byval function parameter.
2276 static SDValue
2277 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2278                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2279                           SDLoc dl) {
2280   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2281
2282   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2283                        /*isVolatile*/false, /*AlwaysInline=*/true,
2284                        /*isTailCall*/false,
2285                        MachinePointerInfo(), MachinePointerInfo());
2286 }
2287
2288 /// Return true if the calling convention is one that
2289 /// supports tail call optimization.
2290 static bool IsTailCallConvention(CallingConv::ID CC) {
2291   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2292           CC == CallingConv::HiPE);
2293 }
2294
2295 /// \brief Return true if the calling convention is a C calling convention.
2296 static bool IsCCallConvention(CallingConv::ID CC) {
2297   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2298           CC == CallingConv::X86_64_SysV);
2299 }
2300
2301 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2302   auto Attr =
2303       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2304   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2305     return false;
2306
2307   CallSite CS(CI);
2308   CallingConv::ID CalleeCC = CS.getCallingConv();
2309   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2310     return false;
2311
2312   return true;
2313 }
2314
2315 /// Return true if the function is being made into
2316 /// a tailcall target by changing its ABI.
2317 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2318                                    bool GuaranteedTailCallOpt) {
2319   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2320 }
2321
2322 SDValue
2323 X86TargetLowering::LowerMemArgument(SDValue Chain,
2324                                     CallingConv::ID CallConv,
2325                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2326                                     SDLoc dl, SelectionDAG &DAG,
2327                                     const CCValAssign &VA,
2328                                     MachineFrameInfo *MFI,
2329                                     unsigned i) const {
2330   // Create the nodes corresponding to a load from this parameter slot.
2331   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2332   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2333       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2334   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2335   EVT ValVT;
2336
2337   // If value is passed by pointer we have address passed instead of the value
2338   // itself.
2339   bool ExtendedInMem = VA.isExtInLoc() &&
2340     VA.getValVT().getScalarType() == MVT::i1;
2341
2342   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2343     ValVT = VA.getLocVT();
2344   else
2345     ValVT = VA.getValVT();
2346
2347   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2348   // changed with more analysis.
2349   // In case of tail call optimization mark all arguments mutable. Since they
2350   // could be overwritten by lowering of arguments in case of a tail call.
2351   if (Flags.isByVal()) {
2352     unsigned Bytes = Flags.getByValSize();
2353     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2354     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2355     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2356   } else {
2357     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2358                                     VA.getLocMemOffset(), isImmutable);
2359     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2360     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2361                                MachinePointerInfo::getFixedStack(FI),
2362                                false, false, false, 0);
2363     return ExtendedInMem ?
2364       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2365   }
2366 }
2367
2368 // FIXME: Get this from tablegen.
2369 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2370                                                 const X86Subtarget *Subtarget) {
2371   assert(Subtarget->is64Bit());
2372
2373   if (Subtarget->isCallingConvWin64(CallConv)) {
2374     static const MCPhysReg GPR64ArgRegsWin64[] = {
2375       X86::RCX, X86::RDX, X86::R8,  X86::R9
2376     };
2377     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2378   }
2379
2380   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2381     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2382   };
2383   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2384 }
2385
2386 // FIXME: Get this from tablegen.
2387 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2388                                                 CallingConv::ID CallConv,
2389                                                 const X86Subtarget *Subtarget) {
2390   assert(Subtarget->is64Bit());
2391   if (Subtarget->isCallingConvWin64(CallConv)) {
2392     // The XMM registers which might contain var arg parameters are shadowed
2393     // in their paired GPR.  So we only need to save the GPR to their home
2394     // slots.
2395     // TODO: __vectorcall will change this.
2396     return None;
2397   }
2398
2399   const Function *Fn = MF.getFunction();
2400   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2401   bool isSoftFloat = Subtarget->useSoftFloat();
2402   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2403          "SSE register cannot be used when SSE is disabled!");
2404   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2405     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2406     // registers.
2407     return None;
2408
2409   static const MCPhysReg XMMArgRegs64Bit[] = {
2410     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2411     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2412   };
2413   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2414 }
2415
2416 SDValue
2417 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2418                                         CallingConv::ID CallConv,
2419                                         bool isVarArg,
2420                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2421                                         SDLoc dl,
2422                                         SelectionDAG &DAG,
2423                                         SmallVectorImpl<SDValue> &InVals)
2424                                           const {
2425   MachineFunction &MF = DAG.getMachineFunction();
2426   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2427   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2428
2429   const Function* Fn = MF.getFunction();
2430   if (Fn->hasExternalLinkage() &&
2431       Subtarget->isTargetCygMing() &&
2432       Fn->getName() == "main")
2433     FuncInfo->setForceFramePointer(true);
2434
2435   MachineFrameInfo *MFI = MF.getFrameInfo();
2436   bool Is64Bit = Subtarget->is64Bit();
2437   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2438
2439   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2440          "Var args not supported with calling convention fastcc, ghc or hipe");
2441
2442   // Assign locations to all of the incoming arguments.
2443   SmallVector<CCValAssign, 16> ArgLocs;
2444   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2445
2446   // Allocate shadow area for Win64
2447   if (IsWin64)
2448     CCInfo.AllocateStack(32, 8);
2449
2450   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2451
2452   unsigned LastVal = ~0U;
2453   SDValue ArgValue;
2454   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2455     CCValAssign &VA = ArgLocs[i];
2456     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2457     // places.
2458     assert(VA.getValNo() != LastVal &&
2459            "Don't support value assigned to multiple locs yet");
2460     (void)LastVal;
2461     LastVal = VA.getValNo();
2462
2463     if (VA.isRegLoc()) {
2464       EVT RegVT = VA.getLocVT();
2465       const TargetRegisterClass *RC;
2466       if (RegVT == MVT::i32)
2467         RC = &X86::GR32RegClass;
2468       else if (Is64Bit && RegVT == MVT::i64)
2469         RC = &X86::GR64RegClass;
2470       else if (RegVT == MVT::f32)
2471         RC = &X86::FR32RegClass;
2472       else if (RegVT == MVT::f64)
2473         RC = &X86::FR64RegClass;
2474       else if (RegVT.is512BitVector())
2475         RC = &X86::VR512RegClass;
2476       else if (RegVT.is256BitVector())
2477         RC = &X86::VR256RegClass;
2478       else if (RegVT.is128BitVector())
2479         RC = &X86::VR128RegClass;
2480       else if (RegVT == MVT::x86mmx)
2481         RC = &X86::VR64RegClass;
2482       else if (RegVT == MVT::i1)
2483         RC = &X86::VK1RegClass;
2484       else if (RegVT == MVT::v8i1)
2485         RC = &X86::VK8RegClass;
2486       else if (RegVT == MVT::v16i1)
2487         RC = &X86::VK16RegClass;
2488       else if (RegVT == MVT::v32i1)
2489         RC = &X86::VK32RegClass;
2490       else if (RegVT == MVT::v64i1)
2491         RC = &X86::VK64RegClass;
2492       else
2493         llvm_unreachable("Unknown argument type!");
2494
2495       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2496       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2497
2498       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2499       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2500       // right size.
2501       if (VA.getLocInfo() == CCValAssign::SExt)
2502         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2503                                DAG.getValueType(VA.getValVT()));
2504       else if (VA.getLocInfo() == CCValAssign::ZExt)
2505         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2506                                DAG.getValueType(VA.getValVT()));
2507       else if (VA.getLocInfo() == CCValAssign::BCvt)
2508         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2509
2510       if (VA.isExtInLoc()) {
2511         // Handle MMX values passed in XMM regs.
2512         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2513           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2514         else
2515           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2516       }
2517     } else {
2518       assert(VA.isMemLoc());
2519       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2520     }
2521
2522     // If value is passed via pointer - do a load.
2523     if (VA.getLocInfo() == CCValAssign::Indirect)
2524       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2525                              MachinePointerInfo(), false, false, false, 0);
2526
2527     InVals.push_back(ArgValue);
2528   }
2529
2530   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2531     // All x86 ABIs require that for returning structs by value we copy the
2532     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2533     // the argument into a virtual register so that we can access it from the
2534     // return points.
2535     if (Ins[i].Flags.isSRet()) {
2536       unsigned Reg = FuncInfo->getSRetReturnReg();
2537       if (!Reg) {
2538         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2539         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2540         FuncInfo->setSRetReturnReg(Reg);
2541       }
2542       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2543       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2544       break;
2545     }
2546   }
2547
2548   unsigned StackSize = CCInfo.getNextStackOffset();
2549   // Align stack specially for tail calls.
2550   if (FuncIsMadeTailCallSafe(CallConv,
2551                              MF.getTarget().Options.GuaranteedTailCallOpt))
2552     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2553
2554   // If the function takes variable number of arguments, make a frame index for
2555   // the start of the first vararg value... for expansion of llvm.va_start. We
2556   // can skip this if there are no va_start calls.
2557   if (MFI->hasVAStart() &&
2558       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2559                    CallConv != CallingConv::X86_ThisCall))) {
2560     FuncInfo->setVarArgsFrameIndex(
2561         MFI->CreateFixedObject(1, StackSize, true));
2562   }
2563
2564   MachineModuleInfo &MMI = MF.getMMI();
2565   const Function *WinEHParent = nullptr;
2566   if (MMI.hasWinEHFuncInfo(Fn))
2567     WinEHParent = MMI.getWinEHParent(Fn);
2568   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2569   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2570
2571   // Figure out if XMM registers are in use.
2572   assert(!(Subtarget->useSoftFloat() &&
2573            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2574          "SSE register cannot be used when SSE is disabled!");
2575
2576   // 64-bit calling conventions support varargs and register parameters, so we
2577   // have to do extra work to spill them in the prologue.
2578   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2579     // Find the first unallocated argument registers.
2580     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2581     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2582     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2583     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2584     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2585            "SSE register cannot be used when SSE is disabled!");
2586
2587     // Gather all the live in physical registers.
2588     SmallVector<SDValue, 6> LiveGPRs;
2589     SmallVector<SDValue, 8> LiveXMMRegs;
2590     SDValue ALVal;
2591     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2592       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2593       LiveGPRs.push_back(
2594           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2595     }
2596     if (!ArgXMMs.empty()) {
2597       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2598       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2599       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2600         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2601         LiveXMMRegs.push_back(
2602             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2603       }
2604     }
2605
2606     if (IsWin64) {
2607       // Get to the caller-allocated home save location.  Add 8 to account
2608       // for the return address.
2609       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2610       FuncInfo->setRegSaveFrameIndex(
2611           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2612       // Fixup to set vararg frame on shadow area (4 x i64).
2613       if (NumIntRegs < 4)
2614         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2615     } else {
2616       // For X86-64, if there are vararg parameters that are passed via
2617       // registers, then we must store them to their spots on the stack so
2618       // they may be loaded by deferencing the result of va_next.
2619       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2620       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2621       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2622           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2623     }
2624
2625     // Store the integer parameter registers.
2626     SmallVector<SDValue, 8> MemOps;
2627     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2628                                       getPointerTy(DAG.getDataLayout()));
2629     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2630     for (SDValue Val : LiveGPRs) {
2631       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2632                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2633       SDValue Store =
2634         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2635                      MachinePointerInfo::getFixedStack(
2636                        FuncInfo->getRegSaveFrameIndex(), Offset),
2637                      false, false, 0);
2638       MemOps.push_back(Store);
2639       Offset += 8;
2640     }
2641
2642     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2643       // Now store the XMM (fp + vector) parameter registers.
2644       SmallVector<SDValue, 12> SaveXMMOps;
2645       SaveXMMOps.push_back(Chain);
2646       SaveXMMOps.push_back(ALVal);
2647       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2648                              FuncInfo->getRegSaveFrameIndex(), dl));
2649       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2650                              FuncInfo->getVarArgsFPOffset(), dl));
2651       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2652                         LiveXMMRegs.end());
2653       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2654                                    MVT::Other, SaveXMMOps));
2655     }
2656
2657     if (!MemOps.empty())
2658       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2659   } else if (IsWin64 && IsWinEHOutlined) {
2660     // Get to the caller-allocated home save location.  Add 8 to account
2661     // for the return address.
2662     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2663     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2664         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2665
2666     MMI.getWinEHFuncInfo(Fn)
2667         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2668         FuncInfo->getRegSaveFrameIndex();
2669
2670     // Store the second integer parameter (rdx) into rsp+16 relative to the
2671     // stack pointer at the entry of the function.
2672     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2673                                       getPointerTy(DAG.getDataLayout()));
2674     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2675     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2676     Chain = DAG.getStore(
2677         Val.getValue(1), dl, Val, RSFIN,
2678         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2679         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2680   }
2681
2682   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2683     // Find the largest legal vector type.
2684     MVT VecVT = MVT::Other;
2685     // FIXME: Only some x86_32 calling conventions support AVX512.
2686     if (Subtarget->hasAVX512() &&
2687         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2688                      CallConv == CallingConv::Intel_OCL_BI)))
2689       VecVT = MVT::v16f32;
2690     else if (Subtarget->hasAVX())
2691       VecVT = MVT::v8f32;
2692     else if (Subtarget->hasSSE2())
2693       VecVT = MVT::v4f32;
2694
2695     // We forward some GPRs and some vector types.
2696     SmallVector<MVT, 2> RegParmTypes;
2697     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2698     RegParmTypes.push_back(IntVT);
2699     if (VecVT != MVT::Other)
2700       RegParmTypes.push_back(VecVT);
2701
2702     // Compute the set of forwarded registers. The rest are scratch.
2703     SmallVectorImpl<ForwardedRegister> &Forwards =
2704         FuncInfo->getForwardedMustTailRegParms();
2705     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2706
2707     // Conservatively forward AL on x86_64, since it might be used for varargs.
2708     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2709       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2710       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2711     }
2712
2713     // Copy all forwards from physical to virtual registers.
2714     for (ForwardedRegister &F : Forwards) {
2715       // FIXME: Can we use a less constrained schedule?
2716       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2717       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2718       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2719     }
2720   }
2721
2722   // Some CCs need callee pop.
2723   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2724                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2725     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2726   } else {
2727     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2728     // If this is an sret function, the return should pop the hidden pointer.
2729     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2730         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2731         argsAreStructReturn(Ins) == StackStructReturn)
2732       FuncInfo->setBytesToPopOnReturn(4);
2733   }
2734
2735   if (!Is64Bit) {
2736     // RegSaveFrameIndex is X86-64 only.
2737     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2738     if (CallConv == CallingConv::X86_FastCall ||
2739         CallConv == CallingConv::X86_ThisCall)
2740       // fastcc functions can't have varargs.
2741       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2742   }
2743
2744   FuncInfo->setArgumentStackSize(StackSize);
2745
2746   if (IsWinEHParent) {
2747     if (Is64Bit) {
2748       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2749       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2750       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2751       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2752       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2753                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2754                            /*isVolatile=*/true,
2755                            /*isNonTemporal=*/false, /*Alignment=*/0);
2756     } else {
2757       // Functions using Win32 EH are considered to have opaque SP adjustments
2758       // to force local variables to be addressed from the frame or base
2759       // pointers.
2760       MFI->setHasOpaqueSPAdjustment(true);
2761     }
2762   }
2763
2764   return Chain;
2765 }
2766
2767 SDValue
2768 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2769                                     SDValue StackPtr, SDValue Arg,
2770                                     SDLoc dl, SelectionDAG &DAG,
2771                                     const CCValAssign &VA,
2772                                     ISD::ArgFlagsTy Flags) const {
2773   unsigned LocMemOffset = VA.getLocMemOffset();
2774   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2775   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2776                        StackPtr, PtrOff);
2777   if (Flags.isByVal())
2778     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2779
2780   return DAG.getStore(Chain, dl, Arg, PtrOff,
2781                       MachinePointerInfo::getStack(LocMemOffset),
2782                       false, false, 0);
2783 }
2784
2785 /// Emit a load of return address if tail call
2786 /// optimization is performed and it is required.
2787 SDValue
2788 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2789                                            SDValue &OutRetAddr, SDValue Chain,
2790                                            bool IsTailCall, bool Is64Bit,
2791                                            int FPDiff, SDLoc dl) const {
2792   // Adjust the Return address stack slot.
2793   EVT VT = getPointerTy(DAG.getDataLayout());
2794   OutRetAddr = getReturnAddressFrameIndex(DAG);
2795
2796   // Load the "old" Return address.
2797   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2798                            false, false, false, 0);
2799   return SDValue(OutRetAddr.getNode(), 1);
2800 }
2801
2802 /// Emit a store of the return address if tail call
2803 /// optimization is performed and it is required (FPDiff!=0).
2804 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2805                                         SDValue Chain, SDValue RetAddrFrIdx,
2806                                         EVT PtrVT, unsigned SlotSize,
2807                                         int FPDiff, SDLoc dl) {
2808   // Store the return address to the appropriate stack slot.
2809   if (!FPDiff) return Chain;
2810   // Calculate the new stack slot for the return address.
2811   int NewReturnAddrFI =
2812     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2813                                          false);
2814   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2815   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2816                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2817                        false, false, 0);
2818   return Chain;
2819 }
2820
2821 SDValue
2822 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2823                              SmallVectorImpl<SDValue> &InVals) const {
2824   SelectionDAG &DAG                     = CLI.DAG;
2825   SDLoc &dl                             = CLI.DL;
2826   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2827   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2828   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2829   SDValue Chain                         = CLI.Chain;
2830   SDValue Callee                        = CLI.Callee;
2831   CallingConv::ID CallConv              = CLI.CallConv;
2832   bool &isTailCall                      = CLI.IsTailCall;
2833   bool isVarArg                         = CLI.IsVarArg;
2834
2835   MachineFunction &MF = DAG.getMachineFunction();
2836   bool Is64Bit        = Subtarget->is64Bit();
2837   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2838   StructReturnType SR = callIsStructReturn(Outs);
2839   bool IsSibcall      = false;
2840   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2841   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2842
2843   if (Attr.getValueAsString() == "true")
2844     isTailCall = false;
2845
2846   if (Subtarget->isPICStyleGOT() &&
2847       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2848     // If we are using a GOT, disable tail calls to external symbols with
2849     // default visibility. Tail calling such a symbol requires using a GOT
2850     // relocation, which forces early binding of the symbol. This breaks code
2851     // that require lazy function symbol resolution. Using musttail or
2852     // GuaranteedTailCallOpt will override this.
2853     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2854     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2855                G->getGlobal()->hasDefaultVisibility()))
2856       isTailCall = false;
2857   }
2858
2859   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2860   if (IsMustTail) {
2861     // Force this to be a tail call.  The verifier rules are enough to ensure
2862     // that we can lower this successfully without moving the return address
2863     // around.
2864     isTailCall = true;
2865   } else if (isTailCall) {
2866     // Check if it's really possible to do a tail call.
2867     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2868                     isVarArg, SR != NotStructReturn,
2869                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2870                     Outs, OutVals, Ins, DAG);
2871
2872     // Sibcalls are automatically detected tailcalls which do not require
2873     // ABI changes.
2874     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2875       IsSibcall = true;
2876
2877     if (isTailCall)
2878       ++NumTailCalls;
2879   }
2880
2881   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2882          "Var args not supported with calling convention fastcc, ghc or hipe");
2883
2884   // Analyze operands of the call, assigning locations to each operand.
2885   SmallVector<CCValAssign, 16> ArgLocs;
2886   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2887
2888   // Allocate shadow area for Win64
2889   if (IsWin64)
2890     CCInfo.AllocateStack(32, 8);
2891
2892   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2893
2894   // Get a count of how many bytes are to be pushed on the stack.
2895   unsigned NumBytes = CCInfo.getNextStackOffset();
2896   if (IsSibcall)
2897     // This is a sibcall. The memory operands are available in caller's
2898     // own caller's stack.
2899     NumBytes = 0;
2900   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2901            IsTailCallConvention(CallConv))
2902     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2903
2904   int FPDiff = 0;
2905   if (isTailCall && !IsSibcall && !IsMustTail) {
2906     // Lower arguments at fp - stackoffset + fpdiff.
2907     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2908
2909     FPDiff = NumBytesCallerPushed - NumBytes;
2910
2911     // Set the delta of movement of the returnaddr stackslot.
2912     // But only set if delta is greater than previous delta.
2913     if (FPDiff < X86Info->getTCReturnAddrDelta())
2914       X86Info->setTCReturnAddrDelta(FPDiff);
2915   }
2916
2917   unsigned NumBytesToPush = NumBytes;
2918   unsigned NumBytesToPop = NumBytes;
2919
2920   // If we have an inalloca argument, all stack space has already been allocated
2921   // for us and be right at the top of the stack.  We don't support multiple
2922   // arguments passed in memory when using inalloca.
2923   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2924     NumBytesToPush = 0;
2925     if (!ArgLocs.back().isMemLoc())
2926       report_fatal_error("cannot use inalloca attribute on a register "
2927                          "parameter");
2928     if (ArgLocs.back().getLocMemOffset() != 0)
2929       report_fatal_error("any parameter with the inalloca attribute must be "
2930                          "the only memory argument");
2931   }
2932
2933   if (!IsSibcall)
2934     Chain = DAG.getCALLSEQ_START(
2935         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2936
2937   SDValue RetAddrFrIdx;
2938   // Load return address for tail calls.
2939   if (isTailCall && FPDiff)
2940     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2941                                     Is64Bit, FPDiff, dl);
2942
2943   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2944   SmallVector<SDValue, 8> MemOpChains;
2945   SDValue StackPtr;
2946
2947   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2948   // of tail call optimization arguments are handle later.
2949   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2950   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2951     // Skip inalloca arguments, they have already been written.
2952     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2953     if (Flags.isInAlloca())
2954       continue;
2955
2956     CCValAssign &VA = ArgLocs[i];
2957     EVT RegVT = VA.getLocVT();
2958     SDValue Arg = OutVals[i];
2959     bool isByVal = Flags.isByVal();
2960
2961     // Promote the value if needed.
2962     switch (VA.getLocInfo()) {
2963     default: llvm_unreachable("Unknown loc info!");
2964     case CCValAssign::Full: break;
2965     case CCValAssign::SExt:
2966       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2967       break;
2968     case CCValAssign::ZExt:
2969       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2970       break;
2971     case CCValAssign::AExt:
2972       if (Arg.getValueType().isVector() &&
2973           Arg.getValueType().getScalarType() == MVT::i1)
2974         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2975       else if (RegVT.is128BitVector()) {
2976         // Special case: passing MMX values in XMM registers.
2977         Arg = DAG.getBitcast(MVT::i64, Arg);
2978         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2979         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2980       } else
2981         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2982       break;
2983     case CCValAssign::BCvt:
2984       Arg = DAG.getBitcast(RegVT, Arg);
2985       break;
2986     case CCValAssign::Indirect: {
2987       // Store the argument.
2988       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2989       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2990       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2991                            MachinePointerInfo::getFixedStack(FI),
2992                            false, false, 0);
2993       Arg = SpillSlot;
2994       break;
2995     }
2996     }
2997
2998     if (VA.isRegLoc()) {
2999       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3000       if (isVarArg && IsWin64) {
3001         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3002         // shadow reg if callee is a varargs function.
3003         unsigned ShadowReg = 0;
3004         switch (VA.getLocReg()) {
3005         case X86::XMM0: ShadowReg = X86::RCX; break;
3006         case X86::XMM1: ShadowReg = X86::RDX; break;
3007         case X86::XMM2: ShadowReg = X86::R8; break;
3008         case X86::XMM3: ShadowReg = X86::R9; break;
3009         }
3010         if (ShadowReg)
3011           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3012       }
3013     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3014       assert(VA.isMemLoc());
3015       if (!StackPtr.getNode())
3016         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3017                                       getPointerTy(DAG.getDataLayout()));
3018       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3019                                              dl, DAG, VA, Flags));
3020     }
3021   }
3022
3023   if (!MemOpChains.empty())
3024     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3025
3026   if (Subtarget->isPICStyleGOT()) {
3027     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3028     // GOT pointer.
3029     if (!isTailCall) {
3030       RegsToPass.push_back(std::make_pair(
3031           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3032                                           getPointerTy(DAG.getDataLayout()))));
3033     } else {
3034       // If we are tail calling and generating PIC/GOT style code load the
3035       // address of the callee into ECX. The value in ecx is used as target of
3036       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3037       // for tail calls on PIC/GOT architectures. Normally we would just put the
3038       // address of GOT into ebx and then call target@PLT. But for tail calls
3039       // ebx would be restored (since ebx is callee saved) before jumping to the
3040       // target@PLT.
3041
3042       // Note: The actual moving to ECX is done further down.
3043       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3044       if (G && !G->getGlobal()->hasLocalLinkage() &&
3045           G->getGlobal()->hasDefaultVisibility())
3046         Callee = LowerGlobalAddress(Callee, DAG);
3047       else if (isa<ExternalSymbolSDNode>(Callee))
3048         Callee = LowerExternalSymbol(Callee, DAG);
3049     }
3050   }
3051
3052   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3053     // From AMD64 ABI document:
3054     // For calls that may call functions that use varargs or stdargs
3055     // (prototype-less calls or calls to functions containing ellipsis (...) in
3056     // the declaration) %al is used as hidden argument to specify the number
3057     // of SSE registers used. The contents of %al do not need to match exactly
3058     // the number of registers, but must be an ubound on the number of SSE
3059     // registers used and is in the range 0 - 8 inclusive.
3060
3061     // Count the number of XMM registers allocated.
3062     static const MCPhysReg XMMArgRegs[] = {
3063       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3064       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3065     };
3066     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3067     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3068            && "SSE registers cannot be used when SSE is disabled");
3069
3070     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3071                                         DAG.getConstant(NumXMMRegs, dl,
3072                                                         MVT::i8)));
3073   }
3074
3075   if (isVarArg && IsMustTail) {
3076     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3077     for (const auto &F : Forwards) {
3078       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3079       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3080     }
3081   }
3082
3083   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3084   // don't need this because the eligibility check rejects calls that require
3085   // shuffling arguments passed in memory.
3086   if (!IsSibcall && isTailCall) {
3087     // Force all the incoming stack arguments to be loaded from the stack
3088     // before any new outgoing arguments are stored to the stack, because the
3089     // outgoing stack slots may alias the incoming argument stack slots, and
3090     // the alias isn't otherwise explicit. This is slightly more conservative
3091     // than necessary, because it means that each store effectively depends
3092     // on every argument instead of just those arguments it would clobber.
3093     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3094
3095     SmallVector<SDValue, 8> MemOpChains2;
3096     SDValue FIN;
3097     int FI = 0;
3098     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3099       CCValAssign &VA = ArgLocs[i];
3100       if (VA.isRegLoc())
3101         continue;
3102       assert(VA.isMemLoc());
3103       SDValue Arg = OutVals[i];
3104       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3105       // Skip inalloca arguments.  They don't require any work.
3106       if (Flags.isInAlloca())
3107         continue;
3108       // Create frame index.
3109       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3110       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3111       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3112       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3113
3114       if (Flags.isByVal()) {
3115         // Copy relative to framepointer.
3116         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3117         if (!StackPtr.getNode())
3118           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3119                                         getPointerTy(DAG.getDataLayout()));
3120         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3121                              StackPtr, Source);
3122
3123         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3124                                                          ArgChain,
3125                                                          Flags, DAG, dl));
3126       } else {
3127         // Store relative to framepointer.
3128         MemOpChains2.push_back(
3129           DAG.getStore(ArgChain, dl, Arg, FIN,
3130                        MachinePointerInfo::getFixedStack(FI),
3131                        false, false, 0));
3132       }
3133     }
3134
3135     if (!MemOpChains2.empty())
3136       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3137
3138     // Store the return address to the appropriate stack slot.
3139     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3140                                      getPointerTy(DAG.getDataLayout()),
3141                                      RegInfo->getSlotSize(), FPDiff, dl);
3142   }
3143
3144   // Build a sequence of copy-to-reg nodes chained together with token chain
3145   // and flag operands which copy the outgoing args into registers.
3146   SDValue InFlag;
3147   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3148     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3149                              RegsToPass[i].second, InFlag);
3150     InFlag = Chain.getValue(1);
3151   }
3152
3153   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3154     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3155     // In the 64-bit large code model, we have to make all calls
3156     // through a register, since the call instruction's 32-bit
3157     // pc-relative offset may not be large enough to hold the whole
3158     // address.
3159   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3160     // If the callee is a GlobalAddress node (quite common, every direct call
3161     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3162     // it.
3163     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3164
3165     // We should use extra load for direct calls to dllimported functions in
3166     // non-JIT mode.
3167     const GlobalValue *GV = G->getGlobal();
3168     if (!GV->hasDLLImportStorageClass()) {
3169       unsigned char OpFlags = 0;
3170       bool ExtraLoad = false;
3171       unsigned WrapperKind = ISD::DELETED_NODE;
3172
3173       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3174       // external symbols most go through the PLT in PIC mode.  If the symbol
3175       // has hidden or protected visibility, or if it is static or local, then
3176       // we don't need to use the PLT - we can directly call it.
3177       if (Subtarget->isTargetELF() &&
3178           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3179           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3180         OpFlags = X86II::MO_PLT;
3181       } else if (Subtarget->isPICStyleStubAny() &&
3182                  !GV->isStrongDefinitionForLinker() &&
3183                  (!Subtarget->getTargetTriple().isMacOSX() ||
3184                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3185         // PC-relative references to external symbols should go through $stub,
3186         // unless we're building with the leopard linker or later, which
3187         // automatically synthesizes these stubs.
3188         OpFlags = X86II::MO_DARWIN_STUB;
3189       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3190                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3191         // If the function is marked as non-lazy, generate an indirect call
3192         // which loads from the GOT directly. This avoids runtime overhead
3193         // at the cost of eager binding (and one extra byte of encoding).
3194         OpFlags = X86II::MO_GOTPCREL;
3195         WrapperKind = X86ISD::WrapperRIP;
3196         ExtraLoad = true;
3197       }
3198
3199       Callee = DAG.getTargetGlobalAddress(
3200           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3201
3202       // Add a wrapper if needed.
3203       if (WrapperKind != ISD::DELETED_NODE)
3204         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3205                              getPointerTy(DAG.getDataLayout()), Callee);
3206       // Add extra indirection if needed.
3207       if (ExtraLoad)
3208         Callee = DAG.getLoad(
3209             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3210             MachinePointerInfo::getGOT(), false, false, false, 0);
3211     }
3212   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3213     unsigned char OpFlags = 0;
3214
3215     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3216     // external symbols should go through the PLT.
3217     if (Subtarget->isTargetELF() &&
3218         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3219       OpFlags = X86II::MO_PLT;
3220     } else if (Subtarget->isPICStyleStubAny() &&
3221                (!Subtarget->getTargetTriple().isMacOSX() ||
3222                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3223       // PC-relative references to external symbols should go through $stub,
3224       // unless we're building with the leopard linker or later, which
3225       // automatically synthesizes these stubs.
3226       OpFlags = X86II::MO_DARWIN_STUB;
3227     }
3228
3229     Callee = DAG.getTargetExternalSymbol(
3230         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3231   } else if (Subtarget->isTarget64BitILP32() &&
3232              Callee->getValueType(0) == MVT::i32) {
3233     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3234     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3235   }
3236
3237   // Returns a chain & a flag for retval copy to use.
3238   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3239   SmallVector<SDValue, 8> Ops;
3240
3241   if (!IsSibcall && isTailCall) {
3242     Chain = DAG.getCALLSEQ_END(Chain,
3243                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3244                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3245     InFlag = Chain.getValue(1);
3246   }
3247
3248   Ops.push_back(Chain);
3249   Ops.push_back(Callee);
3250
3251   if (isTailCall)
3252     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3253
3254   // Add argument registers to the end of the list so that they are known live
3255   // into the call.
3256   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3257     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3258                                   RegsToPass[i].second.getValueType()));
3259
3260   // Add a register mask operand representing the call-preserved registers.
3261   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3262   assert(Mask && "Missing call preserved mask for calling convention");
3263
3264   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3265   // the function clobbers all registers. If an exception is thrown, the runtime
3266   // will not restore CSRs.
3267   // FIXME: Model this more precisely so that we can register allocate across
3268   // the normal edge and spill and fill across the exceptional edge.
3269   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3270     const Function *CallerFn = MF.getFunction();
3271     EHPersonality Pers =
3272         CallerFn->hasPersonalityFn()
3273             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3274             : EHPersonality::Unknown;
3275     if (isMSVCEHPersonality(Pers))
3276       Mask = RegInfo->getNoPreservedMask();
3277   }
3278
3279   Ops.push_back(DAG.getRegisterMask(Mask));
3280
3281   if (InFlag.getNode())
3282     Ops.push_back(InFlag);
3283
3284   if (isTailCall) {
3285     // We used to do:
3286     //// If this is the first return lowered for this function, add the regs
3287     //// to the liveout set for the function.
3288     // This isn't right, although it's probably harmless on x86; liveouts
3289     // should be computed from returns not tail calls.  Consider a void
3290     // function making a tail call to a function returning int.
3291     MF.getFrameInfo()->setHasTailCall();
3292     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3293   }
3294
3295   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3296   InFlag = Chain.getValue(1);
3297
3298   // Create the CALLSEQ_END node.
3299   unsigned NumBytesForCalleeToPop;
3300   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3301                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3302     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3303   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3304            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3305            SR == StackStructReturn)
3306     // If this is a call to a struct-return function, the callee
3307     // pops the hidden struct pointer, so we have to push it back.
3308     // This is common for Darwin/X86, Linux & Mingw32 targets.
3309     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3310     NumBytesForCalleeToPop = 4;
3311   else
3312     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3313
3314   // Returns a flag for retval copy to use.
3315   if (!IsSibcall) {
3316     Chain = DAG.getCALLSEQ_END(Chain,
3317                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3318                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3319                                                      true),
3320                                InFlag, dl);
3321     InFlag = Chain.getValue(1);
3322   }
3323
3324   // Handle result values, copying them out of physregs into vregs that we
3325   // return.
3326   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3327                          Ins, dl, DAG, InVals);
3328 }
3329
3330 //===----------------------------------------------------------------------===//
3331 //                Fast Calling Convention (tail call) implementation
3332 //===----------------------------------------------------------------------===//
3333
3334 //  Like std call, callee cleans arguments, convention except that ECX is
3335 //  reserved for storing the tail called function address. Only 2 registers are
3336 //  free for argument passing (inreg). Tail call optimization is performed
3337 //  provided:
3338 //                * tailcallopt is enabled
3339 //                * caller/callee are fastcc
3340 //  On X86_64 architecture with GOT-style position independent code only local
3341 //  (within module) calls are supported at the moment.
3342 //  To keep the stack aligned according to platform abi the function
3343 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3344 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3345 //  If a tail called function callee has more arguments than the caller the
3346 //  caller needs to make sure that there is room to move the RETADDR to. This is
3347 //  achieved by reserving an area the size of the argument delta right after the
3348 //  original RETADDR, but before the saved framepointer or the spilled registers
3349 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3350 //  stack layout:
3351 //    arg1
3352 //    arg2
3353 //    RETADDR
3354 //    [ new RETADDR
3355 //      move area ]
3356 //    (possible EBP)
3357 //    ESI
3358 //    EDI
3359 //    local1 ..
3360
3361 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3362 /// for a 16 byte align requirement.
3363 unsigned
3364 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3365                                                SelectionDAG& DAG) const {
3366   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3367   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3368   unsigned StackAlignment = TFI.getStackAlignment();
3369   uint64_t AlignMask = StackAlignment - 1;
3370   int64_t Offset = StackSize;
3371   unsigned SlotSize = RegInfo->getSlotSize();
3372   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3373     // Number smaller than 12 so just add the difference.
3374     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3375   } else {
3376     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3377     Offset = ((~AlignMask) & Offset) + StackAlignment +
3378       (StackAlignment-SlotSize);
3379   }
3380   return Offset;
3381 }
3382
3383 /// MatchingStackOffset - Return true if the given stack call argument is
3384 /// already available in the same position (relatively) of the caller's
3385 /// incoming argument stack.
3386 static
3387 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3388                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3389                          const X86InstrInfo *TII) {
3390   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3391   int FI = INT_MAX;
3392   if (Arg.getOpcode() == ISD::CopyFromReg) {
3393     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3394     if (!TargetRegisterInfo::isVirtualRegister(VR))
3395       return false;
3396     MachineInstr *Def = MRI->getVRegDef(VR);
3397     if (!Def)
3398       return false;
3399     if (!Flags.isByVal()) {
3400       if (!TII->isLoadFromStackSlot(Def, FI))
3401         return false;
3402     } else {
3403       unsigned Opcode = Def->getOpcode();
3404       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3405            Opcode == X86::LEA64_32r) &&
3406           Def->getOperand(1).isFI()) {
3407         FI = Def->getOperand(1).getIndex();
3408         Bytes = Flags.getByValSize();
3409       } else
3410         return false;
3411     }
3412   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3413     if (Flags.isByVal())
3414       // ByVal argument is passed in as a pointer but it's now being
3415       // dereferenced. e.g.
3416       // define @foo(%struct.X* %A) {
3417       //   tail call @bar(%struct.X* byval %A)
3418       // }
3419       return false;
3420     SDValue Ptr = Ld->getBasePtr();
3421     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3422     if (!FINode)
3423       return false;
3424     FI = FINode->getIndex();
3425   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3426     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3427     FI = FINode->getIndex();
3428     Bytes = Flags.getByValSize();
3429   } else
3430     return false;
3431
3432   assert(FI != INT_MAX);
3433   if (!MFI->isFixedObjectIndex(FI))
3434     return false;
3435   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3436 }
3437
3438 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3439 /// for tail call optimization. Targets which want to do tail call
3440 /// optimization should implement this function.
3441 bool
3442 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3443                                                      CallingConv::ID CalleeCC,
3444                                                      bool isVarArg,
3445                                                      bool isCalleeStructRet,
3446                                                      bool isCallerStructRet,
3447                                                      Type *RetTy,
3448                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3449                                     const SmallVectorImpl<SDValue> &OutVals,
3450                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3451                                                      SelectionDAG &DAG) const {
3452   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3453     return false;
3454
3455   // If -tailcallopt is specified, make fastcc functions tail-callable.
3456   const MachineFunction &MF = DAG.getMachineFunction();
3457   const Function *CallerF = MF.getFunction();
3458
3459   // If the function return type is x86_fp80 and the callee return type is not,
3460   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3461   // perform a tailcall optimization here.
3462   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3463     return false;
3464
3465   CallingConv::ID CallerCC = CallerF->getCallingConv();
3466   bool CCMatch = CallerCC == CalleeCC;
3467   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3468   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3469
3470   // Win64 functions have extra shadow space for argument homing. Don't do the
3471   // sibcall if the caller and callee have mismatched expectations for this
3472   // space.
3473   if (IsCalleeWin64 != IsCallerWin64)
3474     return false;
3475
3476   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3477     if (IsTailCallConvention(CalleeCC) && CCMatch)
3478       return true;
3479     return false;
3480   }
3481
3482   // Look for obvious safe cases to perform tail call optimization that do not
3483   // require ABI changes. This is what gcc calls sibcall.
3484
3485   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3486   // emit a special epilogue.
3487   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3488   if (RegInfo->needsStackRealignment(MF))
3489     return false;
3490
3491   // Also avoid sibcall optimization if either caller or callee uses struct
3492   // return semantics.
3493   if (isCalleeStructRet || isCallerStructRet)
3494     return false;
3495
3496   // An stdcall/thiscall caller is expected to clean up its arguments; the
3497   // callee isn't going to do that.
3498   // FIXME: this is more restrictive than needed. We could produce a tailcall
3499   // when the stack adjustment matches. For example, with a thiscall that takes
3500   // only one argument.
3501   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3502                    CallerCC == CallingConv::X86_ThisCall))
3503     return false;
3504
3505   // Do not sibcall optimize vararg calls unless all arguments are passed via
3506   // registers.
3507   if (isVarArg && !Outs.empty()) {
3508
3509     // Optimizing for varargs on Win64 is unlikely to be safe without
3510     // additional testing.
3511     if (IsCalleeWin64 || IsCallerWin64)
3512       return false;
3513
3514     SmallVector<CCValAssign, 16> ArgLocs;
3515     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3516                    *DAG.getContext());
3517
3518     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3519     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3520       if (!ArgLocs[i].isRegLoc())
3521         return false;
3522   }
3523
3524   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3525   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3526   // this into a sibcall.
3527   bool Unused = false;
3528   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3529     if (!Ins[i].Used) {
3530       Unused = true;
3531       break;
3532     }
3533   }
3534   if (Unused) {
3535     SmallVector<CCValAssign, 16> RVLocs;
3536     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3537                    *DAG.getContext());
3538     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3539     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3540       CCValAssign &VA = RVLocs[i];
3541       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3542         return false;
3543     }
3544   }
3545
3546   // If the calling conventions do not match, then we'd better make sure the
3547   // results are returned in the same way as what the caller expects.
3548   if (!CCMatch) {
3549     SmallVector<CCValAssign, 16> RVLocs1;
3550     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3551                     *DAG.getContext());
3552     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3553
3554     SmallVector<CCValAssign, 16> RVLocs2;
3555     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3556                     *DAG.getContext());
3557     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3558
3559     if (RVLocs1.size() != RVLocs2.size())
3560       return false;
3561     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3562       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3563         return false;
3564       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3565         return false;
3566       if (RVLocs1[i].isRegLoc()) {
3567         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3568           return false;
3569       } else {
3570         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3571           return false;
3572       }
3573     }
3574   }
3575
3576   // If the callee takes no arguments then go on to check the results of the
3577   // call.
3578   if (!Outs.empty()) {
3579     // Check if stack adjustment is needed. For now, do not do this if any
3580     // argument is passed on the stack.
3581     SmallVector<CCValAssign, 16> ArgLocs;
3582     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3583                    *DAG.getContext());
3584
3585     // Allocate shadow area for Win64
3586     if (IsCalleeWin64)
3587       CCInfo.AllocateStack(32, 8);
3588
3589     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3590     if (CCInfo.getNextStackOffset()) {
3591       MachineFunction &MF = DAG.getMachineFunction();
3592       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3593         return false;
3594
3595       // Check if the arguments are already laid out in the right way as
3596       // the caller's fixed stack objects.
3597       MachineFrameInfo *MFI = MF.getFrameInfo();
3598       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3599       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3600       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3601         CCValAssign &VA = ArgLocs[i];
3602         SDValue Arg = OutVals[i];
3603         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3604         if (VA.getLocInfo() == CCValAssign::Indirect)
3605           return false;
3606         if (!VA.isRegLoc()) {
3607           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3608                                    MFI, MRI, TII))
3609             return false;
3610         }
3611       }
3612     }
3613
3614     // If the tailcall address may be in a register, then make sure it's
3615     // possible to register allocate for it. In 32-bit, the call address can
3616     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3617     // callee-saved registers are restored. These happen to be the same
3618     // registers used to pass 'inreg' arguments so watch out for those.
3619     if (!Subtarget->is64Bit() &&
3620         ((!isa<GlobalAddressSDNode>(Callee) &&
3621           !isa<ExternalSymbolSDNode>(Callee)) ||
3622          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3623       unsigned NumInRegs = 0;
3624       // In PIC we need an extra register to formulate the address computation
3625       // for the callee.
3626       unsigned MaxInRegs =
3627         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3628
3629       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3630         CCValAssign &VA = ArgLocs[i];
3631         if (!VA.isRegLoc())
3632           continue;
3633         unsigned Reg = VA.getLocReg();
3634         switch (Reg) {
3635         default: break;
3636         case X86::EAX: case X86::EDX: case X86::ECX:
3637           if (++NumInRegs == MaxInRegs)
3638             return false;
3639           break;
3640         }
3641       }
3642     }
3643   }
3644
3645   return true;
3646 }
3647
3648 FastISel *
3649 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3650                                   const TargetLibraryInfo *libInfo) const {
3651   return X86::createFastISel(funcInfo, libInfo);
3652 }
3653
3654 //===----------------------------------------------------------------------===//
3655 //                           Other Lowering Hooks
3656 //===----------------------------------------------------------------------===//
3657
3658 static bool MayFoldLoad(SDValue Op) {
3659   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3660 }
3661
3662 static bool MayFoldIntoStore(SDValue Op) {
3663   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3664 }
3665
3666 static bool isTargetShuffle(unsigned Opcode) {
3667   switch(Opcode) {
3668   default: return false;
3669   case X86ISD::BLENDI:
3670   case X86ISD::PSHUFB:
3671   case X86ISD::PSHUFD:
3672   case X86ISD::PSHUFHW:
3673   case X86ISD::PSHUFLW:
3674   case X86ISD::SHUFP:
3675   case X86ISD::PALIGNR:
3676   case X86ISD::MOVLHPS:
3677   case X86ISD::MOVLHPD:
3678   case X86ISD::MOVHLPS:
3679   case X86ISD::MOVLPS:
3680   case X86ISD::MOVLPD:
3681   case X86ISD::MOVSHDUP:
3682   case X86ISD::MOVSLDUP:
3683   case X86ISD::MOVDDUP:
3684   case X86ISD::MOVSS:
3685   case X86ISD::MOVSD:
3686   case X86ISD::UNPCKL:
3687   case X86ISD::UNPCKH:
3688   case X86ISD::VPERMILPI:
3689   case X86ISD::VPERM2X128:
3690   case X86ISD::VPERMI:
3691     return true;
3692   }
3693 }
3694
3695 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3696                                     SDValue V1, unsigned TargetMask,
3697                                     SelectionDAG &DAG) {
3698   switch(Opc) {
3699   default: llvm_unreachable("Unknown x86 shuffle node");
3700   case X86ISD::PSHUFD:
3701   case X86ISD::PSHUFHW:
3702   case X86ISD::PSHUFLW:
3703   case X86ISD::VPERMILPI:
3704   case X86ISD::VPERMI:
3705     return DAG.getNode(Opc, dl, VT, V1,
3706                        DAG.getConstant(TargetMask, dl, MVT::i8));
3707   }
3708 }
3709
3710 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3711                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3712   switch(Opc) {
3713   default: llvm_unreachable("Unknown x86 shuffle node");
3714   case X86ISD::MOVLHPS:
3715   case X86ISD::MOVLHPD:
3716   case X86ISD::MOVHLPS:
3717   case X86ISD::MOVLPS:
3718   case X86ISD::MOVLPD:
3719   case X86ISD::MOVSS:
3720   case X86ISD::MOVSD:
3721   case X86ISD::UNPCKL:
3722   case X86ISD::UNPCKH:
3723     return DAG.getNode(Opc, dl, VT, V1, V2);
3724   }
3725 }
3726
3727 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3728   MachineFunction &MF = DAG.getMachineFunction();
3729   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3730   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3731   int ReturnAddrIndex = FuncInfo->getRAIndex();
3732
3733   if (ReturnAddrIndex == 0) {
3734     // Set up a frame object for the return address.
3735     unsigned SlotSize = RegInfo->getSlotSize();
3736     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3737                                                            -(int64_t)SlotSize,
3738                                                            false);
3739     FuncInfo->setRAIndex(ReturnAddrIndex);
3740   }
3741
3742   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3743 }
3744
3745 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3746                                        bool hasSymbolicDisplacement) {
3747   // Offset should fit into 32 bit immediate field.
3748   if (!isInt<32>(Offset))
3749     return false;
3750
3751   // If we don't have a symbolic displacement - we don't have any extra
3752   // restrictions.
3753   if (!hasSymbolicDisplacement)
3754     return true;
3755
3756   // FIXME: Some tweaks might be needed for medium code model.
3757   if (M != CodeModel::Small && M != CodeModel::Kernel)
3758     return false;
3759
3760   // For small code model we assume that latest object is 16MB before end of 31
3761   // bits boundary. We may also accept pretty large negative constants knowing
3762   // that all objects are in the positive half of address space.
3763   if (M == CodeModel::Small && Offset < 16*1024*1024)
3764     return true;
3765
3766   // For kernel code model we know that all object resist in the negative half
3767   // of 32bits address space. We may not accept negative offsets, since they may
3768   // be just off and we may accept pretty large positive ones.
3769   if (M == CodeModel::Kernel && Offset >= 0)
3770     return true;
3771
3772   return false;
3773 }
3774
3775 /// isCalleePop - Determines whether the callee is required to pop its
3776 /// own arguments. Callee pop is necessary to support tail calls.
3777 bool X86::isCalleePop(CallingConv::ID CallingConv,
3778                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3779   switch (CallingConv) {
3780   default:
3781     return false;
3782   case CallingConv::X86_StdCall:
3783   case CallingConv::X86_FastCall:
3784   case CallingConv::X86_ThisCall:
3785     return !is64Bit;
3786   case CallingConv::Fast:
3787   case CallingConv::GHC:
3788   case CallingConv::HiPE:
3789     if (IsVarArg)
3790       return false;
3791     return TailCallOpt;
3792   }
3793 }
3794
3795 /// \brief Return true if the condition is an unsigned comparison operation.
3796 static bool isX86CCUnsigned(unsigned X86CC) {
3797   switch (X86CC) {
3798   default: llvm_unreachable("Invalid integer condition!");
3799   case X86::COND_E:     return true;
3800   case X86::COND_G:     return false;
3801   case X86::COND_GE:    return false;
3802   case X86::COND_L:     return false;
3803   case X86::COND_LE:    return false;
3804   case X86::COND_NE:    return true;
3805   case X86::COND_B:     return true;
3806   case X86::COND_A:     return true;
3807   case X86::COND_BE:    return true;
3808   case X86::COND_AE:    return true;
3809   }
3810   llvm_unreachable("covered switch fell through?!");
3811 }
3812
3813 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3814 /// specific condition code, returning the condition code and the LHS/RHS of the
3815 /// comparison to make.
3816 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3817                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3818   if (!isFP) {
3819     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3820       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3821         // X > -1   -> X == 0, jump !sign.
3822         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3823         return X86::COND_NS;
3824       }
3825       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3826         // X < 0   -> X == 0, jump on sign.
3827         return X86::COND_S;
3828       }
3829       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3830         // X < 1   -> X <= 0
3831         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3832         return X86::COND_LE;
3833       }
3834     }
3835
3836     switch (SetCCOpcode) {
3837     default: llvm_unreachable("Invalid integer condition!");
3838     case ISD::SETEQ:  return X86::COND_E;
3839     case ISD::SETGT:  return X86::COND_G;
3840     case ISD::SETGE:  return X86::COND_GE;
3841     case ISD::SETLT:  return X86::COND_L;
3842     case ISD::SETLE:  return X86::COND_LE;
3843     case ISD::SETNE:  return X86::COND_NE;
3844     case ISD::SETULT: return X86::COND_B;
3845     case ISD::SETUGT: return X86::COND_A;
3846     case ISD::SETULE: return X86::COND_BE;
3847     case ISD::SETUGE: return X86::COND_AE;
3848     }
3849   }
3850
3851   // First determine if it is required or is profitable to flip the operands.
3852
3853   // If LHS is a foldable load, but RHS is not, flip the condition.
3854   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3855       !ISD::isNON_EXTLoad(RHS.getNode())) {
3856     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3857     std::swap(LHS, RHS);
3858   }
3859
3860   switch (SetCCOpcode) {
3861   default: break;
3862   case ISD::SETOLT:
3863   case ISD::SETOLE:
3864   case ISD::SETUGT:
3865   case ISD::SETUGE:
3866     std::swap(LHS, RHS);
3867     break;
3868   }
3869
3870   // On a floating point condition, the flags are set as follows:
3871   // ZF  PF  CF   op
3872   //  0 | 0 | 0 | X > Y
3873   //  0 | 0 | 1 | X < Y
3874   //  1 | 0 | 0 | X == Y
3875   //  1 | 1 | 1 | unordered
3876   switch (SetCCOpcode) {
3877   default: llvm_unreachable("Condcode should be pre-legalized away");
3878   case ISD::SETUEQ:
3879   case ISD::SETEQ:   return X86::COND_E;
3880   case ISD::SETOLT:              // flipped
3881   case ISD::SETOGT:
3882   case ISD::SETGT:   return X86::COND_A;
3883   case ISD::SETOLE:              // flipped
3884   case ISD::SETOGE:
3885   case ISD::SETGE:   return X86::COND_AE;
3886   case ISD::SETUGT:              // flipped
3887   case ISD::SETULT:
3888   case ISD::SETLT:   return X86::COND_B;
3889   case ISD::SETUGE:              // flipped
3890   case ISD::SETULE:
3891   case ISD::SETLE:   return X86::COND_BE;
3892   case ISD::SETONE:
3893   case ISD::SETNE:   return X86::COND_NE;
3894   case ISD::SETUO:   return X86::COND_P;
3895   case ISD::SETO:    return X86::COND_NP;
3896   case ISD::SETOEQ:
3897   case ISD::SETUNE:  return X86::COND_INVALID;
3898   }
3899 }
3900
3901 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3902 /// code. Current x86 isa includes the following FP cmov instructions:
3903 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3904 static bool hasFPCMov(unsigned X86CC) {
3905   switch (X86CC) {
3906   default:
3907     return false;
3908   case X86::COND_B:
3909   case X86::COND_BE:
3910   case X86::COND_E:
3911   case X86::COND_P:
3912   case X86::COND_A:
3913   case X86::COND_AE:
3914   case X86::COND_NE:
3915   case X86::COND_NP:
3916     return true;
3917   }
3918 }
3919
3920 /// isFPImmLegal - Returns true if the target can instruction select the
3921 /// specified FP immediate natively. If false, the legalizer will
3922 /// materialize the FP immediate as a load from a constant pool.
3923 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3924   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3925     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3926       return true;
3927   }
3928   return false;
3929 }
3930
3931 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3932                                               ISD::LoadExtType ExtTy,
3933                                               EVT NewVT) const {
3934   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3935   // relocation target a movq or addq instruction: don't let the load shrink.
3936   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3937   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3938     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3939       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3940   return true;
3941 }
3942
3943 /// \brief Returns true if it is beneficial to convert a load of a constant
3944 /// to just the constant itself.
3945 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3946                                                           Type *Ty) const {
3947   assert(Ty->isIntegerTy());
3948
3949   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3950   if (BitSize == 0 || BitSize > 64)
3951     return false;
3952   return true;
3953 }
3954
3955 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3956                                                 unsigned Index) const {
3957   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3958     return false;
3959
3960   return (Index == 0 || Index == ResVT.getVectorNumElements());
3961 }
3962
3963 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3964   // Speculate cttz only if we can directly use TZCNT.
3965   return Subtarget->hasBMI();
3966 }
3967
3968 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3969   // Speculate ctlz only if we can directly use LZCNT.
3970   return Subtarget->hasLZCNT();
3971 }
3972
3973 /// isUndefInRange - Return true if every element in Mask, beginning
3974 /// from position Pos and ending in Pos+Size is undef.
3975 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3976   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
3977     if (0 <= Mask[i])
3978       return false;
3979   return true;
3980 }
3981
3982 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3983 /// the specified range (L, H].
3984 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3985   return (Val < 0) || (Val >= Low && Val < Hi);
3986 }
3987
3988 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3989 /// specified value.
3990 static bool isUndefOrEqual(int Val, int CmpVal) {
3991   return (Val < 0 || Val == CmpVal);
3992 }
3993
3994 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3995 /// from position Pos and ending in Pos+Size, falls within the specified
3996 /// sequential range (Low, Low+Size]. or is undef.
3997 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3998                                        unsigned Pos, unsigned Size, int Low) {
3999   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4000     if (!isUndefOrEqual(Mask[i], Low))
4001       return false;
4002   return true;
4003 }
4004
4005 /// isVEXTRACTIndex - Return true if the specified
4006 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4007 /// suitable for instruction that extract 128 or 256 bit vectors
4008 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4009   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4010   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4011     return false;
4012
4013   // The index should be aligned on a vecWidth-bit boundary.
4014   uint64_t Index =
4015     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4016
4017   MVT VT = N->getSimpleValueType(0);
4018   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4019   bool Result = (Index * ElSize) % vecWidth == 0;
4020
4021   return Result;
4022 }
4023
4024 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4025 /// operand specifies a subvector insert that is suitable for input to
4026 /// insertion of 128 or 256-bit subvectors
4027 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4028   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4029   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4030     return false;
4031   // The index should be aligned on a vecWidth-bit boundary.
4032   uint64_t Index =
4033     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4034
4035   MVT VT = N->getSimpleValueType(0);
4036   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4037   bool Result = (Index * ElSize) % vecWidth == 0;
4038
4039   return Result;
4040 }
4041
4042 bool X86::isVINSERT128Index(SDNode *N) {
4043   return isVINSERTIndex(N, 128);
4044 }
4045
4046 bool X86::isVINSERT256Index(SDNode *N) {
4047   return isVINSERTIndex(N, 256);
4048 }
4049
4050 bool X86::isVEXTRACT128Index(SDNode *N) {
4051   return isVEXTRACTIndex(N, 128);
4052 }
4053
4054 bool X86::isVEXTRACT256Index(SDNode *N) {
4055   return isVEXTRACTIndex(N, 256);
4056 }
4057
4058 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4059   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4060   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4061     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4062
4063   uint64_t Index =
4064     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4065
4066   MVT VecVT = N->getOperand(0).getSimpleValueType();
4067   MVT ElVT = VecVT.getVectorElementType();
4068
4069   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4070   return Index / NumElemsPerChunk;
4071 }
4072
4073 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4074   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4075   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4076     llvm_unreachable("Illegal insert subvector for VINSERT");
4077
4078   uint64_t Index =
4079     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4080
4081   MVT VecVT = N->getSimpleValueType(0);
4082   MVT ElVT = VecVT.getVectorElementType();
4083
4084   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4085   return Index / NumElemsPerChunk;
4086 }
4087
4088 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4089 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4090 /// and VINSERTI128 instructions.
4091 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4092   return getExtractVEXTRACTImmediate(N, 128);
4093 }
4094
4095 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4096 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4097 /// and VINSERTI64x4 instructions.
4098 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4099   return getExtractVEXTRACTImmediate(N, 256);
4100 }
4101
4102 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4103 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4104 /// and VINSERTI128 instructions.
4105 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4106   return getInsertVINSERTImmediate(N, 128);
4107 }
4108
4109 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4110 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4111 /// and VINSERTI64x4 instructions.
4112 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4113   return getInsertVINSERTImmediate(N, 256);
4114 }
4115
4116 /// isZero - Returns true if Elt is a constant integer zero
4117 static bool isZero(SDValue V) {
4118   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4119   return C && C->isNullValue();
4120 }
4121
4122 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4123 /// constant +0.0.
4124 bool X86::isZeroNode(SDValue Elt) {
4125   if (isZero(Elt))
4126     return true;
4127   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4128     return CFP->getValueAPF().isPosZero();
4129   return false;
4130 }
4131
4132 /// getZeroVector - Returns a vector of specified type with all zero elements.
4133 ///
4134 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4135                              SelectionDAG &DAG, SDLoc dl) {
4136   assert(VT.isVector() && "Expected a vector type");
4137
4138   // Always build SSE zero vectors as <4 x i32> bitcasted
4139   // to their dest type. This ensures they get CSE'd.
4140   SDValue Vec;
4141   if (VT.is128BitVector()) {  // SSE
4142     if (Subtarget->hasSSE2()) {  // SSE2
4143       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4144       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4145     } else { // SSE1
4146       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4147       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4148     }
4149   } else if (VT.is256BitVector()) { // AVX
4150     if (Subtarget->hasInt256()) { // AVX2
4151       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4152       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4153       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4154     } else {
4155       // 256-bit logic and arithmetic instructions in AVX are all
4156       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4157       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4158       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4159       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4160     }
4161   } else if (VT.is512BitVector()) { // AVX-512
4162       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4163       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4164                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4165       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4166   } else if (VT.getScalarType() == MVT::i1) {
4167
4168     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4169             && "Unexpected vector type");
4170     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4171             && "Unexpected vector type");
4172     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4173     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4174     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4175   } else
4176     llvm_unreachable("Unexpected vector type");
4177
4178   return DAG.getBitcast(VT, Vec);
4179 }
4180
4181 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4182                                 SelectionDAG &DAG, SDLoc dl,
4183                                 unsigned vectorWidth) {
4184   assert((vectorWidth == 128 || vectorWidth == 256) &&
4185          "Unsupported vector width");
4186   EVT VT = Vec.getValueType();
4187   EVT ElVT = VT.getVectorElementType();
4188   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4189   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4190                                   VT.getVectorNumElements()/Factor);
4191
4192   // Extract from UNDEF is UNDEF.
4193   if (Vec.getOpcode() == ISD::UNDEF)
4194     return DAG.getUNDEF(ResultVT);
4195
4196   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4197   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4198
4199   // This is the index of the first element of the vectorWidth-bit chunk
4200   // we want.
4201   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4202                                * ElemsPerChunk);
4203
4204   // If the input is a buildvector just emit a smaller one.
4205   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4206     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4207                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4208                                     ElemsPerChunk));
4209
4210   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4211   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4212 }
4213
4214 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4215 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4216 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4217 /// instructions or a simple subregister reference. Idx is an index in the
4218 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4219 /// lowering EXTRACT_VECTOR_ELT operations easier.
4220 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4221                                    SelectionDAG &DAG, SDLoc dl) {
4222   assert((Vec.getValueType().is256BitVector() ||
4223           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4224   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4225 }
4226
4227 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4228 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4229                                    SelectionDAG &DAG, SDLoc dl) {
4230   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4231   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4232 }
4233
4234 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4235                                unsigned IdxVal, SelectionDAG &DAG,
4236                                SDLoc dl, unsigned vectorWidth) {
4237   assert((vectorWidth == 128 || vectorWidth == 256) &&
4238          "Unsupported vector width");
4239   // Inserting UNDEF is Result
4240   if (Vec.getOpcode() == ISD::UNDEF)
4241     return Result;
4242   EVT VT = Vec.getValueType();
4243   EVT ElVT = VT.getVectorElementType();
4244   EVT ResultVT = Result.getValueType();
4245
4246   // Insert the relevant vectorWidth bits.
4247   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4248
4249   // This is the index of the first element of the vectorWidth-bit chunk
4250   // we want.
4251   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4252                                * ElemsPerChunk);
4253
4254   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4255   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4256 }
4257
4258 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4259 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4260 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4261 /// simple superregister reference.  Idx is an index in the 128 bits
4262 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4263 /// lowering INSERT_VECTOR_ELT operations easier.
4264 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4265                                   SelectionDAG &DAG, SDLoc dl) {
4266   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4267
4268   // For insertion into the zero index (low half) of a 256-bit vector, it is
4269   // more efficient to generate a blend with immediate instead of an insert*128.
4270   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4271   // extend the subvector to the size of the result vector. Make sure that
4272   // we are not recursing on that node by checking for undef here.
4273   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4274       Result.getOpcode() != ISD::UNDEF) {
4275     EVT ResultVT = Result.getValueType();
4276     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4277     SDValue Undef = DAG.getUNDEF(ResultVT);
4278     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4279                                  Vec, ZeroIndex);
4280
4281     // The blend instruction, and therefore its mask, depend on the data type.
4282     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4283     if (ScalarType.isFloatingPoint()) {
4284       // Choose either vblendps (float) or vblendpd (double).
4285       unsigned ScalarSize = ScalarType.getSizeInBits();
4286       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4287       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4288       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4289       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4290     }
4291
4292     const X86Subtarget &Subtarget =
4293     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4294
4295     // AVX2 is needed for 256-bit integer blend support.
4296     // Integers must be cast to 32-bit because there is only vpblendd;
4297     // vpblendw can't be used for this because it has a handicapped mask.
4298
4299     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4300     // is still more efficient than using the wrong domain vinsertf128 that
4301     // will be created by InsertSubVector().
4302     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4303
4304     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4305     Vec256 = DAG.getBitcast(CastVT, Vec256);
4306     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4307     return DAG.getBitcast(ResultVT, Vec256);
4308   }
4309
4310   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4311 }
4312
4313 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4314                                   SelectionDAG &DAG, SDLoc dl) {
4315   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4316   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4317 }
4318
4319 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4320 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4321 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4322 /// large BUILD_VECTORS.
4323 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4324                                    unsigned NumElems, SelectionDAG &DAG,
4325                                    SDLoc dl) {
4326   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4327   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4328 }
4329
4330 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4331                                    unsigned NumElems, SelectionDAG &DAG,
4332                                    SDLoc dl) {
4333   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4334   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4335 }
4336
4337 /// getOnesVector - Returns a vector of specified type with all bits set.
4338 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4339 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4340 /// Then bitcast to their original type, ensuring they get CSE'd.
4341 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4342                              SDLoc dl) {
4343   assert(VT.isVector() && "Expected a vector type");
4344
4345   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4346   SDValue Vec;
4347   if (VT.is256BitVector()) {
4348     if (HasInt256) { // AVX2
4349       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4350       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4351     } else { // AVX
4352       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4353       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4354     }
4355   } else if (VT.is128BitVector()) {
4356     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4357   } else
4358     llvm_unreachable("Unexpected vector type");
4359
4360   return DAG.getBitcast(VT, Vec);
4361 }
4362
4363 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4364 /// operation of specified width.
4365 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4366                        SDValue V2) {
4367   unsigned NumElems = VT.getVectorNumElements();
4368   SmallVector<int, 8> Mask;
4369   Mask.push_back(NumElems);
4370   for (unsigned i = 1; i != NumElems; ++i)
4371     Mask.push_back(i);
4372   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4373 }
4374
4375 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4376 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4377                           SDValue V2) {
4378   unsigned NumElems = VT.getVectorNumElements();
4379   SmallVector<int, 8> Mask;
4380   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4381     Mask.push_back(i);
4382     Mask.push_back(i + NumElems);
4383   }
4384   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4385 }
4386
4387 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4388 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4389                           SDValue V2) {
4390   unsigned NumElems = VT.getVectorNumElements();
4391   SmallVector<int, 8> Mask;
4392   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4393     Mask.push_back(i + Half);
4394     Mask.push_back(i + NumElems + Half);
4395   }
4396   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4397 }
4398
4399 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4400 /// vector of zero or undef vector.  This produces a shuffle where the low
4401 /// element of V2 is swizzled into the zero/undef vector, landing at element
4402 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4403 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4404                                            bool IsZero,
4405                                            const X86Subtarget *Subtarget,
4406                                            SelectionDAG &DAG) {
4407   MVT VT = V2.getSimpleValueType();
4408   SDValue V1 = IsZero
4409     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4410   unsigned NumElems = VT.getVectorNumElements();
4411   SmallVector<int, 16> MaskVec;
4412   for (unsigned i = 0; i != NumElems; ++i)
4413     // If this is the insertion idx, put the low elt of V2 here.
4414     MaskVec.push_back(i == Idx ? NumElems : i);
4415   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4416 }
4417
4418 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4419 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4420 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4421 /// shuffles which use a single input multiple times, and in those cases it will
4422 /// adjust the mask to only have indices within that single input.
4423 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4424 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4425                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4426   unsigned NumElems = VT.getVectorNumElements();
4427   SDValue ImmN;
4428
4429   IsUnary = false;
4430   bool IsFakeUnary = false;
4431   switch(N->getOpcode()) {
4432   case X86ISD::BLENDI:
4433     ImmN = N->getOperand(N->getNumOperands()-1);
4434     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4435     break;
4436   case X86ISD::SHUFP:
4437     ImmN = N->getOperand(N->getNumOperands()-1);
4438     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4439     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4440     break;
4441   case X86ISD::UNPCKH:
4442     DecodeUNPCKHMask(VT, Mask);
4443     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4444     break;
4445   case X86ISD::UNPCKL:
4446     DecodeUNPCKLMask(VT, Mask);
4447     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4448     break;
4449   case X86ISD::MOVHLPS:
4450     DecodeMOVHLPSMask(NumElems, Mask);
4451     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4452     break;
4453   case X86ISD::MOVLHPS:
4454     DecodeMOVLHPSMask(NumElems, Mask);
4455     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4456     break;
4457   case X86ISD::PALIGNR:
4458     ImmN = N->getOperand(N->getNumOperands()-1);
4459     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4460     break;
4461   case X86ISD::PSHUFD:
4462   case X86ISD::VPERMILPI:
4463     ImmN = N->getOperand(N->getNumOperands()-1);
4464     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4465     IsUnary = true;
4466     break;
4467   case X86ISD::PSHUFHW:
4468     ImmN = N->getOperand(N->getNumOperands()-1);
4469     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4470     IsUnary = true;
4471     break;
4472   case X86ISD::PSHUFLW:
4473     ImmN = N->getOperand(N->getNumOperands()-1);
4474     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4475     IsUnary = true;
4476     break;
4477   case X86ISD::PSHUFB: {
4478     IsUnary = true;
4479     SDValue MaskNode = N->getOperand(1);
4480     while (MaskNode->getOpcode() == ISD::BITCAST)
4481       MaskNode = MaskNode->getOperand(0);
4482
4483     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4484       // If we have a build-vector, then things are easy.
4485       EVT VT = MaskNode.getValueType();
4486       assert(VT.isVector() &&
4487              "Can't produce a non-vector with a build_vector!");
4488       if (!VT.isInteger())
4489         return false;
4490
4491       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4492
4493       SmallVector<uint64_t, 32> RawMask;
4494       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4495         SDValue Op = MaskNode->getOperand(i);
4496         if (Op->getOpcode() == ISD::UNDEF) {
4497           RawMask.push_back((uint64_t)SM_SentinelUndef);
4498           continue;
4499         }
4500         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4501         if (!CN)
4502           return false;
4503         APInt MaskElement = CN->getAPIntValue();
4504
4505         // We now have to decode the element which could be any integer size and
4506         // extract each byte of it.
4507         for (int j = 0; j < NumBytesPerElement; ++j) {
4508           // Note that this is x86 and so always little endian: the low byte is
4509           // the first byte of the mask.
4510           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4511           MaskElement = MaskElement.lshr(8);
4512         }
4513       }
4514       DecodePSHUFBMask(RawMask, Mask);
4515       break;
4516     }
4517
4518     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4519     if (!MaskLoad)
4520       return false;
4521
4522     SDValue Ptr = MaskLoad->getBasePtr();
4523     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4524         Ptr->getOpcode() == X86ISD::WrapperRIP)
4525       Ptr = Ptr->getOperand(0);
4526
4527     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4528     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4529       return false;
4530
4531     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4532       DecodePSHUFBMask(C, Mask);
4533       if (Mask.empty())
4534         return false;
4535       break;
4536     }
4537
4538     return false;
4539   }
4540   case X86ISD::VPERMI:
4541     ImmN = N->getOperand(N->getNumOperands()-1);
4542     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4543     IsUnary = true;
4544     break;
4545   case X86ISD::MOVSS:
4546   case X86ISD::MOVSD:
4547     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4548     break;
4549   case X86ISD::VPERM2X128:
4550     ImmN = N->getOperand(N->getNumOperands()-1);
4551     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4552     if (Mask.empty()) return false;
4553     // Mask only contains negative index if an element is zero.
4554     if (std::any_of(Mask.begin(), Mask.end(),
4555                     [](int M){ return M == SM_SentinelZero; }))
4556       return false;
4557     break;
4558   case X86ISD::MOVSLDUP:
4559     DecodeMOVSLDUPMask(VT, Mask);
4560     IsUnary = true;
4561     break;
4562   case X86ISD::MOVSHDUP:
4563     DecodeMOVSHDUPMask(VT, Mask);
4564     IsUnary = true;
4565     break;
4566   case X86ISD::MOVDDUP:
4567     DecodeMOVDDUPMask(VT, Mask);
4568     IsUnary = true;
4569     break;
4570   case X86ISD::MOVLHPD:
4571   case X86ISD::MOVLPD:
4572   case X86ISD::MOVLPS:
4573     // Not yet implemented
4574     return false;
4575   default: llvm_unreachable("unknown target shuffle node");
4576   }
4577
4578   // If we have a fake unary shuffle, the shuffle mask is spread across two
4579   // inputs that are actually the same node. Re-map the mask to always point
4580   // into the first input.
4581   if (IsFakeUnary)
4582     for (int &M : Mask)
4583       if (M >= (int)Mask.size())
4584         M -= Mask.size();
4585
4586   return true;
4587 }
4588
4589 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4590 /// element of the result of the vector shuffle.
4591 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4592                                    unsigned Depth) {
4593   if (Depth == 6)
4594     return SDValue();  // Limit search depth.
4595
4596   SDValue V = SDValue(N, 0);
4597   EVT VT = V.getValueType();
4598   unsigned Opcode = V.getOpcode();
4599
4600   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4601   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4602     int Elt = SV->getMaskElt(Index);
4603
4604     if (Elt < 0)
4605       return DAG.getUNDEF(VT.getVectorElementType());
4606
4607     unsigned NumElems = VT.getVectorNumElements();
4608     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4609                                          : SV->getOperand(1);
4610     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4611   }
4612
4613   // Recurse into target specific vector shuffles to find scalars.
4614   if (isTargetShuffle(Opcode)) {
4615     MVT ShufVT = V.getSimpleValueType();
4616     unsigned NumElems = ShufVT.getVectorNumElements();
4617     SmallVector<int, 16> ShuffleMask;
4618     bool IsUnary;
4619
4620     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4621       return SDValue();
4622
4623     int Elt = ShuffleMask[Index];
4624     if (Elt < 0)
4625       return DAG.getUNDEF(ShufVT.getVectorElementType());
4626
4627     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4628                                          : N->getOperand(1);
4629     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4630                                Depth+1);
4631   }
4632
4633   // Actual nodes that may contain scalar elements
4634   if (Opcode == ISD::BITCAST) {
4635     V = V.getOperand(0);
4636     EVT SrcVT = V.getValueType();
4637     unsigned NumElems = VT.getVectorNumElements();
4638
4639     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4640       return SDValue();
4641   }
4642
4643   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4644     return (Index == 0) ? V.getOperand(0)
4645                         : DAG.getUNDEF(VT.getVectorElementType());
4646
4647   if (V.getOpcode() == ISD::BUILD_VECTOR)
4648     return V.getOperand(Index);
4649
4650   return SDValue();
4651 }
4652
4653 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4654 ///
4655 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4656                                        unsigned NumNonZero, unsigned NumZero,
4657                                        SelectionDAG &DAG,
4658                                        const X86Subtarget* Subtarget,
4659                                        const TargetLowering &TLI) {
4660   if (NumNonZero > 8)
4661     return SDValue();
4662
4663   SDLoc dl(Op);
4664   SDValue V;
4665   bool First = true;
4666
4667   // SSE4.1 - use PINSRB to insert each byte directly.
4668   if (Subtarget->hasSSE41()) {
4669     for (unsigned i = 0; i < 16; ++i) {
4670       bool isNonZero = (NonZeros & (1 << i)) != 0;
4671       if (isNonZero) {
4672         if (First) {
4673           if (NumZero)
4674             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4675           else
4676             V = DAG.getUNDEF(MVT::v16i8);
4677           First = false;
4678         }
4679         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4680                         MVT::v16i8, V, Op.getOperand(i),
4681                         DAG.getIntPtrConstant(i, dl));
4682       }
4683     }
4684
4685     return V;
4686   }
4687
4688   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4689   for (unsigned i = 0; i < 16; ++i) {
4690     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4691     if (ThisIsNonZero && First) {
4692       if (NumZero)
4693         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4694       else
4695         V = DAG.getUNDEF(MVT::v8i16);
4696       First = false;
4697     }
4698
4699     if ((i & 1) != 0) {
4700       SDValue ThisElt, LastElt;
4701       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4702       if (LastIsNonZero) {
4703         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4704                               MVT::i16, Op.getOperand(i-1));
4705       }
4706       if (ThisIsNonZero) {
4707         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4708         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4709                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4710         if (LastIsNonZero)
4711           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4712       } else
4713         ThisElt = LastElt;
4714
4715       if (ThisElt.getNode())
4716         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4717                         DAG.getIntPtrConstant(i/2, dl));
4718     }
4719   }
4720
4721   return DAG.getBitcast(MVT::v16i8, V);
4722 }
4723
4724 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4725 ///
4726 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4727                                      unsigned NumNonZero, unsigned NumZero,
4728                                      SelectionDAG &DAG,
4729                                      const X86Subtarget* Subtarget,
4730                                      const TargetLowering &TLI) {
4731   if (NumNonZero > 4)
4732     return SDValue();
4733
4734   SDLoc dl(Op);
4735   SDValue V;
4736   bool First = true;
4737   for (unsigned i = 0; i < 8; ++i) {
4738     bool isNonZero = (NonZeros & (1 << i)) != 0;
4739     if (isNonZero) {
4740       if (First) {
4741         if (NumZero)
4742           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4743         else
4744           V = DAG.getUNDEF(MVT::v8i16);
4745         First = false;
4746       }
4747       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4748                       MVT::v8i16, V, Op.getOperand(i),
4749                       DAG.getIntPtrConstant(i, dl));
4750     }
4751   }
4752
4753   return V;
4754 }
4755
4756 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4757 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4758                                      const X86Subtarget *Subtarget,
4759                                      const TargetLowering &TLI) {
4760   // Find all zeroable elements.
4761   std::bitset<4> Zeroable;
4762   for (int i=0; i < 4; ++i) {
4763     SDValue Elt = Op->getOperand(i);
4764     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4765   }
4766   assert(Zeroable.size() - Zeroable.count() > 1 &&
4767          "We expect at least two non-zero elements!");
4768
4769   // We only know how to deal with build_vector nodes where elements are either
4770   // zeroable or extract_vector_elt with constant index.
4771   SDValue FirstNonZero;
4772   unsigned FirstNonZeroIdx;
4773   for (unsigned i=0; i < 4; ++i) {
4774     if (Zeroable[i])
4775       continue;
4776     SDValue Elt = Op->getOperand(i);
4777     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4778         !isa<ConstantSDNode>(Elt.getOperand(1)))
4779       return SDValue();
4780     // Make sure that this node is extracting from a 128-bit vector.
4781     MVT VT = Elt.getOperand(0).getSimpleValueType();
4782     if (!VT.is128BitVector())
4783       return SDValue();
4784     if (!FirstNonZero.getNode()) {
4785       FirstNonZero = Elt;
4786       FirstNonZeroIdx = i;
4787     }
4788   }
4789
4790   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4791   SDValue V1 = FirstNonZero.getOperand(0);
4792   MVT VT = V1.getSimpleValueType();
4793
4794   // See if this build_vector can be lowered as a blend with zero.
4795   SDValue Elt;
4796   unsigned EltMaskIdx, EltIdx;
4797   int Mask[4];
4798   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4799     if (Zeroable[EltIdx]) {
4800       // The zero vector will be on the right hand side.
4801       Mask[EltIdx] = EltIdx+4;
4802       continue;
4803     }
4804
4805     Elt = Op->getOperand(EltIdx);
4806     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4807     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4808     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4809       break;
4810     Mask[EltIdx] = EltIdx;
4811   }
4812
4813   if (EltIdx == 4) {
4814     // Let the shuffle legalizer deal with blend operations.
4815     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4816     if (V1.getSimpleValueType() != VT)
4817       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4818     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4819   }
4820
4821   // See if we can lower this build_vector to a INSERTPS.
4822   if (!Subtarget->hasSSE41())
4823     return SDValue();
4824
4825   SDValue V2 = Elt.getOperand(0);
4826   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4827     V1 = SDValue();
4828
4829   bool CanFold = true;
4830   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4831     if (Zeroable[i])
4832       continue;
4833
4834     SDValue Current = Op->getOperand(i);
4835     SDValue SrcVector = Current->getOperand(0);
4836     if (!V1.getNode())
4837       V1 = SrcVector;
4838     CanFold = SrcVector == V1 &&
4839       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4840   }
4841
4842   if (!CanFold)
4843     return SDValue();
4844
4845   assert(V1.getNode() && "Expected at least two non-zero elements!");
4846   if (V1.getSimpleValueType() != MVT::v4f32)
4847     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4848   if (V2.getSimpleValueType() != MVT::v4f32)
4849     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4850
4851   // Ok, we can emit an INSERTPS instruction.
4852   unsigned ZMask = Zeroable.to_ulong();
4853
4854   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4855   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4856   SDLoc DL(Op);
4857   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4858                                DAG.getIntPtrConstant(InsertPSMask, DL));
4859   return DAG.getBitcast(VT, Result);
4860 }
4861
4862 /// Return a vector logical shift node.
4863 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4864                          unsigned NumBits, SelectionDAG &DAG,
4865                          const TargetLowering &TLI, SDLoc dl) {
4866   assert(VT.is128BitVector() && "Unknown type for VShift");
4867   MVT ShVT = MVT::v2i64;
4868   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4869   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4870   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4871   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4872   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4873   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4874 }
4875
4876 static SDValue
4877 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4878
4879   // Check if the scalar load can be widened into a vector load. And if
4880   // the address is "base + cst" see if the cst can be "absorbed" into
4881   // the shuffle mask.
4882   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4883     SDValue Ptr = LD->getBasePtr();
4884     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4885       return SDValue();
4886     EVT PVT = LD->getValueType(0);
4887     if (PVT != MVT::i32 && PVT != MVT::f32)
4888       return SDValue();
4889
4890     int FI = -1;
4891     int64_t Offset = 0;
4892     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4893       FI = FINode->getIndex();
4894       Offset = 0;
4895     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4896                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4897       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4898       Offset = Ptr.getConstantOperandVal(1);
4899       Ptr = Ptr.getOperand(0);
4900     } else {
4901       return SDValue();
4902     }
4903
4904     // FIXME: 256-bit vector instructions don't require a strict alignment,
4905     // improve this code to support it better.
4906     unsigned RequiredAlign = VT.getSizeInBits()/8;
4907     SDValue Chain = LD->getChain();
4908     // Make sure the stack object alignment is at least 16 or 32.
4909     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4910     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4911       if (MFI->isFixedObjectIndex(FI)) {
4912         // Can't change the alignment. FIXME: It's possible to compute
4913         // the exact stack offset and reference FI + adjust offset instead.
4914         // If someone *really* cares about this. That's the way to implement it.
4915         return SDValue();
4916       } else {
4917         MFI->setObjectAlignment(FI, RequiredAlign);
4918       }
4919     }
4920
4921     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4922     // Ptr + (Offset & ~15).
4923     if (Offset < 0)
4924       return SDValue();
4925     if ((Offset % RequiredAlign) & 3)
4926       return SDValue();
4927     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4928     if (StartOffset) {
4929       SDLoc DL(Ptr);
4930       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4931                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4932     }
4933
4934     int EltNo = (Offset - StartOffset) >> 2;
4935     unsigned NumElems = VT.getVectorNumElements();
4936
4937     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4938     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4939                              LD->getPointerInfo().getWithOffset(StartOffset),
4940                              false, false, false, 0);
4941
4942     SmallVector<int, 8> Mask(NumElems, EltNo);
4943
4944     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4945   }
4946
4947   return SDValue();
4948 }
4949
4950 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4951 /// elements can be replaced by a single large load which has the same value as
4952 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4953 ///
4954 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4955 ///
4956 /// FIXME: we'd also like to handle the case where the last elements are zero
4957 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4958 /// There's even a handy isZeroNode for that purpose.
4959 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4960                                         SDLoc &DL, SelectionDAG &DAG,
4961                                         bool isAfterLegalize) {
4962   unsigned NumElems = Elts.size();
4963
4964   LoadSDNode *LDBase = nullptr;
4965   unsigned LastLoadedElt = -1U;
4966
4967   // For each element in the initializer, see if we've found a load or an undef.
4968   // If we don't find an initial load element, or later load elements are
4969   // non-consecutive, bail out.
4970   for (unsigned i = 0; i < NumElems; ++i) {
4971     SDValue Elt = Elts[i];
4972     // Look through a bitcast.
4973     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4974       Elt = Elt.getOperand(0);
4975     if (!Elt.getNode() ||
4976         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4977       return SDValue();
4978     if (!LDBase) {
4979       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4980         return SDValue();
4981       LDBase = cast<LoadSDNode>(Elt.getNode());
4982       LastLoadedElt = i;
4983       continue;
4984     }
4985     if (Elt.getOpcode() == ISD::UNDEF)
4986       continue;
4987
4988     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4989     EVT LdVT = Elt.getValueType();
4990     // Each loaded element must be the correct fractional portion of the
4991     // requested vector load.
4992     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4993       return SDValue();
4994     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4995       return SDValue();
4996     LastLoadedElt = i;
4997   }
4998
4999   // If we have found an entire vector of loads and undefs, then return a large
5000   // load of the entire vector width starting at the base pointer.  If we found
5001   // consecutive loads for the low half, generate a vzext_load node.
5002   if (LastLoadedElt == NumElems - 1) {
5003     assert(LDBase && "Did not find base load for merging consecutive loads");
5004     EVT EltVT = LDBase->getValueType(0);
5005     // Ensure that the input vector size for the merged loads matches the
5006     // cumulative size of the input elements.
5007     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5008       return SDValue();
5009
5010     if (isAfterLegalize &&
5011         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5012       return SDValue();
5013
5014     SDValue NewLd = SDValue();
5015
5016     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5017                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5018                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5019                         LDBase->getAlignment());
5020
5021     if (LDBase->hasAnyUseOfValue(1)) {
5022       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5023                                      SDValue(LDBase, 1),
5024                                      SDValue(NewLd.getNode(), 1));
5025       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5026       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5027                              SDValue(NewLd.getNode(), 1));
5028     }
5029
5030     return NewLd;
5031   }
5032
5033   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5034   //of a v4i32 / v4f32. It's probably worth generalizing.
5035   EVT EltVT = VT.getVectorElementType();
5036   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5037       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5038     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5039     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5040     SDValue ResNode =
5041         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5042                                 LDBase->getPointerInfo(),
5043                                 LDBase->getAlignment(),
5044                                 false/*isVolatile*/, true/*ReadMem*/,
5045                                 false/*WriteMem*/);
5046
5047     // Make sure the newly-created LOAD is in the same position as LDBase in
5048     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5049     // update uses of LDBase's output chain to use the TokenFactor.
5050     if (LDBase->hasAnyUseOfValue(1)) {
5051       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5052                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5053       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5054       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5055                              SDValue(ResNode.getNode(), 1));
5056     }
5057
5058     return DAG.getBitcast(VT, ResNode);
5059   }
5060   return SDValue();
5061 }
5062
5063 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5064 /// to generate a splat value for the following cases:
5065 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5066 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5067 /// a scalar load, or a constant.
5068 /// The VBROADCAST node is returned when a pattern is found,
5069 /// or SDValue() otherwise.
5070 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5071                                     SelectionDAG &DAG) {
5072   // VBROADCAST requires AVX.
5073   // TODO: Splats could be generated for non-AVX CPUs using SSE
5074   // instructions, but there's less potential gain for only 128-bit vectors.
5075   if (!Subtarget->hasAVX())
5076     return SDValue();
5077
5078   MVT VT = Op.getSimpleValueType();
5079   SDLoc dl(Op);
5080
5081   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5082          "Unsupported vector type for broadcast.");
5083
5084   SDValue Ld;
5085   bool ConstSplatVal;
5086
5087   switch (Op.getOpcode()) {
5088     default:
5089       // Unknown pattern found.
5090       return SDValue();
5091
5092     case ISD::BUILD_VECTOR: {
5093       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5094       BitVector UndefElements;
5095       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5096
5097       // We need a splat of a single value to use broadcast, and it doesn't
5098       // make any sense if the value is only in one element of the vector.
5099       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5100         return SDValue();
5101
5102       Ld = Splat;
5103       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5104                        Ld.getOpcode() == ISD::ConstantFP);
5105
5106       // Make sure that all of the users of a non-constant load are from the
5107       // BUILD_VECTOR node.
5108       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5109         return SDValue();
5110       break;
5111     }
5112
5113     case ISD::VECTOR_SHUFFLE: {
5114       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5115
5116       // Shuffles must have a splat mask where the first element is
5117       // broadcasted.
5118       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5119         return SDValue();
5120
5121       SDValue Sc = Op.getOperand(0);
5122       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5123           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5124
5125         if (!Subtarget->hasInt256())
5126           return SDValue();
5127
5128         // Use the register form of the broadcast instruction available on AVX2.
5129         if (VT.getSizeInBits() >= 256)
5130           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5131         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5132       }
5133
5134       Ld = Sc.getOperand(0);
5135       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5136                        Ld.getOpcode() == ISD::ConstantFP);
5137
5138       // The scalar_to_vector node and the suspected
5139       // load node must have exactly one user.
5140       // Constants may have multiple users.
5141
5142       // AVX-512 has register version of the broadcast
5143       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5144         Ld.getValueType().getSizeInBits() >= 32;
5145       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5146           !hasRegVer))
5147         return SDValue();
5148       break;
5149     }
5150   }
5151
5152   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5153   bool IsGE256 = (VT.getSizeInBits() >= 256);
5154
5155   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5156   // instruction to save 8 or more bytes of constant pool data.
5157   // TODO: If multiple splats are generated to load the same constant,
5158   // it may be detrimental to overall size. There needs to be a way to detect
5159   // that condition to know if this is truly a size win.
5160   const Function *F = DAG.getMachineFunction().getFunction();
5161   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5162
5163   // Handle broadcasting a single constant scalar from the constant pool
5164   // into a vector.
5165   // On Sandybridge (no AVX2), it is still better to load a constant vector
5166   // from the constant pool and not to broadcast it from a scalar.
5167   // But override that restriction when optimizing for size.
5168   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5169   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5170     EVT CVT = Ld.getValueType();
5171     assert(!CVT.isVector() && "Must not broadcast a vector type");
5172
5173     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5174     // For size optimization, also splat v2f64 and v2i64, and for size opt
5175     // with AVX2, also splat i8 and i16.
5176     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5177     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5178         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5179       const Constant *C = nullptr;
5180       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5181         C = CI->getConstantIntValue();
5182       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5183         C = CF->getConstantFPValue();
5184
5185       assert(C && "Invalid constant type");
5186
5187       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5188       SDValue CP =
5189           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5190       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5191       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5192                        MachinePointerInfo::getConstantPool(),
5193                        false, false, false, Alignment);
5194
5195       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5196     }
5197   }
5198
5199   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5200
5201   // Handle AVX2 in-register broadcasts.
5202   if (!IsLoad && Subtarget->hasInt256() &&
5203       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5204     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5205
5206   // The scalar source must be a normal load.
5207   if (!IsLoad)
5208     return SDValue();
5209
5210   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5211       (Subtarget->hasVLX() && ScalarSize == 64))
5212     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5213
5214   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5215   // double since there is no vbroadcastsd xmm
5216   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5217     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5218       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5219   }
5220
5221   // Unsupported broadcast.
5222   return SDValue();
5223 }
5224
5225 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5226 /// underlying vector and index.
5227 ///
5228 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5229 /// index.
5230 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5231                                          SDValue ExtIdx) {
5232   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5233   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5234     return Idx;
5235
5236   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5237   // lowered this:
5238   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5239   // to:
5240   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5241   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5242   //                           undef)
5243   //                       Constant<0>)
5244   // In this case the vector is the extract_subvector expression and the index
5245   // is 2, as specified by the shuffle.
5246   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5247   SDValue ShuffleVec = SVOp->getOperand(0);
5248   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5249   assert(ShuffleVecVT.getVectorElementType() ==
5250          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5251
5252   int ShuffleIdx = SVOp->getMaskElt(Idx);
5253   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5254     ExtractedFromVec = ShuffleVec;
5255     return ShuffleIdx;
5256   }
5257   return Idx;
5258 }
5259
5260 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5261   MVT VT = Op.getSimpleValueType();
5262
5263   // Skip if insert_vec_elt is not supported.
5264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5265   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5266     return SDValue();
5267
5268   SDLoc DL(Op);
5269   unsigned NumElems = Op.getNumOperands();
5270
5271   SDValue VecIn1;
5272   SDValue VecIn2;
5273   SmallVector<unsigned, 4> InsertIndices;
5274   SmallVector<int, 8> Mask(NumElems, -1);
5275
5276   for (unsigned i = 0; i != NumElems; ++i) {
5277     unsigned Opc = Op.getOperand(i).getOpcode();
5278
5279     if (Opc == ISD::UNDEF)
5280       continue;
5281
5282     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5283       // Quit if more than 1 elements need inserting.
5284       if (InsertIndices.size() > 1)
5285         return SDValue();
5286
5287       InsertIndices.push_back(i);
5288       continue;
5289     }
5290
5291     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5292     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5293     // Quit if non-constant index.
5294     if (!isa<ConstantSDNode>(ExtIdx))
5295       return SDValue();
5296     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5297
5298     // Quit if extracted from vector of different type.
5299     if (ExtractedFromVec.getValueType() != VT)
5300       return SDValue();
5301
5302     if (!VecIn1.getNode())
5303       VecIn1 = ExtractedFromVec;
5304     else if (VecIn1 != ExtractedFromVec) {
5305       if (!VecIn2.getNode())
5306         VecIn2 = ExtractedFromVec;
5307       else if (VecIn2 != ExtractedFromVec)
5308         // Quit if more than 2 vectors to shuffle
5309         return SDValue();
5310     }
5311
5312     if (ExtractedFromVec == VecIn1)
5313       Mask[i] = Idx;
5314     else if (ExtractedFromVec == VecIn2)
5315       Mask[i] = Idx + NumElems;
5316   }
5317
5318   if (!VecIn1.getNode())
5319     return SDValue();
5320
5321   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5322   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5323   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5324     unsigned Idx = InsertIndices[i];
5325     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5326                      DAG.getIntPtrConstant(Idx, DL));
5327   }
5328
5329   return NV;
5330 }
5331
5332 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5333   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5334          Op.getScalarValueSizeInBits() == 1 &&
5335          "Can not convert non-constant vector");
5336   uint64_t Immediate = 0;
5337   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5338     SDValue In = Op.getOperand(idx);
5339     if (In.getOpcode() != ISD::UNDEF)
5340       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5341   }
5342   SDLoc dl(Op);
5343   MVT VT =
5344    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5345   return DAG.getConstant(Immediate, dl, VT);
5346 }
5347 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5348 SDValue
5349 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5350
5351   MVT VT = Op.getSimpleValueType();
5352   assert((VT.getVectorElementType() == MVT::i1) &&
5353          "Unexpected type in LowerBUILD_VECTORvXi1!");
5354
5355   SDLoc dl(Op);
5356   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5357     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5358     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5359     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5360   }
5361
5362   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5363     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5364     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5365     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5366   }
5367
5368   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5369     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5370     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5371       return DAG.getBitcast(VT, Imm);
5372     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5373     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5374                         DAG.getIntPtrConstant(0, dl));
5375   }
5376
5377   // Vector has one or more non-const elements
5378   uint64_t Immediate = 0;
5379   SmallVector<unsigned, 16> NonConstIdx;
5380   bool IsSplat = true;
5381   bool HasConstElts = false;
5382   int SplatIdx = -1;
5383   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5384     SDValue In = Op.getOperand(idx);
5385     if (In.getOpcode() == ISD::UNDEF)
5386       continue;
5387     if (!isa<ConstantSDNode>(In))
5388       NonConstIdx.push_back(idx);
5389     else {
5390       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5391       HasConstElts = true;
5392     }
5393     if (SplatIdx == -1)
5394       SplatIdx = idx;
5395     else if (In != Op.getOperand(SplatIdx))
5396       IsSplat = false;
5397   }
5398
5399   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5400   if (IsSplat)
5401     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5402                        DAG.getConstant(1, dl, VT),
5403                        DAG.getConstant(0, dl, VT));
5404
5405   // insert elements one by one
5406   SDValue DstVec;
5407   SDValue Imm;
5408   if (Immediate) {
5409     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5410     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5411   }
5412   else if (HasConstElts)
5413     Imm = DAG.getConstant(0, dl, VT);
5414   else
5415     Imm = DAG.getUNDEF(VT);
5416   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5417     DstVec = DAG.getBitcast(VT, Imm);
5418   else {
5419     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5420     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5421                          DAG.getIntPtrConstant(0, dl));
5422   }
5423
5424   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5425     unsigned InsertIdx = NonConstIdx[i];
5426     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5427                          Op.getOperand(InsertIdx),
5428                          DAG.getIntPtrConstant(InsertIdx, dl));
5429   }
5430   return DstVec;
5431 }
5432
5433 /// \brief Return true if \p N implements a horizontal binop and return the
5434 /// operands for the horizontal binop into V0 and V1.
5435 ///
5436 /// This is a helper function of LowerToHorizontalOp().
5437 /// This function checks that the build_vector \p N in input implements a
5438 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5439 /// operation to match.
5440 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5441 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5442 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5443 /// arithmetic sub.
5444 ///
5445 /// This function only analyzes elements of \p N whose indices are
5446 /// in range [BaseIdx, LastIdx).
5447 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5448                               SelectionDAG &DAG,
5449                               unsigned BaseIdx, unsigned LastIdx,
5450                               SDValue &V0, SDValue &V1) {
5451   EVT VT = N->getValueType(0);
5452
5453   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5454   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5455          "Invalid Vector in input!");
5456
5457   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5458   bool CanFold = true;
5459   unsigned ExpectedVExtractIdx = BaseIdx;
5460   unsigned NumElts = LastIdx - BaseIdx;
5461   V0 = DAG.getUNDEF(VT);
5462   V1 = DAG.getUNDEF(VT);
5463
5464   // Check if N implements a horizontal binop.
5465   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5466     SDValue Op = N->getOperand(i + BaseIdx);
5467
5468     // Skip UNDEFs.
5469     if (Op->getOpcode() == ISD::UNDEF) {
5470       // Update the expected vector extract index.
5471       if (i * 2 == NumElts)
5472         ExpectedVExtractIdx = BaseIdx;
5473       ExpectedVExtractIdx += 2;
5474       continue;
5475     }
5476
5477     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5478
5479     if (!CanFold)
5480       break;
5481
5482     SDValue Op0 = Op.getOperand(0);
5483     SDValue Op1 = Op.getOperand(1);
5484
5485     // Try to match the following pattern:
5486     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5487     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5488         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5489         Op0.getOperand(0) == Op1.getOperand(0) &&
5490         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5491         isa<ConstantSDNode>(Op1.getOperand(1)));
5492     if (!CanFold)
5493       break;
5494
5495     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5496     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5497
5498     if (i * 2 < NumElts) {
5499       if (V0.getOpcode() == ISD::UNDEF) {
5500         V0 = Op0.getOperand(0);
5501         if (V0.getValueType() != VT)
5502           return false;
5503       }
5504     } else {
5505       if (V1.getOpcode() == ISD::UNDEF) {
5506         V1 = Op0.getOperand(0);
5507         if (V1.getValueType() != VT)
5508           return false;
5509       }
5510       if (i * 2 == NumElts)
5511         ExpectedVExtractIdx = BaseIdx;
5512     }
5513
5514     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5515     if (I0 == ExpectedVExtractIdx)
5516       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5517     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5518       // Try to match the following dag sequence:
5519       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5520       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5521     } else
5522       CanFold = false;
5523
5524     ExpectedVExtractIdx += 2;
5525   }
5526
5527   return CanFold;
5528 }
5529
5530 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5531 /// a concat_vector.
5532 ///
5533 /// This is a helper function of LowerToHorizontalOp().
5534 /// This function expects two 256-bit vectors called V0 and V1.
5535 /// At first, each vector is split into two separate 128-bit vectors.
5536 /// Then, the resulting 128-bit vectors are used to implement two
5537 /// horizontal binary operations.
5538 ///
5539 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5540 ///
5541 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5542 /// the two new horizontal binop.
5543 /// When Mode is set, the first horizontal binop dag node would take as input
5544 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5545 /// horizontal binop dag node would take as input the lower 128-bit of V1
5546 /// and the upper 128-bit of V1.
5547 ///   Example:
5548 ///     HADD V0_LO, V0_HI
5549 ///     HADD V1_LO, V1_HI
5550 ///
5551 /// Otherwise, the first horizontal binop dag node takes as input the lower
5552 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5553 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5554 ///   Example:
5555 ///     HADD V0_LO, V1_LO
5556 ///     HADD V0_HI, V1_HI
5557 ///
5558 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5559 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5560 /// the upper 128-bits of the result.
5561 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5562                                      SDLoc DL, SelectionDAG &DAG,
5563                                      unsigned X86Opcode, bool Mode,
5564                                      bool isUndefLO, bool isUndefHI) {
5565   EVT VT = V0.getValueType();
5566   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5567          "Invalid nodes in input!");
5568
5569   unsigned NumElts = VT.getVectorNumElements();
5570   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5571   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5572   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5573   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5574   EVT NewVT = V0_LO.getValueType();
5575
5576   SDValue LO = DAG.getUNDEF(NewVT);
5577   SDValue HI = DAG.getUNDEF(NewVT);
5578
5579   if (Mode) {
5580     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5581     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5582       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5583     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5584       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5585   } else {
5586     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5587     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5588                        V1_LO->getOpcode() != ISD::UNDEF))
5589       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5590
5591     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5592                        V1_HI->getOpcode() != ISD::UNDEF))
5593       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5594   }
5595
5596   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5597 }
5598
5599 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5600 /// node.
5601 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5602                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5603   EVT VT = BV->getValueType(0);
5604   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5605       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5606     return SDValue();
5607
5608   SDLoc DL(BV);
5609   unsigned NumElts = VT.getVectorNumElements();
5610   SDValue InVec0 = DAG.getUNDEF(VT);
5611   SDValue InVec1 = DAG.getUNDEF(VT);
5612
5613   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5614           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5615
5616   // Odd-numbered elements in the input build vector are obtained from
5617   // adding two integer/float elements.
5618   // Even-numbered elements in the input build vector are obtained from
5619   // subtracting two integer/float elements.
5620   unsigned ExpectedOpcode = ISD::FSUB;
5621   unsigned NextExpectedOpcode = ISD::FADD;
5622   bool AddFound = false;
5623   bool SubFound = false;
5624
5625   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5626     SDValue Op = BV->getOperand(i);
5627
5628     // Skip 'undef' values.
5629     unsigned Opcode = Op.getOpcode();
5630     if (Opcode == ISD::UNDEF) {
5631       std::swap(ExpectedOpcode, NextExpectedOpcode);
5632       continue;
5633     }
5634
5635     // Early exit if we found an unexpected opcode.
5636     if (Opcode != ExpectedOpcode)
5637       return SDValue();
5638
5639     SDValue Op0 = Op.getOperand(0);
5640     SDValue Op1 = Op.getOperand(1);
5641
5642     // Try to match the following pattern:
5643     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5644     // Early exit if we cannot match that sequence.
5645     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5646         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5647         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5648         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5649         Op0.getOperand(1) != Op1.getOperand(1))
5650       return SDValue();
5651
5652     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5653     if (I0 != i)
5654       return SDValue();
5655
5656     // We found a valid add/sub node. Update the information accordingly.
5657     if (i & 1)
5658       AddFound = true;
5659     else
5660       SubFound = true;
5661
5662     // Update InVec0 and InVec1.
5663     if (InVec0.getOpcode() == ISD::UNDEF) {
5664       InVec0 = Op0.getOperand(0);
5665       if (InVec0.getValueType() != VT)
5666         return SDValue();
5667     }
5668     if (InVec1.getOpcode() == ISD::UNDEF) {
5669       InVec1 = Op1.getOperand(0);
5670       if (InVec1.getValueType() != VT)
5671         return SDValue();
5672     }
5673
5674     // Make sure that operands in input to each add/sub node always
5675     // come from a same pair of vectors.
5676     if (InVec0 != Op0.getOperand(0)) {
5677       if (ExpectedOpcode == ISD::FSUB)
5678         return SDValue();
5679
5680       // FADD is commutable. Try to commute the operands
5681       // and then test again.
5682       std::swap(Op0, Op1);
5683       if (InVec0 != Op0.getOperand(0))
5684         return SDValue();
5685     }
5686
5687     if (InVec1 != Op1.getOperand(0))
5688       return SDValue();
5689
5690     // Update the pair of expected opcodes.
5691     std::swap(ExpectedOpcode, NextExpectedOpcode);
5692   }
5693
5694   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5695   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5696       InVec1.getOpcode() != ISD::UNDEF)
5697     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5698
5699   return SDValue();
5700 }
5701
5702 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5703 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5704                                    const X86Subtarget *Subtarget,
5705                                    SelectionDAG &DAG) {
5706   EVT VT = BV->getValueType(0);
5707   unsigned NumElts = VT.getVectorNumElements();
5708   unsigned NumUndefsLO = 0;
5709   unsigned NumUndefsHI = 0;
5710   unsigned Half = NumElts/2;
5711
5712   // Count the number of UNDEF operands in the build_vector in input.
5713   for (unsigned i = 0, e = Half; i != e; ++i)
5714     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5715       NumUndefsLO++;
5716
5717   for (unsigned i = Half, e = NumElts; i != e; ++i)
5718     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5719       NumUndefsHI++;
5720
5721   // Early exit if this is either a build_vector of all UNDEFs or all the
5722   // operands but one are UNDEF.
5723   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5724     return SDValue();
5725
5726   SDLoc DL(BV);
5727   SDValue InVec0, InVec1;
5728   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5729     // Try to match an SSE3 float HADD/HSUB.
5730     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5731       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5732
5733     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5734       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5735   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5736     // Try to match an SSSE3 integer HADD/HSUB.
5737     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5738       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5739
5740     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5741       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5742   }
5743
5744   if (!Subtarget->hasAVX())
5745     return SDValue();
5746
5747   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5748     // Try to match an AVX horizontal add/sub of packed single/double
5749     // precision floating point values from 256-bit vectors.
5750     SDValue InVec2, InVec3;
5751     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5752         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5753         ((InVec0.getOpcode() == ISD::UNDEF ||
5754           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5755         ((InVec1.getOpcode() == ISD::UNDEF ||
5756           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5757       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5758
5759     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5760         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5761         ((InVec0.getOpcode() == ISD::UNDEF ||
5762           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5763         ((InVec1.getOpcode() == ISD::UNDEF ||
5764           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5765       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5766   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5767     // Try to match an AVX2 horizontal add/sub of signed integers.
5768     SDValue InVec2, InVec3;
5769     unsigned X86Opcode;
5770     bool CanFold = true;
5771
5772     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5773         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5774         ((InVec0.getOpcode() == ISD::UNDEF ||
5775           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5776         ((InVec1.getOpcode() == ISD::UNDEF ||
5777           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5778       X86Opcode = X86ISD::HADD;
5779     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5780         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5781         ((InVec0.getOpcode() == ISD::UNDEF ||
5782           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5783         ((InVec1.getOpcode() == ISD::UNDEF ||
5784           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5785       X86Opcode = X86ISD::HSUB;
5786     else
5787       CanFold = false;
5788
5789     if (CanFold) {
5790       // Fold this build_vector into a single horizontal add/sub.
5791       // Do this only if the target has AVX2.
5792       if (Subtarget->hasAVX2())
5793         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5794
5795       // Do not try to expand this build_vector into a pair of horizontal
5796       // add/sub if we can emit a pair of scalar add/sub.
5797       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5798         return SDValue();
5799
5800       // Convert this build_vector into a pair of horizontal binop followed by
5801       // a concat vector.
5802       bool isUndefLO = NumUndefsLO == Half;
5803       bool isUndefHI = NumUndefsHI == Half;
5804       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5805                                    isUndefLO, isUndefHI);
5806     }
5807   }
5808
5809   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5810        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5811     unsigned X86Opcode;
5812     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5813       X86Opcode = X86ISD::HADD;
5814     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5815       X86Opcode = X86ISD::HSUB;
5816     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5817       X86Opcode = X86ISD::FHADD;
5818     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5819       X86Opcode = X86ISD::FHSUB;
5820     else
5821       return SDValue();
5822
5823     // Don't try to expand this build_vector into a pair of horizontal add/sub
5824     // if we can simply emit a pair of scalar add/sub.
5825     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5826       return SDValue();
5827
5828     // Convert this build_vector into two horizontal add/sub followed by
5829     // a concat vector.
5830     bool isUndefLO = NumUndefsLO == Half;
5831     bool isUndefHI = NumUndefsHI == Half;
5832     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5833                                  isUndefLO, isUndefHI);
5834   }
5835
5836   return SDValue();
5837 }
5838
5839 SDValue
5840 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5841   SDLoc dl(Op);
5842
5843   MVT VT = Op.getSimpleValueType();
5844   MVT ExtVT = VT.getVectorElementType();
5845   unsigned NumElems = Op.getNumOperands();
5846
5847   // Generate vectors for predicate vectors.
5848   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5849     return LowerBUILD_VECTORvXi1(Op, DAG);
5850
5851   // Vectors containing all zeros can be matched by pxor and xorps later
5852   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5853     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5854     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5855     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5856       return Op;
5857
5858     return getZeroVector(VT, Subtarget, DAG, dl);
5859   }
5860
5861   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5862   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5863   // vpcmpeqd on 256-bit vectors.
5864   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5865     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5866       return Op;
5867
5868     if (!VT.is512BitVector())
5869       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5870   }
5871
5872   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5873   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5874     return AddSub;
5875   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5876     return HorizontalOp;
5877   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5878     return Broadcast;
5879
5880   unsigned EVTBits = ExtVT.getSizeInBits();
5881
5882   unsigned NumZero  = 0;
5883   unsigned NumNonZero = 0;
5884   unsigned NonZeros = 0;
5885   bool IsAllConstants = true;
5886   SmallSet<SDValue, 8> Values;
5887   for (unsigned i = 0; i < NumElems; ++i) {
5888     SDValue Elt = Op.getOperand(i);
5889     if (Elt.getOpcode() == ISD::UNDEF)
5890       continue;
5891     Values.insert(Elt);
5892     if (Elt.getOpcode() != ISD::Constant &&
5893         Elt.getOpcode() != ISD::ConstantFP)
5894       IsAllConstants = false;
5895     if (X86::isZeroNode(Elt))
5896       NumZero++;
5897     else {
5898       NonZeros |= (1 << i);
5899       NumNonZero++;
5900     }
5901   }
5902
5903   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5904   if (NumNonZero == 0)
5905     return DAG.getUNDEF(VT);
5906
5907   // Special case for single non-zero, non-undef, element.
5908   if (NumNonZero == 1) {
5909     unsigned Idx = countTrailingZeros(NonZeros);
5910     SDValue Item = Op.getOperand(Idx);
5911
5912     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5913     // the value are obviously zero, truncate the value to i32 and do the
5914     // insertion that way.  Only do this if the value is non-constant or if the
5915     // value is a constant being inserted into element 0.  It is cheaper to do
5916     // a constant pool load than it is to do a movd + shuffle.
5917     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5918         (!IsAllConstants || Idx == 0)) {
5919       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5920         // Handle SSE only.
5921         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5922         EVT VecVT = MVT::v4i32;
5923
5924         // Truncate the value (which may itself be a constant) to i32, and
5925         // convert it to a vector with movd (S2V+shuffle to zero extend).
5926         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5927         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5928         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5929                                       Item, Idx * 2, true, Subtarget, DAG));
5930       }
5931     }
5932
5933     // If we have a constant or non-constant insertion into the low element of
5934     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5935     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5936     // depending on what the source datatype is.
5937     if (Idx == 0) {
5938       if (NumZero == 0)
5939         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5940
5941       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5942           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5943         if (VT.is512BitVector()) {
5944           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5945           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5946                              Item, DAG.getIntPtrConstant(0, dl));
5947         }
5948         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5949                "Expected an SSE value type!");
5950         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5951         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5952         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5953       }
5954
5955       // We can't directly insert an i8 or i16 into a vector, so zero extend
5956       // it to i32 first.
5957       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5958         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5959         if (VT.is256BitVector()) {
5960           if (Subtarget->hasAVX()) {
5961             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5962             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5963           } else {
5964             // Without AVX, we need to extend to a 128-bit vector and then
5965             // insert into the 256-bit vector.
5966             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5967             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5968             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5969           }
5970         } else {
5971           assert(VT.is128BitVector() && "Expected an SSE value type!");
5972           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5973           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5974         }
5975         return DAG.getBitcast(VT, Item);
5976       }
5977     }
5978
5979     // Is it a vector logical left shift?
5980     if (NumElems == 2 && Idx == 1 &&
5981         X86::isZeroNode(Op.getOperand(0)) &&
5982         !X86::isZeroNode(Op.getOperand(1))) {
5983       unsigned NumBits = VT.getSizeInBits();
5984       return getVShift(true, VT,
5985                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5986                                    VT, Op.getOperand(1)),
5987                        NumBits/2, DAG, *this, dl);
5988     }
5989
5990     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5991       return SDValue();
5992
5993     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5994     // is a non-constant being inserted into an element other than the low one,
5995     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5996     // movd/movss) to move this into the low element, then shuffle it into
5997     // place.
5998     if (EVTBits == 32) {
5999       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6000       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6001     }
6002   }
6003
6004   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6005   if (Values.size() == 1) {
6006     if (EVTBits == 32) {
6007       // Instead of a shuffle like this:
6008       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6009       // Check if it's possible to issue this instead.
6010       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6011       unsigned Idx = countTrailingZeros(NonZeros);
6012       SDValue Item = Op.getOperand(Idx);
6013       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6014         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6015     }
6016     return SDValue();
6017   }
6018
6019   // A vector full of immediates; various special cases are already
6020   // handled, so this is best done with a single constant-pool load.
6021   if (IsAllConstants)
6022     return SDValue();
6023
6024   // For AVX-length vectors, see if we can use a vector load to get all of the
6025   // elements, otherwise build the individual 128-bit pieces and use
6026   // shuffles to put them in place.
6027   if (VT.is256BitVector() || VT.is512BitVector()) {
6028     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6029
6030     // Check for a build vector of consecutive loads.
6031     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6032       return LD;
6033
6034     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6035
6036     // Build both the lower and upper subvector.
6037     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6038                                 makeArrayRef(&V[0], NumElems/2));
6039     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6040                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6041
6042     // Recreate the wider vector with the lower and upper part.
6043     if (VT.is256BitVector())
6044       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6045     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6046   }
6047
6048   // Let legalizer expand 2-wide build_vectors.
6049   if (EVTBits == 64) {
6050     if (NumNonZero == 1) {
6051       // One half is zero or undef.
6052       unsigned Idx = countTrailingZeros(NonZeros);
6053       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6054                                  Op.getOperand(Idx));
6055       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6056     }
6057     return SDValue();
6058   }
6059
6060   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6061   if (EVTBits == 8 && NumElems == 16)
6062     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6063                                         Subtarget, *this))
6064       return V;
6065
6066   if (EVTBits == 16 && NumElems == 8)
6067     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6068                                       Subtarget, *this))
6069       return V;
6070
6071   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6072   if (EVTBits == 32 && NumElems == 4)
6073     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6074       return V;
6075
6076   // If element VT is == 32 bits, turn it into a number of shuffles.
6077   SmallVector<SDValue, 8> V(NumElems);
6078   if (NumElems == 4 && NumZero > 0) {
6079     for (unsigned i = 0; i < 4; ++i) {
6080       bool isZero = !(NonZeros & (1 << i));
6081       if (isZero)
6082         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6083       else
6084         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6085     }
6086
6087     for (unsigned i = 0; i < 2; ++i) {
6088       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6089         default: break;
6090         case 0:
6091           V[i] = V[i*2];  // Must be a zero vector.
6092           break;
6093         case 1:
6094           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6095           break;
6096         case 2:
6097           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6098           break;
6099         case 3:
6100           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6101           break;
6102       }
6103     }
6104
6105     bool Reverse1 = (NonZeros & 0x3) == 2;
6106     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6107     int MaskVec[] = {
6108       Reverse1 ? 1 : 0,
6109       Reverse1 ? 0 : 1,
6110       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6111       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6112     };
6113     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6114   }
6115
6116   if (Values.size() > 1 && VT.is128BitVector()) {
6117     // Check for a build vector of consecutive loads.
6118     for (unsigned i = 0; i < NumElems; ++i)
6119       V[i] = Op.getOperand(i);
6120
6121     // Check for elements which are consecutive loads.
6122     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6123       return LD;
6124
6125     // Check for a build vector from mostly shuffle plus few inserting.
6126     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6127       return Sh;
6128
6129     // For SSE 4.1, use insertps to put the high elements into the low element.
6130     if (Subtarget->hasSSE41()) {
6131       SDValue Result;
6132       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6133         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6134       else
6135         Result = DAG.getUNDEF(VT);
6136
6137       for (unsigned i = 1; i < NumElems; ++i) {
6138         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6139         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6140                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6141       }
6142       return Result;
6143     }
6144
6145     // Otherwise, expand into a number of unpckl*, start by extending each of
6146     // our (non-undef) elements to the full vector width with the element in the
6147     // bottom slot of the vector (which generates no code for SSE).
6148     for (unsigned i = 0; i < NumElems; ++i) {
6149       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6150         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6151       else
6152         V[i] = DAG.getUNDEF(VT);
6153     }
6154
6155     // Next, we iteratively mix elements, e.g. for v4f32:
6156     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6157     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6158     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6159     unsigned EltStride = NumElems >> 1;
6160     while (EltStride != 0) {
6161       for (unsigned i = 0; i < EltStride; ++i) {
6162         // If V[i+EltStride] is undef and this is the first round of mixing,
6163         // then it is safe to just drop this shuffle: V[i] is already in the
6164         // right place, the one element (since it's the first round) being
6165         // inserted as undef can be dropped.  This isn't safe for successive
6166         // rounds because they will permute elements within both vectors.
6167         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6168             EltStride == NumElems/2)
6169           continue;
6170
6171         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6172       }
6173       EltStride >>= 1;
6174     }
6175     return V[0];
6176   }
6177   return SDValue();
6178 }
6179
6180 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6181 // to create 256-bit vectors from two other 128-bit ones.
6182 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6183   SDLoc dl(Op);
6184   MVT ResVT = Op.getSimpleValueType();
6185
6186   assert((ResVT.is256BitVector() ||
6187           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6188
6189   SDValue V1 = Op.getOperand(0);
6190   SDValue V2 = Op.getOperand(1);
6191   unsigned NumElems = ResVT.getVectorNumElements();
6192   if (ResVT.is256BitVector())
6193     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6194
6195   if (Op.getNumOperands() == 4) {
6196     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6197                                 ResVT.getVectorNumElements()/2);
6198     SDValue V3 = Op.getOperand(2);
6199     SDValue V4 = Op.getOperand(3);
6200     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6201       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6202   }
6203   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6204 }
6205
6206 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6207                                        const X86Subtarget *Subtarget,
6208                                        SelectionDAG & DAG) {
6209   SDLoc dl(Op);
6210   MVT ResVT = Op.getSimpleValueType();
6211   unsigned NumOfOperands = Op.getNumOperands();
6212
6213   assert(isPowerOf2_32(NumOfOperands) &&
6214          "Unexpected number of operands in CONCAT_VECTORS");
6215
6216   if (NumOfOperands > 2) {
6217     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6218                                   ResVT.getVectorNumElements()/2);
6219     SmallVector<SDValue, 2> Ops;
6220     for (unsigned i = 0; i < NumOfOperands/2; i++)
6221       Ops.push_back(Op.getOperand(i));
6222     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6223     Ops.clear();
6224     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6225       Ops.push_back(Op.getOperand(i));
6226     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6227     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6228   }
6229
6230   SDValue V1 = Op.getOperand(0);
6231   SDValue V2 = Op.getOperand(1);
6232   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6233   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6234
6235   if (IsZeroV1 && IsZeroV2)
6236     return getZeroVector(ResVT, Subtarget, DAG, dl);
6237
6238   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6239   SDValue Undef = DAG.getUNDEF(ResVT);
6240   unsigned NumElems = ResVT.getVectorNumElements();
6241   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6242
6243   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6244   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6245   if (IsZeroV1)
6246     return V2;
6247
6248   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6249   // Zero the upper bits of V1
6250   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6251   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6252   if (IsZeroV2)
6253     return V1;
6254   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6255 }
6256
6257 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6258                                    const X86Subtarget *Subtarget,
6259                                    SelectionDAG &DAG) {
6260   MVT VT = Op.getSimpleValueType();
6261   if (VT.getVectorElementType() == MVT::i1)
6262     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6263
6264   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6265          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6266           Op.getNumOperands() == 4)));
6267
6268   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6269   // from two other 128-bit ones.
6270
6271   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6272   return LowerAVXCONCAT_VECTORS(Op, DAG);
6273 }
6274
6275
6276 //===----------------------------------------------------------------------===//
6277 // Vector shuffle lowering
6278 //
6279 // This is an experimental code path for lowering vector shuffles on x86. It is
6280 // designed to handle arbitrary vector shuffles and blends, gracefully
6281 // degrading performance as necessary. It works hard to recognize idiomatic
6282 // shuffles and lower them to optimal instruction patterns without leaving
6283 // a framework that allows reasonably efficient handling of all vector shuffle
6284 // patterns.
6285 //===----------------------------------------------------------------------===//
6286
6287 /// \brief Tiny helper function to identify a no-op mask.
6288 ///
6289 /// This is a somewhat boring predicate function. It checks whether the mask
6290 /// array input, which is assumed to be a single-input shuffle mask of the kind
6291 /// used by the X86 shuffle instructions (not a fully general
6292 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6293 /// in-place shuffle are 'no-op's.
6294 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6295   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6296     if (Mask[i] != -1 && Mask[i] != i)
6297       return false;
6298   return true;
6299 }
6300
6301 /// \brief Helper function to classify a mask as a single-input mask.
6302 ///
6303 /// This isn't a generic single-input test because in the vector shuffle
6304 /// lowering we canonicalize single inputs to be the first input operand. This
6305 /// means we can more quickly test for a single input by only checking whether
6306 /// an input from the second operand exists. We also assume that the size of
6307 /// mask corresponds to the size of the input vectors which isn't true in the
6308 /// fully general case.
6309 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6310   for (int M : Mask)
6311     if (M >= (int)Mask.size())
6312       return false;
6313   return true;
6314 }
6315
6316 /// \brief Test whether there are elements crossing 128-bit lanes in this
6317 /// shuffle mask.
6318 ///
6319 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6320 /// and we routinely test for these.
6321 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6322   int LaneSize = 128 / VT.getScalarSizeInBits();
6323   int Size = Mask.size();
6324   for (int i = 0; i < Size; ++i)
6325     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6326       return true;
6327   return false;
6328 }
6329
6330 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6331 ///
6332 /// This checks a shuffle mask to see if it is performing the same
6333 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6334 /// that it is also not lane-crossing. It may however involve a blend from the
6335 /// same lane of a second vector.
6336 ///
6337 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6338 /// non-trivial to compute in the face of undef lanes. The representation is
6339 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6340 /// entries from both V1 and V2 inputs to the wider mask.
6341 static bool
6342 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6343                                 SmallVectorImpl<int> &RepeatedMask) {
6344   int LaneSize = 128 / VT.getScalarSizeInBits();
6345   RepeatedMask.resize(LaneSize, -1);
6346   int Size = Mask.size();
6347   for (int i = 0; i < Size; ++i) {
6348     if (Mask[i] < 0)
6349       continue;
6350     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6351       // This entry crosses lanes, so there is no way to model this shuffle.
6352       return false;
6353
6354     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6355     if (RepeatedMask[i % LaneSize] == -1)
6356       // This is the first non-undef entry in this slot of a 128-bit lane.
6357       RepeatedMask[i % LaneSize] =
6358           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6359     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6360       // Found a mismatch with the repeated mask.
6361       return false;
6362   }
6363   return true;
6364 }
6365
6366 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6367 /// arguments.
6368 ///
6369 /// This is a fast way to test a shuffle mask against a fixed pattern:
6370 ///
6371 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6372 ///
6373 /// It returns true if the mask is exactly as wide as the argument list, and
6374 /// each element of the mask is either -1 (signifying undef) or the value given
6375 /// in the argument.
6376 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6377                                 ArrayRef<int> ExpectedMask) {
6378   if (Mask.size() != ExpectedMask.size())
6379     return false;
6380
6381   int Size = Mask.size();
6382
6383   // If the values are build vectors, we can look through them to find
6384   // equivalent inputs that make the shuffles equivalent.
6385   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6386   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6387
6388   for (int i = 0; i < Size; ++i)
6389     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6390       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6391       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6392       if (!MaskBV || !ExpectedBV ||
6393           MaskBV->getOperand(Mask[i] % Size) !=
6394               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6395         return false;
6396     }
6397
6398   return true;
6399 }
6400
6401 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6402 ///
6403 /// This helper function produces an 8-bit shuffle immediate corresponding to
6404 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6405 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6406 /// example.
6407 ///
6408 /// NB: We rely heavily on "undef" masks preserving the input lane.
6409 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6410                                           SelectionDAG &DAG) {
6411   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6412   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6413   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6414   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6415   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6416
6417   unsigned Imm = 0;
6418   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6419   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6420   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6421   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6422   return DAG.getConstant(Imm, DL, MVT::i8);
6423 }
6424
6425 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6426 ///
6427 /// This is used as a fallback approach when first class blend instructions are
6428 /// unavailable. Currently it is only suitable for integer vectors, but could
6429 /// be generalized for floating point vectors if desirable.
6430 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6431                                             SDValue V2, ArrayRef<int> Mask,
6432                                             SelectionDAG &DAG) {
6433   assert(VT.isInteger() && "Only supports integer vector types!");
6434   MVT EltVT = VT.getScalarType();
6435   int NumEltBits = EltVT.getSizeInBits();
6436   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6437   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6438                                     EltVT);
6439   SmallVector<SDValue, 16> MaskOps;
6440   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6441     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6442       return SDValue(); // Shuffled input!
6443     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6444   }
6445
6446   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6447   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6448   // We have to cast V2 around.
6449   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6450   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6451                                       DAG.getBitcast(MaskVT, V1Mask),
6452                                       DAG.getBitcast(MaskVT, V2)));
6453   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6454 }
6455
6456 /// \brief Try to emit a blend instruction for a shuffle.
6457 ///
6458 /// This doesn't do any checks for the availability of instructions for blending
6459 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6460 /// be matched in the backend with the type given. What it does check for is
6461 /// that the shuffle mask is in fact a blend.
6462 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6463                                          SDValue V2, ArrayRef<int> Mask,
6464                                          const X86Subtarget *Subtarget,
6465                                          SelectionDAG &DAG) {
6466   unsigned BlendMask = 0;
6467   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6468     if (Mask[i] >= Size) {
6469       if (Mask[i] != i + Size)
6470         return SDValue(); // Shuffled V2 input!
6471       BlendMask |= 1u << i;
6472       continue;
6473     }
6474     if (Mask[i] >= 0 && Mask[i] != i)
6475       return SDValue(); // Shuffled V1 input!
6476   }
6477   switch (VT.SimpleTy) {
6478   case MVT::v2f64:
6479   case MVT::v4f32:
6480   case MVT::v4f64:
6481   case MVT::v8f32:
6482     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6483                        DAG.getConstant(BlendMask, DL, MVT::i8));
6484
6485   case MVT::v4i64:
6486   case MVT::v8i32:
6487     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6488     // FALLTHROUGH
6489   case MVT::v2i64:
6490   case MVT::v4i32:
6491     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6492     // that instruction.
6493     if (Subtarget->hasAVX2()) {
6494       // Scale the blend by the number of 32-bit dwords per element.
6495       int Scale =  VT.getScalarSizeInBits() / 32;
6496       BlendMask = 0;
6497       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6498         if (Mask[i] >= Size)
6499           for (int j = 0; j < Scale; ++j)
6500             BlendMask |= 1u << (i * Scale + j);
6501
6502       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6503       V1 = DAG.getBitcast(BlendVT, V1);
6504       V2 = DAG.getBitcast(BlendVT, V2);
6505       return DAG.getBitcast(
6506           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6507                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6508     }
6509     // FALLTHROUGH
6510   case MVT::v8i16: {
6511     // For integer shuffles we need to expand the mask and cast the inputs to
6512     // v8i16s prior to blending.
6513     int Scale = 8 / VT.getVectorNumElements();
6514     BlendMask = 0;
6515     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6516       if (Mask[i] >= Size)
6517         for (int j = 0; j < Scale; ++j)
6518           BlendMask |= 1u << (i * Scale + j);
6519
6520     V1 = DAG.getBitcast(MVT::v8i16, V1);
6521     V2 = DAG.getBitcast(MVT::v8i16, V2);
6522     return DAG.getBitcast(VT,
6523                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6524                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6525   }
6526
6527   case MVT::v16i16: {
6528     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6529     SmallVector<int, 8> RepeatedMask;
6530     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6531       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6532       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6533       BlendMask = 0;
6534       for (int i = 0; i < 8; ++i)
6535         if (RepeatedMask[i] >= 16)
6536           BlendMask |= 1u << i;
6537       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6538                          DAG.getConstant(BlendMask, DL, MVT::i8));
6539     }
6540   }
6541     // FALLTHROUGH
6542   case MVT::v16i8:
6543   case MVT::v32i8: {
6544     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6545            "256-bit byte-blends require AVX2 support!");
6546
6547     // Scale the blend by the number of bytes per element.
6548     int Scale = VT.getScalarSizeInBits() / 8;
6549
6550     // This form of blend is always done on bytes. Compute the byte vector
6551     // type.
6552     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6553
6554     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6555     // mix of LLVM's code generator and the x86 backend. We tell the code
6556     // generator that boolean values in the elements of an x86 vector register
6557     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6558     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6559     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6560     // of the element (the remaining are ignored) and 0 in that high bit would
6561     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6562     // the LLVM model for boolean values in vector elements gets the relevant
6563     // bit set, it is set backwards and over constrained relative to x86's
6564     // actual model.
6565     SmallVector<SDValue, 32> VSELECTMask;
6566     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6567       for (int j = 0; j < Scale; ++j)
6568         VSELECTMask.push_back(
6569             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6570                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6571                                           MVT::i8));
6572
6573     V1 = DAG.getBitcast(BlendVT, V1);
6574     V2 = DAG.getBitcast(BlendVT, V2);
6575     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6576                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6577                                                       BlendVT, VSELECTMask),
6578                                           V1, V2));
6579   }
6580
6581   default:
6582     llvm_unreachable("Not a supported integer vector type!");
6583   }
6584 }
6585
6586 /// \brief Try to lower as a blend of elements from two inputs followed by
6587 /// a single-input permutation.
6588 ///
6589 /// This matches the pattern where we can blend elements from two inputs and
6590 /// then reduce the shuffle to a single-input permutation.
6591 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6592                                                    SDValue V2,
6593                                                    ArrayRef<int> Mask,
6594                                                    SelectionDAG &DAG) {
6595   // We build up the blend mask while checking whether a blend is a viable way
6596   // to reduce the shuffle.
6597   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6598   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6599
6600   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6601     if (Mask[i] < 0)
6602       continue;
6603
6604     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6605
6606     if (BlendMask[Mask[i] % Size] == -1)
6607       BlendMask[Mask[i] % Size] = Mask[i];
6608     else if (BlendMask[Mask[i] % Size] != Mask[i])
6609       return SDValue(); // Can't blend in the needed input!
6610
6611     PermuteMask[i] = Mask[i] % Size;
6612   }
6613
6614   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6615   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6616 }
6617
6618 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6619 /// blends and permutes.
6620 ///
6621 /// This matches the extremely common pattern for handling combined
6622 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6623 /// operations. It will try to pick the best arrangement of shuffles and
6624 /// blends.
6625 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6626                                                           SDValue V1,
6627                                                           SDValue V2,
6628                                                           ArrayRef<int> Mask,
6629                                                           SelectionDAG &DAG) {
6630   // Shuffle the input elements into the desired positions in V1 and V2 and
6631   // blend them together.
6632   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6633   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6634   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6635   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6636     if (Mask[i] >= 0 && Mask[i] < Size) {
6637       V1Mask[i] = Mask[i];
6638       BlendMask[i] = i;
6639     } else if (Mask[i] >= Size) {
6640       V2Mask[i] = Mask[i] - Size;
6641       BlendMask[i] = i + Size;
6642     }
6643
6644   // Try to lower with the simpler initial blend strategy unless one of the
6645   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6646   // shuffle may be able to fold with a load or other benefit. However, when
6647   // we'll have to do 2x as many shuffles in order to achieve this, blending
6648   // first is a better strategy.
6649   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6650     if (SDValue BlendPerm =
6651             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6652       return BlendPerm;
6653
6654   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6655   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6656   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6657 }
6658
6659 /// \brief Try to lower a vector shuffle as a byte rotation.
6660 ///
6661 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6662 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6663 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6664 /// try to generically lower a vector shuffle through such an pattern. It
6665 /// does not check for the profitability of lowering either as PALIGNR or
6666 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6667 /// This matches shuffle vectors that look like:
6668 ///
6669 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6670 ///
6671 /// Essentially it concatenates V1 and V2, shifts right by some number of
6672 /// elements, and takes the low elements as the result. Note that while this is
6673 /// specified as a *right shift* because x86 is little-endian, it is a *left
6674 /// rotate* of the vector lanes.
6675 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6676                                               SDValue V2,
6677                                               ArrayRef<int> Mask,
6678                                               const X86Subtarget *Subtarget,
6679                                               SelectionDAG &DAG) {
6680   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6681
6682   int NumElts = Mask.size();
6683   int NumLanes = VT.getSizeInBits() / 128;
6684   int NumLaneElts = NumElts / NumLanes;
6685
6686   // We need to detect various ways of spelling a rotation:
6687   //   [11, 12, 13, 14, 15,  0,  1,  2]
6688   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6689   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6690   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6691   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6692   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6693   int Rotation = 0;
6694   SDValue Lo, Hi;
6695   for (int l = 0; l < NumElts; l += NumLaneElts) {
6696     for (int i = 0; i < NumLaneElts; ++i) {
6697       if (Mask[l + i] == -1)
6698         continue;
6699       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6700
6701       // Get the mod-Size index and lane correct it.
6702       int LaneIdx = (Mask[l + i] % NumElts) - l;
6703       // Make sure it was in this lane.
6704       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6705         return SDValue();
6706
6707       // Determine where a rotated vector would have started.
6708       int StartIdx = i - LaneIdx;
6709       if (StartIdx == 0)
6710         // The identity rotation isn't interesting, stop.
6711         return SDValue();
6712
6713       // If we found the tail of a vector the rotation must be the missing
6714       // front. If we found the head of a vector, it must be how much of the
6715       // head.
6716       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6717
6718       if (Rotation == 0)
6719         Rotation = CandidateRotation;
6720       else if (Rotation != CandidateRotation)
6721         // The rotations don't match, so we can't match this mask.
6722         return SDValue();
6723
6724       // Compute which value this mask is pointing at.
6725       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6726
6727       // Compute which of the two target values this index should be assigned
6728       // to. This reflects whether the high elements are remaining or the low
6729       // elements are remaining.
6730       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6731
6732       // Either set up this value if we've not encountered it before, or check
6733       // that it remains consistent.
6734       if (!TargetV)
6735         TargetV = MaskV;
6736       else if (TargetV != MaskV)
6737         // This may be a rotation, but it pulls from the inputs in some
6738         // unsupported interleaving.
6739         return SDValue();
6740     }
6741   }
6742
6743   // Check that we successfully analyzed the mask, and normalize the results.
6744   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6745   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6746   if (!Lo)
6747     Lo = Hi;
6748   else if (!Hi)
6749     Hi = Lo;
6750
6751   // The actual rotate instruction rotates bytes, so we need to scale the
6752   // rotation based on how many bytes are in the vector lane.
6753   int Scale = 16 / NumLaneElts;
6754
6755   // SSSE3 targets can use the palignr instruction.
6756   if (Subtarget->hasSSSE3()) {
6757     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6758     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6759     Lo = DAG.getBitcast(AlignVT, Lo);
6760     Hi = DAG.getBitcast(AlignVT, Hi);
6761
6762     return DAG.getBitcast(
6763         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6764                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6765   }
6766
6767   assert(VT.getSizeInBits() == 128 &&
6768          "Rotate-based lowering only supports 128-bit lowering!");
6769   assert(Mask.size() <= 16 &&
6770          "Can shuffle at most 16 bytes in a 128-bit vector!");
6771
6772   // Default SSE2 implementation
6773   int LoByteShift = 16 - Rotation * Scale;
6774   int HiByteShift = Rotation * Scale;
6775
6776   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6777   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6778   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6779
6780   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6781                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6782   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6783                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6784   return DAG.getBitcast(VT,
6785                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6786 }
6787
6788 /// \brief Compute whether each element of a shuffle is zeroable.
6789 ///
6790 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6791 /// Either it is an undef element in the shuffle mask, the element of the input
6792 /// referenced is undef, or the element of the input referenced is known to be
6793 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6794 /// as many lanes with this technique as possible to simplify the remaining
6795 /// shuffle.
6796 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6797                                                      SDValue V1, SDValue V2) {
6798   SmallBitVector Zeroable(Mask.size(), false);
6799
6800   while (V1.getOpcode() == ISD::BITCAST)
6801     V1 = V1->getOperand(0);
6802   while (V2.getOpcode() == ISD::BITCAST)
6803     V2 = V2->getOperand(0);
6804
6805   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6806   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6807
6808   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6809     int M = Mask[i];
6810     // Handle the easy cases.
6811     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6812       Zeroable[i] = true;
6813       continue;
6814     }
6815
6816     // If this is an index into a build_vector node (which has the same number
6817     // of elements), dig out the input value and use it.
6818     SDValue V = M < Size ? V1 : V2;
6819     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6820       continue;
6821
6822     SDValue Input = V.getOperand(M % Size);
6823     // The UNDEF opcode check really should be dead code here, but not quite
6824     // worth asserting on (it isn't invalid, just unexpected).
6825     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6826       Zeroable[i] = true;
6827   }
6828
6829   return Zeroable;
6830 }
6831
6832 /// \brief Try to emit a bitmask instruction for a shuffle.
6833 ///
6834 /// This handles cases where we can model a blend exactly as a bitmask due to
6835 /// one of the inputs being zeroable.
6836 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6837                                            SDValue V2, ArrayRef<int> Mask,
6838                                            SelectionDAG &DAG) {
6839   MVT EltVT = VT.getScalarType();
6840   int NumEltBits = EltVT.getSizeInBits();
6841   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6842   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6843   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6844                                     IntEltVT);
6845   if (EltVT.isFloatingPoint()) {
6846     Zero = DAG.getBitcast(EltVT, Zero);
6847     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6848   }
6849   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6850   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6851   SDValue V;
6852   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6853     if (Zeroable[i])
6854       continue;
6855     if (Mask[i] % Size != i)
6856       return SDValue(); // Not a blend.
6857     if (!V)
6858       V = Mask[i] < Size ? V1 : V2;
6859     else if (V != (Mask[i] < Size ? V1 : V2))
6860       return SDValue(); // Can only let one input through the mask.
6861
6862     VMaskOps[i] = AllOnes;
6863   }
6864   if (!V)
6865     return SDValue(); // No non-zeroable elements!
6866
6867   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6868   V = DAG.getNode(VT.isFloatingPoint()
6869                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6870                   DL, VT, V, VMask);
6871   return V;
6872 }
6873
6874 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6875 ///
6876 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6877 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6878 /// matches elements from one of the input vectors shuffled to the left or
6879 /// right with zeroable elements 'shifted in'. It handles both the strictly
6880 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6881 /// quad word lane.
6882 ///
6883 /// PSHL : (little-endian) left bit shift.
6884 /// [ zz, 0, zz,  2 ]
6885 /// [ -1, 4, zz, -1 ]
6886 /// PSRL : (little-endian) right bit shift.
6887 /// [  1, zz,  3, zz]
6888 /// [ -1, -1,  7, zz]
6889 /// PSLLDQ : (little-endian) left byte shift
6890 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6891 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6892 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6893 /// PSRLDQ : (little-endian) right byte shift
6894 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6895 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6896 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6897 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6898                                          SDValue V2, ArrayRef<int> Mask,
6899                                          SelectionDAG &DAG) {
6900   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6901
6902   int Size = Mask.size();
6903   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6904
6905   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6906     for (int i = 0; i < Size; i += Scale)
6907       for (int j = 0; j < Shift; ++j)
6908         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6909           return false;
6910
6911     return true;
6912   };
6913
6914   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6915     for (int i = 0; i != Size; i += Scale) {
6916       unsigned Pos = Left ? i + Shift : i;
6917       unsigned Low = Left ? i : i + Shift;
6918       unsigned Len = Scale - Shift;
6919       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6920                                       Low + (V == V1 ? 0 : Size)))
6921         return SDValue();
6922     }
6923
6924     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6925     bool ByteShift = ShiftEltBits > 64;
6926     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6927                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6928     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6929
6930     // Normalize the scale for byte shifts to still produce an i64 element
6931     // type.
6932     Scale = ByteShift ? Scale / 2 : Scale;
6933
6934     // We need to round trip through the appropriate type for the shift.
6935     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6936     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6937     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6938            "Illegal integer vector type");
6939     V = DAG.getBitcast(ShiftVT, V);
6940
6941     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6942                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6943     return DAG.getBitcast(VT, V);
6944   };
6945
6946   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6947   // keep doubling the size of the integer elements up to that. We can
6948   // then shift the elements of the integer vector by whole multiples of
6949   // their width within the elements of the larger integer vector. Test each
6950   // multiple to see if we can find a match with the moved element indices
6951   // and that the shifted in elements are all zeroable.
6952   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6953     for (int Shift = 1; Shift != Scale; ++Shift)
6954       for (bool Left : {true, false})
6955         if (CheckZeros(Shift, Scale, Left))
6956           for (SDValue V : {V1, V2})
6957             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6958               return Match;
6959
6960   // no match
6961   return SDValue();
6962 }
6963
6964 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6965 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6966                                            SDValue V2, ArrayRef<int> Mask,
6967                                            SelectionDAG &DAG) {
6968   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6969   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6970
6971   int Size = Mask.size();
6972   int HalfSize = Size / 2;
6973   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6974
6975   // Upper half must be undefined.
6976   if (!isUndefInRange(Mask, HalfSize, HalfSize))
6977     return SDValue();
6978
6979   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
6980   // Remainder of lower half result is zero and upper half is all undef.
6981   auto LowerAsEXTRQ = [&]() {
6982     // Determine the extraction length from the part of the
6983     // lower half that isn't zeroable.
6984     int Len = HalfSize;
6985     for (; Len >= 0; --Len)
6986       if (!Zeroable[Len - 1])
6987         break;
6988     assert(Len > 0 && "Zeroable shuffle mask");
6989
6990     // Attempt to match first Len sequential elements from the lower half.
6991     SDValue Src;
6992     int Idx = -1;
6993     for (int i = 0; i != Len; ++i) {
6994       int M = Mask[i];
6995       if (M < 0)
6996         continue;
6997       SDValue &V = (M < Size ? V1 : V2);
6998       M = M % Size;
6999
7000       // All mask elements must be in the lower half.
7001       if (M > HalfSize)
7002         return SDValue();
7003
7004       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7005         Src = V;
7006         Idx = M - i;
7007         continue;
7008       }
7009       return SDValue();
7010     }
7011
7012     if (Idx < 0)
7013       return SDValue();
7014
7015     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7016     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7017     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7018     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7019                        DAG.getConstant(BitLen, DL, MVT::i8),
7020                        DAG.getConstant(BitIdx, DL, MVT::i8));
7021   };
7022
7023   if (SDValue ExtrQ = LowerAsEXTRQ())
7024     return ExtrQ;
7025
7026   // INSERTQ: Extract lowest Len elements from lower half of second source and
7027   // insert over first source, starting at Idx.
7028   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7029   auto LowerAsInsertQ = [&]() {
7030     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7031       SDValue Base;
7032
7033       // Attempt to match first source from mask before insertion point.
7034       if (isUndefInRange(Mask, 0, Idx)) {
7035         /* EMPTY */
7036       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7037         Base = V1;
7038       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7039         Base = V2;
7040       } else {
7041         continue;
7042       }
7043
7044       // Extend the extraction length looking to match both the insertion of
7045       // the second source and the remaining elements of the first.
7046       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7047         SDValue Insert;
7048         int Len = Hi - Idx;
7049
7050         // Match insertion.
7051         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7052           Insert = V1;
7053         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7054           Insert = V2;
7055         } else {
7056           continue;
7057         }
7058
7059         // Match the remaining elements of the lower half.
7060         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7061           /* EMPTY */
7062         } else if ((!Base || (Base == V1)) &&
7063                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7064           Base = V1;
7065         } else if ((!Base || (Base == V2)) &&
7066                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7067                                               Size + Hi)) {
7068           Base = V2;
7069         } else {
7070           continue;
7071         }
7072
7073         // We may not have a base (first source) - this can safely be undefined.
7074         if (!Base)
7075           Base = DAG.getUNDEF(VT);
7076
7077         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7078         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7079         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7080                            DAG.getConstant(BitLen, DL, MVT::i8),
7081                            DAG.getConstant(BitIdx, DL, MVT::i8));
7082       }
7083     }
7084
7085     return SDValue();
7086   };
7087
7088   if (SDValue InsertQ = LowerAsInsertQ())
7089     return InsertQ;
7090
7091   return SDValue();
7092 }
7093
7094 /// \brief Lower a vector shuffle as a zero or any extension.
7095 ///
7096 /// Given a specific number of elements, element bit width, and extension
7097 /// stride, produce either a zero or any extension based on the available
7098 /// features of the subtarget.
7099 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7100     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7101     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7102   assert(Scale > 1 && "Need a scale to extend.");
7103   int NumElements = VT.getVectorNumElements();
7104   int EltBits = VT.getScalarSizeInBits();
7105   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7106          "Only 8, 16, and 32 bit elements can be extended.");
7107   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7108
7109   // Found a valid zext mask! Try various lowering strategies based on the
7110   // input type and available ISA extensions.
7111   if (Subtarget->hasSSE41()) {
7112     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7113                                  NumElements / Scale);
7114     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7115   }
7116
7117   // For any extends we can cheat for larger element sizes and use shuffle
7118   // instructions that can fold with a load and/or copy.
7119   if (AnyExt && EltBits == 32) {
7120     int PSHUFDMask[4] = {0, -1, 1, -1};
7121     return DAG.getBitcast(
7122         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7123                         DAG.getBitcast(MVT::v4i32, InputV),
7124                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7125   }
7126   if (AnyExt && EltBits == 16 && Scale > 2) {
7127     int PSHUFDMask[4] = {0, -1, 0, -1};
7128     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7129                          DAG.getBitcast(MVT::v4i32, InputV),
7130                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7131     int PSHUFHWMask[4] = {1, -1, -1, -1};
7132     return DAG.getBitcast(
7133         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7134                         DAG.getBitcast(MVT::v8i16, InputV),
7135                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7136   }
7137
7138   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7139   // to 64-bits.
7140   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7141     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7142     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7143
7144     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7145                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7146                                          DAG.getConstant(EltBits, DL, MVT::i8),
7147                                          DAG.getConstant(0, DL, MVT::i8)));
7148     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7149       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7150
7151     SDValue Hi =
7152         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7153                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7154                                 DAG.getConstant(EltBits, DL, MVT::i8),
7155                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7156     return DAG.getNode(ISD::BITCAST, DL, VT,
7157                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7158   }
7159
7160   // If this would require more than 2 unpack instructions to expand, use
7161   // pshufb when available. We can only use more than 2 unpack instructions
7162   // when zero extending i8 elements which also makes it easier to use pshufb.
7163   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7164     assert(NumElements == 16 && "Unexpected byte vector width!");
7165     SDValue PSHUFBMask[16];
7166     for (int i = 0; i < 16; ++i)
7167       PSHUFBMask[i] =
7168           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7169     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7170     return DAG.getBitcast(VT,
7171                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7172                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7173                                                   MVT::v16i8, PSHUFBMask)));
7174   }
7175
7176   // Otherwise emit a sequence of unpacks.
7177   do {
7178     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7179     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7180                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7181     InputV = DAG.getBitcast(InputVT, InputV);
7182     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7183     Scale /= 2;
7184     EltBits *= 2;
7185     NumElements /= 2;
7186   } while (Scale > 1);
7187   return DAG.getBitcast(VT, InputV);
7188 }
7189
7190 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7191 ///
7192 /// This routine will try to do everything in its power to cleverly lower
7193 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7194 /// check for the profitability of this lowering,  it tries to aggressively
7195 /// match this pattern. It will use all of the micro-architectural details it
7196 /// can to emit an efficient lowering. It handles both blends with all-zero
7197 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7198 /// masking out later).
7199 ///
7200 /// The reason we have dedicated lowering for zext-style shuffles is that they
7201 /// are both incredibly common and often quite performance sensitive.
7202 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7203     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7204     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7205   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7206
7207   int Bits = VT.getSizeInBits();
7208   int NumElements = VT.getVectorNumElements();
7209   assert(VT.getScalarSizeInBits() <= 32 &&
7210          "Exceeds 32-bit integer zero extension limit");
7211   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7212
7213   // Define a helper function to check a particular ext-scale and lower to it if
7214   // valid.
7215   auto Lower = [&](int Scale) -> SDValue {
7216     SDValue InputV;
7217     bool AnyExt = true;
7218     for (int i = 0; i < NumElements; ++i) {
7219       if (Mask[i] == -1)
7220         continue; // Valid anywhere but doesn't tell us anything.
7221       if (i % Scale != 0) {
7222         // Each of the extended elements need to be zeroable.
7223         if (!Zeroable[i])
7224           return SDValue();
7225
7226         // We no longer are in the anyext case.
7227         AnyExt = false;
7228         continue;
7229       }
7230
7231       // Each of the base elements needs to be consecutive indices into the
7232       // same input vector.
7233       SDValue V = Mask[i] < NumElements ? V1 : V2;
7234       if (!InputV)
7235         InputV = V;
7236       else if (InputV != V)
7237         return SDValue(); // Flip-flopping inputs.
7238
7239       if (Mask[i] % NumElements != i / Scale)
7240         return SDValue(); // Non-consecutive strided elements.
7241     }
7242
7243     // If we fail to find an input, we have a zero-shuffle which should always
7244     // have already been handled.
7245     // FIXME: Maybe handle this here in case during blending we end up with one?
7246     if (!InputV)
7247       return SDValue();
7248
7249     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7250         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7251   };
7252
7253   // The widest scale possible for extending is to a 64-bit integer.
7254   assert(Bits % 64 == 0 &&
7255          "The number of bits in a vector must be divisible by 64 on x86!");
7256   int NumExtElements = Bits / 64;
7257
7258   // Each iteration, try extending the elements half as much, but into twice as
7259   // many elements.
7260   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7261     assert(NumElements % NumExtElements == 0 &&
7262            "The input vector size must be divisible by the extended size.");
7263     if (SDValue V = Lower(NumElements / NumExtElements))
7264       return V;
7265   }
7266
7267   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7268   if (Bits != 128)
7269     return SDValue();
7270
7271   // Returns one of the source operands if the shuffle can be reduced to a
7272   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7273   auto CanZExtLowHalf = [&]() {
7274     for (int i = NumElements / 2; i != NumElements; ++i)
7275       if (!Zeroable[i])
7276         return SDValue();
7277     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7278       return V1;
7279     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7280       return V2;
7281     return SDValue();
7282   };
7283
7284   if (SDValue V = CanZExtLowHalf()) {
7285     V = DAG.getBitcast(MVT::v2i64, V);
7286     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7287     return DAG.getBitcast(VT, V);
7288   }
7289
7290   // No viable ext lowering found.
7291   return SDValue();
7292 }
7293
7294 /// \brief Try to get a scalar value for a specific element of a vector.
7295 ///
7296 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7297 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7298                                               SelectionDAG &DAG) {
7299   MVT VT = V.getSimpleValueType();
7300   MVT EltVT = VT.getVectorElementType();
7301   while (V.getOpcode() == ISD::BITCAST)
7302     V = V.getOperand(0);
7303   // If the bitcasts shift the element size, we can't extract an equivalent
7304   // element from it.
7305   MVT NewVT = V.getSimpleValueType();
7306   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7307     return SDValue();
7308
7309   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7310       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7311     // Ensure the scalar operand is the same size as the destination.
7312     // FIXME: Add support for scalar truncation where possible.
7313     SDValue S = V.getOperand(Idx);
7314     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7315       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7316   }
7317
7318   return SDValue();
7319 }
7320
7321 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7322 ///
7323 /// This is particularly important because the set of instructions varies
7324 /// significantly based on whether the operand is a load or not.
7325 static bool isShuffleFoldableLoad(SDValue V) {
7326   while (V.getOpcode() == ISD::BITCAST)
7327     V = V.getOperand(0);
7328
7329   return ISD::isNON_EXTLoad(V.getNode());
7330 }
7331
7332 /// \brief Try to lower insertion of a single element into a zero vector.
7333 ///
7334 /// This is a common pattern that we have especially efficient patterns to lower
7335 /// across all subtarget feature sets.
7336 static SDValue lowerVectorShuffleAsElementInsertion(
7337     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7338     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7339   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7340   MVT ExtVT = VT;
7341   MVT EltVT = VT.getVectorElementType();
7342
7343   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7344                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7345                 Mask.begin();
7346   bool IsV1Zeroable = true;
7347   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7348     if (i != V2Index && !Zeroable[i]) {
7349       IsV1Zeroable = false;
7350       break;
7351     }
7352
7353   // Check for a single input from a SCALAR_TO_VECTOR node.
7354   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7355   // all the smarts here sunk into that routine. However, the current
7356   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7357   // vector shuffle lowering is dead.
7358   if (SDValue V2S = getScalarValueForVectorElement(
7359           V2, Mask[V2Index] - Mask.size(), DAG)) {
7360     // We need to zext the scalar if it is smaller than an i32.
7361     V2S = DAG.getBitcast(EltVT, V2S);
7362     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7363       // Using zext to expand a narrow element won't work for non-zero
7364       // insertions.
7365       if (!IsV1Zeroable)
7366         return SDValue();
7367
7368       // Zero-extend directly to i32.
7369       ExtVT = MVT::v4i32;
7370       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7371     }
7372     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7373   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7374              EltVT == MVT::i16) {
7375     // Either not inserting from the low element of the input or the input
7376     // element size is too small to use VZEXT_MOVL to clear the high bits.
7377     return SDValue();
7378   }
7379
7380   if (!IsV1Zeroable) {
7381     // If V1 can't be treated as a zero vector we have fewer options to lower
7382     // this. We can't support integer vectors or non-zero targets cheaply, and
7383     // the V1 elements can't be permuted in any way.
7384     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7385     if (!VT.isFloatingPoint() || V2Index != 0)
7386       return SDValue();
7387     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7388     V1Mask[V2Index] = -1;
7389     if (!isNoopShuffleMask(V1Mask))
7390       return SDValue();
7391     // This is essentially a special case blend operation, but if we have
7392     // general purpose blend operations, they are always faster. Bail and let
7393     // the rest of the lowering handle these as blends.
7394     if (Subtarget->hasSSE41())
7395       return SDValue();
7396
7397     // Otherwise, use MOVSD or MOVSS.
7398     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7399            "Only two types of floating point element types to handle!");
7400     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7401                        ExtVT, V1, V2);
7402   }
7403
7404   // This lowering only works for the low element with floating point vectors.
7405   if (VT.isFloatingPoint() && V2Index != 0)
7406     return SDValue();
7407
7408   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7409   if (ExtVT != VT)
7410     V2 = DAG.getBitcast(VT, V2);
7411
7412   if (V2Index != 0) {
7413     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7414     // the desired position. Otherwise it is more efficient to do a vector
7415     // shift left. We know that we can do a vector shift left because all
7416     // the inputs are zero.
7417     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7418       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7419       V2Shuffle[V2Index] = 0;
7420       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7421     } else {
7422       V2 = DAG.getBitcast(MVT::v2i64, V2);
7423       V2 = DAG.getNode(
7424           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7425           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7426                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7427                               DAG.getDataLayout(), VT)));
7428       V2 = DAG.getBitcast(VT, V2);
7429     }
7430   }
7431   return V2;
7432 }
7433
7434 /// \brief Try to lower broadcast of a single element.
7435 ///
7436 /// For convenience, this code also bundles all of the subtarget feature set
7437 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7438 /// a convenient way to factor it out.
7439 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7440                                              ArrayRef<int> Mask,
7441                                              const X86Subtarget *Subtarget,
7442                                              SelectionDAG &DAG) {
7443   if (!Subtarget->hasAVX())
7444     return SDValue();
7445   if (VT.isInteger() && !Subtarget->hasAVX2())
7446     return SDValue();
7447
7448   // Check that the mask is a broadcast.
7449   int BroadcastIdx = -1;
7450   for (int M : Mask)
7451     if (M >= 0 && BroadcastIdx == -1)
7452       BroadcastIdx = M;
7453     else if (M >= 0 && M != BroadcastIdx)
7454       return SDValue();
7455
7456   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7457                                             "a sorted mask where the broadcast "
7458                                             "comes from V1.");
7459
7460   // Go up the chain of (vector) values to find a scalar load that we can
7461   // combine with the broadcast.
7462   for (;;) {
7463     switch (V.getOpcode()) {
7464     case ISD::CONCAT_VECTORS: {
7465       int OperandSize = Mask.size() / V.getNumOperands();
7466       V = V.getOperand(BroadcastIdx / OperandSize);
7467       BroadcastIdx %= OperandSize;
7468       continue;
7469     }
7470
7471     case ISD::INSERT_SUBVECTOR: {
7472       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7473       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7474       if (!ConstantIdx)
7475         break;
7476
7477       int BeginIdx = (int)ConstantIdx->getZExtValue();
7478       int EndIdx =
7479           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7480       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7481         BroadcastIdx -= BeginIdx;
7482         V = VInner;
7483       } else {
7484         V = VOuter;
7485       }
7486       continue;
7487     }
7488     }
7489     break;
7490   }
7491
7492   // Check if this is a broadcast of a scalar. We special case lowering
7493   // for scalars so that we can more effectively fold with loads.
7494   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7495       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7496     V = V.getOperand(BroadcastIdx);
7497
7498     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7499     // Only AVX2 has register broadcasts.
7500     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7501       return SDValue();
7502   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7503     // We can't broadcast from a vector register without AVX2, and we can only
7504     // broadcast from the zero-element of a vector register.
7505     return SDValue();
7506   }
7507
7508   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7509 }
7510
7511 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7512 // INSERTPS when the V1 elements are already in the correct locations
7513 // because otherwise we can just always use two SHUFPS instructions which
7514 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7515 // perform INSERTPS if a single V1 element is out of place and all V2
7516 // elements are zeroable.
7517 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7518                                             ArrayRef<int> Mask,
7519                                             SelectionDAG &DAG) {
7520   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7521   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7522   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7523   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7524
7525   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7526
7527   unsigned ZMask = 0;
7528   int V1DstIndex = -1;
7529   int V2DstIndex = -1;
7530   bool V1UsedInPlace = false;
7531
7532   for (int i = 0; i < 4; ++i) {
7533     // Synthesize a zero mask from the zeroable elements (includes undefs).
7534     if (Zeroable[i]) {
7535       ZMask |= 1 << i;
7536       continue;
7537     }
7538
7539     // Flag if we use any V1 inputs in place.
7540     if (i == Mask[i]) {
7541       V1UsedInPlace = true;
7542       continue;
7543     }
7544
7545     // We can only insert a single non-zeroable element.
7546     if (V1DstIndex != -1 || V2DstIndex != -1)
7547       return SDValue();
7548
7549     if (Mask[i] < 4) {
7550       // V1 input out of place for insertion.
7551       V1DstIndex = i;
7552     } else {
7553       // V2 input for insertion.
7554       V2DstIndex = i;
7555     }
7556   }
7557
7558   // Don't bother if we have no (non-zeroable) element for insertion.
7559   if (V1DstIndex == -1 && V2DstIndex == -1)
7560     return SDValue();
7561
7562   // Determine element insertion src/dst indices. The src index is from the
7563   // start of the inserted vector, not the start of the concatenated vector.
7564   unsigned V2SrcIndex = 0;
7565   if (V1DstIndex != -1) {
7566     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7567     // and don't use the original V2 at all.
7568     V2SrcIndex = Mask[V1DstIndex];
7569     V2DstIndex = V1DstIndex;
7570     V2 = V1;
7571   } else {
7572     V2SrcIndex = Mask[V2DstIndex] - 4;
7573   }
7574
7575   // If no V1 inputs are used in place, then the result is created only from
7576   // the zero mask and the V2 insertion - so remove V1 dependency.
7577   if (!V1UsedInPlace)
7578     V1 = DAG.getUNDEF(MVT::v4f32);
7579
7580   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7581   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7582
7583   // Insert the V2 element into the desired position.
7584   SDLoc DL(Op);
7585   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7586                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7587 }
7588
7589 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7590 /// UNPCK instruction.
7591 ///
7592 /// This specifically targets cases where we end up with alternating between
7593 /// the two inputs, and so can permute them into something that feeds a single
7594 /// UNPCK instruction. Note that this routine only targets integer vectors
7595 /// because for floating point vectors we have a generalized SHUFPS lowering
7596 /// strategy that handles everything that doesn't *exactly* match an unpack,
7597 /// making this clever lowering unnecessary.
7598 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7599                                           SDValue V2, ArrayRef<int> Mask,
7600                                           SelectionDAG &DAG) {
7601   assert(!VT.isFloatingPoint() &&
7602          "This routine only supports integer vectors.");
7603   assert(!isSingleInputShuffleMask(Mask) &&
7604          "This routine should only be used when blending two inputs.");
7605   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7606
7607   int Size = Mask.size();
7608
7609   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7610     return M >= 0 && M % Size < Size / 2;
7611   });
7612   int NumHiInputs = std::count_if(
7613       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7614
7615   bool UnpackLo = NumLoInputs >= NumHiInputs;
7616
7617   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7618     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7619     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7620
7621     for (int i = 0; i < Size; ++i) {
7622       if (Mask[i] < 0)
7623         continue;
7624
7625       // Each element of the unpack contains Scale elements from this mask.
7626       int UnpackIdx = i / Scale;
7627
7628       // We only handle the case where V1 feeds the first slots of the unpack.
7629       // We rely on canonicalization to ensure this is the case.
7630       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7631         return SDValue();
7632
7633       // Setup the mask for this input. The indexing is tricky as we have to
7634       // handle the unpack stride.
7635       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7636       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7637           Mask[i] % Size;
7638     }
7639
7640     // If we will have to shuffle both inputs to use the unpack, check whether
7641     // we can just unpack first and shuffle the result. If so, skip this unpack.
7642     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7643         !isNoopShuffleMask(V2Mask))
7644       return SDValue();
7645
7646     // Shuffle the inputs into place.
7647     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7648     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7649
7650     // Cast the inputs to the type we will use to unpack them.
7651     V1 = DAG.getBitcast(UnpackVT, V1);
7652     V2 = DAG.getBitcast(UnpackVT, V2);
7653
7654     // Unpack the inputs and cast the result back to the desired type.
7655     return DAG.getBitcast(
7656         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7657                         UnpackVT, V1, V2));
7658   };
7659
7660   // We try each unpack from the largest to the smallest to try and find one
7661   // that fits this mask.
7662   int OrigNumElements = VT.getVectorNumElements();
7663   int OrigScalarSize = VT.getScalarSizeInBits();
7664   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7665     int Scale = ScalarSize / OrigScalarSize;
7666     int NumElements = OrigNumElements / Scale;
7667     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7668     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7669       return Unpack;
7670   }
7671
7672   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7673   // initial unpack.
7674   if (NumLoInputs == 0 || NumHiInputs == 0) {
7675     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7676            "We have to have *some* inputs!");
7677     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7678
7679     // FIXME: We could consider the total complexity of the permute of each
7680     // possible unpacking. Or at the least we should consider how many
7681     // half-crossings are created.
7682     // FIXME: We could consider commuting the unpacks.
7683
7684     SmallVector<int, 32> PermMask;
7685     PermMask.assign(Size, -1);
7686     for (int i = 0; i < Size; ++i) {
7687       if (Mask[i] < 0)
7688         continue;
7689
7690       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7691
7692       PermMask[i] =
7693           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7694     }
7695     return DAG.getVectorShuffle(
7696         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7697                             DL, VT, V1, V2),
7698         DAG.getUNDEF(VT), PermMask);
7699   }
7700
7701   return SDValue();
7702 }
7703
7704 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7705 ///
7706 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7707 /// support for floating point shuffles but not integer shuffles. These
7708 /// instructions will incur a domain crossing penalty on some chips though so
7709 /// it is better to avoid lowering through this for integer vectors where
7710 /// possible.
7711 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7712                                        const X86Subtarget *Subtarget,
7713                                        SelectionDAG &DAG) {
7714   SDLoc DL(Op);
7715   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7716   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7717   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7719   ArrayRef<int> Mask = SVOp->getMask();
7720   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7721
7722   if (isSingleInputShuffleMask(Mask)) {
7723     // Use low duplicate instructions for masks that match their pattern.
7724     if (Subtarget->hasSSE3())
7725       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7726         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7727
7728     // Straight shuffle of a single input vector. Simulate this by using the
7729     // single input as both of the "inputs" to this instruction..
7730     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7731
7732     if (Subtarget->hasAVX()) {
7733       // If we have AVX, we can use VPERMILPS which will allow folding a load
7734       // into the shuffle.
7735       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7736                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7737     }
7738
7739     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7740                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7741   }
7742   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7743   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7744
7745   // If we have a single input, insert that into V1 if we can do so cheaply.
7746   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7747     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7748             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7749       return Insertion;
7750     // Try inverting the insertion since for v2 masks it is easy to do and we
7751     // can't reliably sort the mask one way or the other.
7752     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7753                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7754     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7755             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7756       return Insertion;
7757   }
7758
7759   // Try to use one of the special instruction patterns to handle two common
7760   // blend patterns if a zero-blend above didn't work.
7761   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7762       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7763     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7764       // We can either use a special instruction to load over the low double or
7765       // to move just the low double.
7766       return DAG.getNode(
7767           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7768           DL, MVT::v2f64, V2,
7769           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7770
7771   if (Subtarget->hasSSE41())
7772     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7773                                                   Subtarget, DAG))
7774       return Blend;
7775
7776   // Use dedicated unpack instructions for masks that match their pattern.
7777   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7778     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7779   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7780     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7781
7782   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7783   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7784                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7785 }
7786
7787 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7788 ///
7789 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7790 /// the integer unit to minimize domain crossing penalties. However, for blends
7791 /// it falls back to the floating point shuffle operation with appropriate bit
7792 /// casting.
7793 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7794                                        const X86Subtarget *Subtarget,
7795                                        SelectionDAG &DAG) {
7796   SDLoc DL(Op);
7797   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7798   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7799   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7800   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7801   ArrayRef<int> Mask = SVOp->getMask();
7802   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7803
7804   if (isSingleInputShuffleMask(Mask)) {
7805     // Check for being able to broadcast a single element.
7806     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7807                                                           Mask, Subtarget, DAG))
7808       return Broadcast;
7809
7810     // Straight shuffle of a single input vector. For everything from SSE2
7811     // onward this has a single fast instruction with no scary immediates.
7812     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7813     V1 = DAG.getBitcast(MVT::v4i32, V1);
7814     int WidenedMask[4] = {
7815         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7816         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7817     return DAG.getBitcast(
7818         MVT::v2i64,
7819         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7820                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7821   }
7822   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7823   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7824   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7825   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7826
7827   // If we have a blend of two PACKUS operations an the blend aligns with the
7828   // low and half halves, we can just merge the PACKUS operations. This is
7829   // particularly important as it lets us merge shuffles that this routine itself
7830   // creates.
7831   auto GetPackNode = [](SDValue V) {
7832     while (V.getOpcode() == ISD::BITCAST)
7833       V = V.getOperand(0);
7834
7835     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7836   };
7837   if (SDValue V1Pack = GetPackNode(V1))
7838     if (SDValue V2Pack = GetPackNode(V2))
7839       return DAG.getBitcast(MVT::v2i64,
7840                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7841                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7842                                                      : V1Pack.getOperand(1),
7843                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7844                                                      : V2Pack.getOperand(1)));
7845
7846   // Try to use shift instructions.
7847   if (SDValue Shift =
7848           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7849     return Shift;
7850
7851   // When loading a scalar and then shuffling it into a vector we can often do
7852   // the insertion cheaply.
7853   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7854           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7855     return Insertion;
7856   // Try inverting the insertion since for v2 masks it is easy to do and we
7857   // can't reliably sort the mask one way or the other.
7858   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7859   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7860           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7861     return Insertion;
7862
7863   // We have different paths for blend lowering, but they all must use the
7864   // *exact* same predicate.
7865   bool IsBlendSupported = Subtarget->hasSSE41();
7866   if (IsBlendSupported)
7867     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7868                                                   Subtarget, DAG))
7869       return Blend;
7870
7871   // Use dedicated unpack instructions for masks that match their pattern.
7872   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7873     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7874   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7875     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7876
7877   // Try to use byte rotation instructions.
7878   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7879   if (Subtarget->hasSSSE3())
7880     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7881             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7882       return Rotate;
7883
7884   // If we have direct support for blends, we should lower by decomposing into
7885   // a permute. That will be faster than the domain cross.
7886   if (IsBlendSupported)
7887     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7888                                                       Mask, DAG);
7889
7890   // We implement this with SHUFPD which is pretty lame because it will likely
7891   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7892   // However, all the alternatives are still more cycles and newer chips don't
7893   // have this problem. It would be really nice if x86 had better shuffles here.
7894   V1 = DAG.getBitcast(MVT::v2f64, V1);
7895   V2 = DAG.getBitcast(MVT::v2f64, V2);
7896   return DAG.getBitcast(MVT::v2i64,
7897                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7898 }
7899
7900 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7901 ///
7902 /// This is used to disable more specialized lowerings when the shufps lowering
7903 /// will happen to be efficient.
7904 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7905   // This routine only handles 128-bit shufps.
7906   assert(Mask.size() == 4 && "Unsupported mask size!");
7907
7908   // To lower with a single SHUFPS we need to have the low half and high half
7909   // each requiring a single input.
7910   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7911     return false;
7912   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7913     return false;
7914
7915   return true;
7916 }
7917
7918 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7919 ///
7920 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7921 /// It makes no assumptions about whether this is the *best* lowering, it simply
7922 /// uses it.
7923 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7924                                             ArrayRef<int> Mask, SDValue V1,
7925                                             SDValue V2, SelectionDAG &DAG) {
7926   SDValue LowV = V1, HighV = V2;
7927   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7928
7929   int NumV2Elements =
7930       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7931
7932   if (NumV2Elements == 1) {
7933     int V2Index =
7934         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7935         Mask.begin();
7936
7937     // Compute the index adjacent to V2Index and in the same half by toggling
7938     // the low bit.
7939     int V2AdjIndex = V2Index ^ 1;
7940
7941     if (Mask[V2AdjIndex] == -1) {
7942       // Handles all the cases where we have a single V2 element and an undef.
7943       // This will only ever happen in the high lanes because we commute the
7944       // vector otherwise.
7945       if (V2Index < 2)
7946         std::swap(LowV, HighV);
7947       NewMask[V2Index] -= 4;
7948     } else {
7949       // Handle the case where the V2 element ends up adjacent to a V1 element.
7950       // To make this work, blend them together as the first step.
7951       int V1Index = V2AdjIndex;
7952       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7953       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7954                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7955
7956       // Now proceed to reconstruct the final blend as we have the necessary
7957       // high or low half formed.
7958       if (V2Index < 2) {
7959         LowV = V2;
7960         HighV = V1;
7961       } else {
7962         HighV = V2;
7963       }
7964       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7965       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7966     }
7967   } else if (NumV2Elements == 2) {
7968     if (Mask[0] < 4 && Mask[1] < 4) {
7969       // Handle the easy case where we have V1 in the low lanes and V2 in the
7970       // high lanes.
7971       NewMask[2] -= 4;
7972       NewMask[3] -= 4;
7973     } else if (Mask[2] < 4 && Mask[3] < 4) {
7974       // We also handle the reversed case because this utility may get called
7975       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7976       // arrange things in the right direction.
7977       NewMask[0] -= 4;
7978       NewMask[1] -= 4;
7979       HighV = V1;
7980       LowV = V2;
7981     } else {
7982       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7983       // trying to place elements directly, just blend them and set up the final
7984       // shuffle to place them.
7985
7986       // The first two blend mask elements are for V1, the second two are for
7987       // V2.
7988       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7989                           Mask[2] < 4 ? Mask[2] : Mask[3],
7990                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7991                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7992       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7993                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7994
7995       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7996       // a blend.
7997       LowV = HighV = V1;
7998       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7999       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8000       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8001       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8002     }
8003   }
8004   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8005                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8006 }
8007
8008 /// \brief Lower 4-lane 32-bit floating point shuffles.
8009 ///
8010 /// Uses instructions exclusively from the floating point unit to minimize
8011 /// domain crossing penalties, as these are sufficient to implement all v4f32
8012 /// shuffles.
8013 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8014                                        const X86Subtarget *Subtarget,
8015                                        SelectionDAG &DAG) {
8016   SDLoc DL(Op);
8017   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8018   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8019   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8020   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8021   ArrayRef<int> Mask = SVOp->getMask();
8022   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8023
8024   int NumV2Elements =
8025       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8026
8027   if (NumV2Elements == 0) {
8028     // Check for being able to broadcast a single element.
8029     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8030                                                           Mask, Subtarget, DAG))
8031       return Broadcast;
8032
8033     // Use even/odd duplicate instructions for masks that match their pattern.
8034     if (Subtarget->hasSSE3()) {
8035       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8036         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8037       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8038         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8039     }
8040
8041     if (Subtarget->hasAVX()) {
8042       // If we have AVX, we can use VPERMILPS which will allow folding a load
8043       // into the shuffle.
8044       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8045                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8046     }
8047
8048     // Otherwise, use a straight shuffle of a single input vector. We pass the
8049     // input vector to both operands to simulate this with a SHUFPS.
8050     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8051                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8052   }
8053
8054   // There are special ways we can lower some single-element blends. However, we
8055   // have custom ways we can lower more complex single-element blends below that
8056   // we defer to if both this and BLENDPS fail to match, so restrict this to
8057   // when the V2 input is targeting element 0 of the mask -- that is the fast
8058   // case here.
8059   if (NumV2Elements == 1 && Mask[0] >= 4)
8060     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8061                                                          Mask, Subtarget, DAG))
8062       return V;
8063
8064   if (Subtarget->hasSSE41()) {
8065     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8066                                                   Subtarget, DAG))
8067       return Blend;
8068
8069     // Use INSERTPS if we can complete the shuffle efficiently.
8070     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8071       return V;
8072
8073     if (!isSingleSHUFPSMask(Mask))
8074       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8075               DL, MVT::v4f32, V1, V2, Mask, DAG))
8076         return BlendPerm;
8077   }
8078
8079   // Use dedicated unpack instructions for masks that match their pattern.
8080   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8081     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8082   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8083     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8084   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8085     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8086   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8087     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8088
8089   // Otherwise fall back to a SHUFPS lowering strategy.
8090   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8091 }
8092
8093 /// \brief Lower 4-lane i32 vector shuffles.
8094 ///
8095 /// We try to handle these with integer-domain shuffles where we can, but for
8096 /// blends we use the floating point domain blend instructions.
8097 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8098                                        const X86Subtarget *Subtarget,
8099                                        SelectionDAG &DAG) {
8100   SDLoc DL(Op);
8101   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8102   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8103   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8104   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8105   ArrayRef<int> Mask = SVOp->getMask();
8106   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8107
8108   // Whenever we can lower this as a zext, that instruction is strictly faster
8109   // than any alternative. It also allows us to fold memory operands into the
8110   // shuffle in many cases.
8111   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8112                                                          Mask, Subtarget, DAG))
8113     return ZExt;
8114
8115   int NumV2Elements =
8116       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8117
8118   if (NumV2Elements == 0) {
8119     // Check for being able to broadcast a single element.
8120     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8121                                                           Mask, Subtarget, DAG))
8122       return Broadcast;
8123
8124     // Straight shuffle of a single input vector. For everything from SSE2
8125     // onward this has a single fast instruction with no scary immediates.
8126     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8127     // but we aren't actually going to use the UNPCK instruction because doing
8128     // so prevents folding a load into this instruction or making a copy.
8129     const int UnpackLoMask[] = {0, 0, 1, 1};
8130     const int UnpackHiMask[] = {2, 2, 3, 3};
8131     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8132       Mask = UnpackLoMask;
8133     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8134       Mask = UnpackHiMask;
8135
8136     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8137                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8138   }
8139
8140   // Try to use shift instructions.
8141   if (SDValue Shift =
8142           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8143     return Shift;
8144
8145   // There are special ways we can lower some single-element blends.
8146   if (NumV2Elements == 1)
8147     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8148                                                          Mask, Subtarget, DAG))
8149       return V;
8150
8151   // We have different paths for blend lowering, but they all must use the
8152   // *exact* same predicate.
8153   bool IsBlendSupported = Subtarget->hasSSE41();
8154   if (IsBlendSupported)
8155     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8156                                                   Subtarget, DAG))
8157       return Blend;
8158
8159   if (SDValue Masked =
8160           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8161     return Masked;
8162
8163   // Use dedicated unpack instructions for masks that match their pattern.
8164   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8165     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8166   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8167     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8168   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8169     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8170   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8171     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8172
8173   // Try to use byte rotation instructions.
8174   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8175   if (Subtarget->hasSSSE3())
8176     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8177             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8178       return Rotate;
8179
8180   // If we have direct support for blends, we should lower by decomposing into
8181   // a permute. That will be faster than the domain cross.
8182   if (IsBlendSupported)
8183     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8184                                                       Mask, DAG);
8185
8186   // Try to lower by permuting the inputs into an unpack instruction.
8187   if (SDValue Unpack =
8188           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8189     return Unpack;
8190
8191   // We implement this with SHUFPS because it can blend from two vectors.
8192   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8193   // up the inputs, bypassing domain shift penalties that we would encur if we
8194   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8195   // relevant.
8196   return DAG.getBitcast(
8197       MVT::v4i32,
8198       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8199                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8200 }
8201
8202 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8203 /// shuffle lowering, and the most complex part.
8204 ///
8205 /// The lowering strategy is to try to form pairs of input lanes which are
8206 /// targeted at the same half of the final vector, and then use a dword shuffle
8207 /// to place them onto the right half, and finally unpack the paired lanes into
8208 /// their final position.
8209 ///
8210 /// The exact breakdown of how to form these dword pairs and align them on the
8211 /// correct sides is really tricky. See the comments within the function for
8212 /// more of the details.
8213 ///
8214 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8215 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8216 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8217 /// vector, form the analogous 128-bit 8-element Mask.
8218 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8219     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8220     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8221   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8222   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8223
8224   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8225   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8226   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8227
8228   SmallVector<int, 4> LoInputs;
8229   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8230                [](int M) { return M >= 0; });
8231   std::sort(LoInputs.begin(), LoInputs.end());
8232   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8233   SmallVector<int, 4> HiInputs;
8234   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8235                [](int M) { return M >= 0; });
8236   std::sort(HiInputs.begin(), HiInputs.end());
8237   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8238   int NumLToL =
8239       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8240   int NumHToL = LoInputs.size() - NumLToL;
8241   int NumLToH =
8242       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8243   int NumHToH = HiInputs.size() - NumLToH;
8244   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8245   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8246   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8247   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8248
8249   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8250   // such inputs we can swap two of the dwords across the half mark and end up
8251   // with <=2 inputs to each half in each half. Once there, we can fall through
8252   // to the generic code below. For example:
8253   //
8254   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8255   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8256   //
8257   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8258   // and an existing 2-into-2 on the other half. In this case we may have to
8259   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8260   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8261   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8262   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8263   // half than the one we target for fixing) will be fixed when we re-enter this
8264   // path. We will also combine away any sequence of PSHUFD instructions that
8265   // result into a single instruction. Here is an example of the tricky case:
8266   //
8267   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8268   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8269   //
8270   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8271   //
8272   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8273   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8274   //
8275   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8276   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8277   //
8278   // The result is fine to be handled by the generic logic.
8279   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8280                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8281                           int AOffset, int BOffset) {
8282     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8283            "Must call this with A having 3 or 1 inputs from the A half.");
8284     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8285            "Must call this with B having 1 or 3 inputs from the B half.");
8286     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8287            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8288
8289     // Compute the index of dword with only one word among the three inputs in
8290     // a half by taking the sum of the half with three inputs and subtracting
8291     // the sum of the actual three inputs. The difference is the remaining
8292     // slot.
8293     int ADWord, BDWord;
8294     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8295     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8296     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8297     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8298     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8299     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8300     int TripleNonInputIdx =
8301         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8302     TripleDWord = TripleNonInputIdx / 2;
8303
8304     // We use xor with one to compute the adjacent DWord to whichever one the
8305     // OneInput is in.
8306     OneInputDWord = (OneInput / 2) ^ 1;
8307
8308     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8309     // and BToA inputs. If there is also such a problem with the BToB and AToB
8310     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8311     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8312     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8313     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8314       // Compute how many inputs will be flipped by swapping these DWords. We
8315       // need
8316       // to balance this to ensure we don't form a 3-1 shuffle in the other
8317       // half.
8318       int NumFlippedAToBInputs =
8319           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8320           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8321       int NumFlippedBToBInputs =
8322           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8323           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8324       if ((NumFlippedAToBInputs == 1 &&
8325            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8326           (NumFlippedBToBInputs == 1 &&
8327            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8328         // We choose whether to fix the A half or B half based on whether that
8329         // half has zero flipped inputs. At zero, we may not be able to fix it
8330         // with that half. We also bias towards fixing the B half because that
8331         // will more commonly be the high half, and we have to bias one way.
8332         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8333                                                        ArrayRef<int> Inputs) {
8334           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8335           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8336                                          PinnedIdx ^ 1) != Inputs.end();
8337           // Determine whether the free index is in the flipped dword or the
8338           // unflipped dword based on where the pinned index is. We use this bit
8339           // in an xor to conditionally select the adjacent dword.
8340           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8341           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8342                                              FixFreeIdx) != Inputs.end();
8343           if (IsFixIdxInput == IsFixFreeIdxInput)
8344             FixFreeIdx += 1;
8345           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8346                                         FixFreeIdx) != Inputs.end();
8347           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8348                  "We need to be changing the number of flipped inputs!");
8349           int PSHUFHalfMask[] = {0, 1, 2, 3};
8350           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8351           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8352                           MVT::v8i16, V,
8353                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8354
8355           for (int &M : Mask)
8356             if (M != -1 && M == FixIdx)
8357               M = FixFreeIdx;
8358             else if (M != -1 && M == FixFreeIdx)
8359               M = FixIdx;
8360         };
8361         if (NumFlippedBToBInputs != 0) {
8362           int BPinnedIdx =
8363               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8364           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8365         } else {
8366           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8367           int APinnedIdx =
8368               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8369           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8370         }
8371       }
8372     }
8373
8374     int PSHUFDMask[] = {0, 1, 2, 3};
8375     PSHUFDMask[ADWord] = BDWord;
8376     PSHUFDMask[BDWord] = ADWord;
8377     V = DAG.getBitcast(
8378         VT,
8379         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8380                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8381
8382     // Adjust the mask to match the new locations of A and B.
8383     for (int &M : Mask)
8384       if (M != -1 && M/2 == ADWord)
8385         M = 2 * BDWord + M % 2;
8386       else if (M != -1 && M/2 == BDWord)
8387         M = 2 * ADWord + M % 2;
8388
8389     // Recurse back into this routine to re-compute state now that this isn't
8390     // a 3 and 1 problem.
8391     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8392                                                      DAG);
8393   };
8394   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8395     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8396   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8397     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8398
8399   // At this point there are at most two inputs to the low and high halves from
8400   // each half. That means the inputs can always be grouped into dwords and
8401   // those dwords can then be moved to the correct half with a dword shuffle.
8402   // We use at most one low and one high word shuffle to collect these paired
8403   // inputs into dwords, and finally a dword shuffle to place them.
8404   int PSHUFLMask[4] = {-1, -1, -1, -1};
8405   int PSHUFHMask[4] = {-1, -1, -1, -1};
8406   int PSHUFDMask[4] = {-1, -1, -1, -1};
8407
8408   // First fix the masks for all the inputs that are staying in their
8409   // original halves. This will then dictate the targets of the cross-half
8410   // shuffles.
8411   auto fixInPlaceInputs =
8412       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8413                     MutableArrayRef<int> SourceHalfMask,
8414                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8415     if (InPlaceInputs.empty())
8416       return;
8417     if (InPlaceInputs.size() == 1) {
8418       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8419           InPlaceInputs[0] - HalfOffset;
8420       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8421       return;
8422     }
8423     if (IncomingInputs.empty()) {
8424       // Just fix all of the in place inputs.
8425       for (int Input : InPlaceInputs) {
8426         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8427         PSHUFDMask[Input / 2] = Input / 2;
8428       }
8429       return;
8430     }
8431
8432     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8433     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8434         InPlaceInputs[0] - HalfOffset;
8435     // Put the second input next to the first so that they are packed into
8436     // a dword. We find the adjacent index by toggling the low bit.
8437     int AdjIndex = InPlaceInputs[0] ^ 1;
8438     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8439     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8440     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8441   };
8442   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8443   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8444
8445   // Now gather the cross-half inputs and place them into a free dword of
8446   // their target half.
8447   // FIXME: This operation could almost certainly be simplified dramatically to
8448   // look more like the 3-1 fixing operation.
8449   auto moveInputsToRightHalf = [&PSHUFDMask](
8450       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8451       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8452       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8453       int DestOffset) {
8454     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8455       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8456     };
8457     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8458                                                int Word) {
8459       int LowWord = Word & ~1;
8460       int HighWord = Word | 1;
8461       return isWordClobbered(SourceHalfMask, LowWord) ||
8462              isWordClobbered(SourceHalfMask, HighWord);
8463     };
8464
8465     if (IncomingInputs.empty())
8466       return;
8467
8468     if (ExistingInputs.empty()) {
8469       // Map any dwords with inputs from them into the right half.
8470       for (int Input : IncomingInputs) {
8471         // If the source half mask maps over the inputs, turn those into
8472         // swaps and use the swapped lane.
8473         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8474           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8475             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8476                 Input - SourceOffset;
8477             // We have to swap the uses in our half mask in one sweep.
8478             for (int &M : HalfMask)
8479               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8480                 M = Input;
8481               else if (M == Input)
8482                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8483           } else {
8484             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8485                        Input - SourceOffset &&
8486                    "Previous placement doesn't match!");
8487           }
8488           // Note that this correctly re-maps both when we do a swap and when
8489           // we observe the other side of the swap above. We rely on that to
8490           // avoid swapping the members of the input list directly.
8491           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8492         }
8493
8494         // Map the input's dword into the correct half.
8495         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8496           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8497         else
8498           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8499                      Input / 2 &&
8500                  "Previous placement doesn't match!");
8501       }
8502
8503       // And just directly shift any other-half mask elements to be same-half
8504       // as we will have mirrored the dword containing the element into the
8505       // same position within that half.
8506       for (int &M : HalfMask)
8507         if (M >= SourceOffset && M < SourceOffset + 4) {
8508           M = M - SourceOffset + DestOffset;
8509           assert(M >= 0 && "This should never wrap below zero!");
8510         }
8511       return;
8512     }
8513
8514     // Ensure we have the input in a viable dword of its current half. This
8515     // is particularly tricky because the original position may be clobbered
8516     // by inputs being moved and *staying* in that half.
8517     if (IncomingInputs.size() == 1) {
8518       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8519         int InputFixed = std::find(std::begin(SourceHalfMask),
8520                                    std::end(SourceHalfMask), -1) -
8521                          std::begin(SourceHalfMask) + SourceOffset;
8522         SourceHalfMask[InputFixed - SourceOffset] =
8523             IncomingInputs[0] - SourceOffset;
8524         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8525                      InputFixed);
8526         IncomingInputs[0] = InputFixed;
8527       }
8528     } else if (IncomingInputs.size() == 2) {
8529       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8530           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8531         // We have two non-adjacent or clobbered inputs we need to extract from
8532         // the source half. To do this, we need to map them into some adjacent
8533         // dword slot in the source mask.
8534         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8535                               IncomingInputs[1] - SourceOffset};
8536
8537         // If there is a free slot in the source half mask adjacent to one of
8538         // the inputs, place the other input in it. We use (Index XOR 1) to
8539         // compute an adjacent index.
8540         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8541             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8542           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8543           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8544           InputsFixed[1] = InputsFixed[0] ^ 1;
8545         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8546                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8547           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8548           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8549           InputsFixed[0] = InputsFixed[1] ^ 1;
8550         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8551                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8552           // The two inputs are in the same DWord but it is clobbered and the
8553           // adjacent DWord isn't used at all. Move both inputs to the free
8554           // slot.
8555           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8556           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8557           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8558           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8559         } else {
8560           // The only way we hit this point is if there is no clobbering
8561           // (because there are no off-half inputs to this half) and there is no
8562           // free slot adjacent to one of the inputs. In this case, we have to
8563           // swap an input with a non-input.
8564           for (int i = 0; i < 4; ++i)
8565             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8566                    "We can't handle any clobbers here!");
8567           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8568                  "Cannot have adjacent inputs here!");
8569
8570           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8571           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8572
8573           // We also have to update the final source mask in this case because
8574           // it may need to undo the above swap.
8575           for (int &M : FinalSourceHalfMask)
8576             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8577               M = InputsFixed[1] + SourceOffset;
8578             else if (M == InputsFixed[1] + SourceOffset)
8579               M = (InputsFixed[0] ^ 1) + SourceOffset;
8580
8581           InputsFixed[1] = InputsFixed[0] ^ 1;
8582         }
8583
8584         // Point everything at the fixed inputs.
8585         for (int &M : HalfMask)
8586           if (M == IncomingInputs[0])
8587             M = InputsFixed[0] + SourceOffset;
8588           else if (M == IncomingInputs[1])
8589             M = InputsFixed[1] + SourceOffset;
8590
8591         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8592         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8593       }
8594     } else {
8595       llvm_unreachable("Unhandled input size!");
8596     }
8597
8598     // Now hoist the DWord down to the right half.
8599     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8600     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8601     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8602     for (int &M : HalfMask)
8603       for (int Input : IncomingInputs)
8604         if (M == Input)
8605           M = FreeDWord * 2 + Input % 2;
8606   };
8607   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8608                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8609   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8610                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8611
8612   // Now enact all the shuffles we've computed to move the inputs into their
8613   // target half.
8614   if (!isNoopShuffleMask(PSHUFLMask))
8615     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8616                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8617   if (!isNoopShuffleMask(PSHUFHMask))
8618     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8619                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8620   if (!isNoopShuffleMask(PSHUFDMask))
8621     V = DAG.getBitcast(
8622         VT,
8623         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8624                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8625
8626   // At this point, each half should contain all its inputs, and we can then
8627   // just shuffle them into their final position.
8628   assert(std::count_if(LoMask.begin(), LoMask.end(),
8629                        [](int M) { return M >= 4; }) == 0 &&
8630          "Failed to lift all the high half inputs to the low mask!");
8631   assert(std::count_if(HiMask.begin(), HiMask.end(),
8632                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8633          "Failed to lift all the low half inputs to the high mask!");
8634
8635   // Do a half shuffle for the low mask.
8636   if (!isNoopShuffleMask(LoMask))
8637     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8638                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8639
8640   // Do a half shuffle with the high mask after shifting its values down.
8641   for (int &M : HiMask)
8642     if (M >= 0)
8643       M -= 4;
8644   if (!isNoopShuffleMask(HiMask))
8645     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8646                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8647
8648   return V;
8649 }
8650
8651 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8652 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8653                                           SDValue V2, ArrayRef<int> Mask,
8654                                           SelectionDAG &DAG, bool &V1InUse,
8655                                           bool &V2InUse) {
8656   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8657   SDValue V1Mask[16];
8658   SDValue V2Mask[16];
8659   V1InUse = false;
8660   V2InUse = false;
8661
8662   int Size = Mask.size();
8663   int Scale = 16 / Size;
8664   for (int i = 0; i < 16; ++i) {
8665     if (Mask[i / Scale] == -1) {
8666       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8667     } else {
8668       const int ZeroMask = 0x80;
8669       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8670                                           : ZeroMask;
8671       int V2Idx = Mask[i / Scale] < Size
8672                       ? ZeroMask
8673                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8674       if (Zeroable[i / Scale])
8675         V1Idx = V2Idx = ZeroMask;
8676       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8677       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8678       V1InUse |= (ZeroMask != V1Idx);
8679       V2InUse |= (ZeroMask != V2Idx);
8680     }
8681   }
8682
8683   if (V1InUse)
8684     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8685                      DAG.getBitcast(MVT::v16i8, V1),
8686                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8687   if (V2InUse)
8688     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8689                      DAG.getBitcast(MVT::v16i8, V2),
8690                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8691
8692   // If we need shuffled inputs from both, blend the two.
8693   SDValue V;
8694   if (V1InUse && V2InUse)
8695     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8696   else
8697     V = V1InUse ? V1 : V2;
8698
8699   // Cast the result back to the correct type.
8700   return DAG.getBitcast(VT, V);
8701 }
8702
8703 /// \brief Generic lowering of 8-lane i16 shuffles.
8704 ///
8705 /// This handles both single-input shuffles and combined shuffle/blends with
8706 /// two inputs. The single input shuffles are immediately delegated to
8707 /// a dedicated lowering routine.
8708 ///
8709 /// The blends are lowered in one of three fundamental ways. If there are few
8710 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8711 /// of the input is significantly cheaper when lowered as an interleaving of
8712 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8713 /// halves of the inputs separately (making them have relatively few inputs)
8714 /// and then concatenate them.
8715 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8716                                        const X86Subtarget *Subtarget,
8717                                        SelectionDAG &DAG) {
8718   SDLoc DL(Op);
8719   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8720   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8721   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8722   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8723   ArrayRef<int> OrigMask = SVOp->getMask();
8724   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8725                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8726   MutableArrayRef<int> Mask(MaskStorage);
8727
8728   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8729
8730   // Whenever we can lower this as a zext, that instruction is strictly faster
8731   // than any alternative.
8732   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8733           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8734     return ZExt;
8735
8736   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8737   (void)isV1;
8738   auto isV2 = [](int M) { return M >= 8; };
8739
8740   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8741
8742   if (NumV2Inputs == 0) {
8743     // Check for being able to broadcast a single element.
8744     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8745                                                           Mask, Subtarget, DAG))
8746       return Broadcast;
8747
8748     // Try to use shift instructions.
8749     if (SDValue Shift =
8750             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8751       return Shift;
8752
8753     // Use dedicated unpack instructions for masks that match their pattern.
8754     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8755       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8756     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8757       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8758
8759     // Try to use byte rotation instructions.
8760     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8761                                                         Mask, Subtarget, DAG))
8762       return Rotate;
8763
8764     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8765                                                      Subtarget, DAG);
8766   }
8767
8768   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8769          "All single-input shuffles should be canonicalized to be V1-input "
8770          "shuffles.");
8771
8772   // Try to use shift instructions.
8773   if (SDValue Shift =
8774           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8775     return Shift;
8776
8777   // See if we can use SSE4A Extraction / Insertion.
8778   if (Subtarget->hasSSE4A())
8779     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8780       return V;
8781
8782   // There are special ways we can lower some single-element blends.
8783   if (NumV2Inputs == 1)
8784     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8785                                                          Mask, Subtarget, DAG))
8786       return V;
8787
8788   // We have different paths for blend lowering, but they all must use the
8789   // *exact* same predicate.
8790   bool IsBlendSupported = Subtarget->hasSSE41();
8791   if (IsBlendSupported)
8792     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8793                                                   Subtarget, DAG))
8794       return Blend;
8795
8796   if (SDValue Masked =
8797           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8798     return Masked;
8799
8800   // Use dedicated unpack instructions for masks that match their pattern.
8801   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8802     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8803   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8804     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8805
8806   // Try to use byte rotation instructions.
8807   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8808           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8809     return Rotate;
8810
8811   if (SDValue BitBlend =
8812           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8813     return BitBlend;
8814
8815   if (SDValue Unpack =
8816           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8817     return Unpack;
8818
8819   // If we can't directly blend but can use PSHUFB, that will be better as it
8820   // can both shuffle and set up the inefficient blend.
8821   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8822     bool V1InUse, V2InUse;
8823     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8824                                       V1InUse, V2InUse);
8825   }
8826
8827   // We can always bit-blend if we have to so the fallback strategy is to
8828   // decompose into single-input permutes and blends.
8829   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8830                                                       Mask, DAG);
8831 }
8832
8833 /// \brief Check whether a compaction lowering can be done by dropping even
8834 /// elements and compute how many times even elements must be dropped.
8835 ///
8836 /// This handles shuffles which take every Nth element where N is a power of
8837 /// two. Example shuffle masks:
8838 ///
8839 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8840 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8841 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8842 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8843 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8844 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8845 ///
8846 /// Any of these lanes can of course be undef.
8847 ///
8848 /// This routine only supports N <= 3.
8849 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8850 /// for larger N.
8851 ///
8852 /// \returns N above, or the number of times even elements must be dropped if
8853 /// there is such a number. Otherwise returns zero.
8854 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8855   // Figure out whether we're looping over two inputs or just one.
8856   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8857
8858   // The modulus for the shuffle vector entries is based on whether this is
8859   // a single input or not.
8860   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8861   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8862          "We should only be called with masks with a power-of-2 size!");
8863
8864   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8865
8866   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8867   // and 2^3 simultaneously. This is because we may have ambiguity with
8868   // partially undef inputs.
8869   bool ViableForN[3] = {true, true, true};
8870
8871   for (int i = 0, e = Mask.size(); i < e; ++i) {
8872     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8873     // want.
8874     if (Mask[i] == -1)
8875       continue;
8876
8877     bool IsAnyViable = false;
8878     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8879       if (ViableForN[j]) {
8880         uint64_t N = j + 1;
8881
8882         // The shuffle mask must be equal to (i * 2^N) % M.
8883         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8884           IsAnyViable = true;
8885         else
8886           ViableForN[j] = false;
8887       }
8888     // Early exit if we exhaust the possible powers of two.
8889     if (!IsAnyViable)
8890       break;
8891   }
8892
8893   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8894     if (ViableForN[j])
8895       return j + 1;
8896
8897   // Return 0 as there is no viable power of two.
8898   return 0;
8899 }
8900
8901 /// \brief Generic lowering of v16i8 shuffles.
8902 ///
8903 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8904 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8905 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8906 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8907 /// back together.
8908 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8909                                        const X86Subtarget *Subtarget,
8910                                        SelectionDAG &DAG) {
8911   SDLoc DL(Op);
8912   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8913   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8914   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8915   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8916   ArrayRef<int> Mask = SVOp->getMask();
8917   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8918
8919   // Try to use shift instructions.
8920   if (SDValue Shift =
8921           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8922     return Shift;
8923
8924   // Try to use byte rotation instructions.
8925   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8926           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8927     return Rotate;
8928
8929   // Try to use a zext lowering.
8930   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8931           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8932     return ZExt;
8933
8934   // See if we can use SSE4A Extraction / Insertion.
8935   if (Subtarget->hasSSE4A())
8936     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8937       return V;
8938
8939   int NumV2Elements =
8940       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8941
8942   // For single-input shuffles, there are some nicer lowering tricks we can use.
8943   if (NumV2Elements == 0) {
8944     // Check for being able to broadcast a single element.
8945     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8946                                                           Mask, Subtarget, DAG))
8947       return Broadcast;
8948
8949     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8950     // Notably, this handles splat and partial-splat shuffles more efficiently.
8951     // However, it only makes sense if the pre-duplication shuffle simplifies
8952     // things significantly. Currently, this means we need to be able to
8953     // express the pre-duplication shuffle as an i16 shuffle.
8954     //
8955     // FIXME: We should check for other patterns which can be widened into an
8956     // i16 shuffle as well.
8957     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8958       for (int i = 0; i < 16; i += 2)
8959         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8960           return false;
8961
8962       return true;
8963     };
8964     auto tryToWidenViaDuplication = [&]() -> SDValue {
8965       if (!canWidenViaDuplication(Mask))
8966         return SDValue();
8967       SmallVector<int, 4> LoInputs;
8968       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8969                    [](int M) { return M >= 0 && M < 8; });
8970       std::sort(LoInputs.begin(), LoInputs.end());
8971       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8972                      LoInputs.end());
8973       SmallVector<int, 4> HiInputs;
8974       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8975                    [](int M) { return M >= 8; });
8976       std::sort(HiInputs.begin(), HiInputs.end());
8977       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8978                      HiInputs.end());
8979
8980       bool TargetLo = LoInputs.size() >= HiInputs.size();
8981       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8982       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8983
8984       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8985       SmallDenseMap<int, int, 8> LaneMap;
8986       for (int I : InPlaceInputs) {
8987         PreDupI16Shuffle[I/2] = I/2;
8988         LaneMap[I] = I;
8989       }
8990       int j = TargetLo ? 0 : 4, je = j + 4;
8991       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8992         // Check if j is already a shuffle of this input. This happens when
8993         // there are two adjacent bytes after we move the low one.
8994         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8995           // If we haven't yet mapped the input, search for a slot into which
8996           // we can map it.
8997           while (j < je && PreDupI16Shuffle[j] != -1)
8998             ++j;
8999
9000           if (j == je)
9001             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9002             return SDValue();
9003
9004           // Map this input with the i16 shuffle.
9005           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9006         }
9007
9008         // Update the lane map based on the mapping we ended up with.
9009         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9010       }
9011       V1 = DAG.getBitcast(
9012           MVT::v16i8,
9013           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9014                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9015
9016       // Unpack the bytes to form the i16s that will be shuffled into place.
9017       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9018                        MVT::v16i8, V1, V1);
9019
9020       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9021       for (int i = 0; i < 16; ++i)
9022         if (Mask[i] != -1) {
9023           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9024           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9025           if (PostDupI16Shuffle[i / 2] == -1)
9026             PostDupI16Shuffle[i / 2] = MappedMask;
9027           else
9028             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9029                    "Conflicting entrties in the original shuffle!");
9030         }
9031       return DAG.getBitcast(
9032           MVT::v16i8,
9033           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9034                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9035     };
9036     if (SDValue V = tryToWidenViaDuplication())
9037       return V;
9038   }
9039
9040   // Use dedicated unpack instructions for masks that match their pattern.
9041   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9042                                          0, 16, 1, 17, 2, 18, 3, 19,
9043                                          // High half.
9044                                          4, 20, 5, 21, 6, 22, 7, 23}))
9045     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9046   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9047                                          8, 24, 9, 25, 10, 26, 11, 27,
9048                                          // High half.
9049                                          12, 28, 13, 29, 14, 30, 15, 31}))
9050     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9051
9052   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9053   // with PSHUFB. It is important to do this before we attempt to generate any
9054   // blends but after all of the single-input lowerings. If the single input
9055   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9056   // want to preserve that and we can DAG combine any longer sequences into
9057   // a PSHUFB in the end. But once we start blending from multiple inputs,
9058   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9059   // and there are *very* few patterns that would actually be faster than the
9060   // PSHUFB approach because of its ability to zero lanes.
9061   //
9062   // FIXME: The only exceptions to the above are blends which are exact
9063   // interleavings with direct instructions supporting them. We currently don't
9064   // handle those well here.
9065   if (Subtarget->hasSSSE3()) {
9066     bool V1InUse = false;
9067     bool V2InUse = false;
9068
9069     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9070                                                 DAG, V1InUse, V2InUse);
9071
9072     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9073     // do so. This avoids using them to handle blends-with-zero which is
9074     // important as a single pshufb is significantly faster for that.
9075     if (V1InUse && V2InUse) {
9076       if (Subtarget->hasSSE41())
9077         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9078                                                       Mask, Subtarget, DAG))
9079           return Blend;
9080
9081       // We can use an unpack to do the blending rather than an or in some
9082       // cases. Even though the or may be (very minorly) more efficient, we
9083       // preference this lowering because there are common cases where part of
9084       // the complexity of the shuffles goes away when we do the final blend as
9085       // an unpack.
9086       // FIXME: It might be worth trying to detect if the unpack-feeding
9087       // shuffles will both be pshufb, in which case we shouldn't bother with
9088       // this.
9089       if (SDValue Unpack =
9090               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9091         return Unpack;
9092     }
9093
9094     return PSHUFB;
9095   }
9096
9097   // There are special ways we can lower some single-element blends.
9098   if (NumV2Elements == 1)
9099     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9100                                                          Mask, Subtarget, DAG))
9101       return V;
9102
9103   if (SDValue BitBlend =
9104           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9105     return BitBlend;
9106
9107   // Check whether a compaction lowering can be done. This handles shuffles
9108   // which take every Nth element for some even N. See the helper function for
9109   // details.
9110   //
9111   // We special case these as they can be particularly efficiently handled with
9112   // the PACKUSB instruction on x86 and they show up in common patterns of
9113   // rearranging bytes to truncate wide elements.
9114   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9115     // NumEvenDrops is the power of two stride of the elements. Another way of
9116     // thinking about it is that we need to drop the even elements this many
9117     // times to get the original input.
9118     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9119
9120     // First we need to zero all the dropped bytes.
9121     assert(NumEvenDrops <= 3 &&
9122            "No support for dropping even elements more than 3 times.");
9123     // We use the mask type to pick which bytes are preserved based on how many
9124     // elements are dropped.
9125     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9126     SDValue ByteClearMask = DAG.getBitcast(
9127         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9128     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9129     if (!IsSingleInput)
9130       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9131
9132     // Now pack things back together.
9133     V1 = DAG.getBitcast(MVT::v8i16, V1);
9134     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9135     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9136     for (int i = 1; i < NumEvenDrops; ++i) {
9137       Result = DAG.getBitcast(MVT::v8i16, Result);
9138       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9139     }
9140
9141     return Result;
9142   }
9143
9144   // Handle multi-input cases by blending single-input shuffles.
9145   if (NumV2Elements > 0)
9146     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9147                                                       Mask, DAG);
9148
9149   // The fallback path for single-input shuffles widens this into two v8i16
9150   // vectors with unpacks, shuffles those, and then pulls them back together
9151   // with a pack.
9152   SDValue V = V1;
9153
9154   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9155   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9156   for (int i = 0; i < 16; ++i)
9157     if (Mask[i] >= 0)
9158       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9159
9160   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9161
9162   SDValue VLoHalf, VHiHalf;
9163   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9164   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9165   // i16s.
9166   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9167                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9168       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9169                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9170     // Use a mask to drop the high bytes.
9171     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9172     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9173                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9174
9175     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9176     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9177
9178     // Squash the masks to point directly into VLoHalf.
9179     for (int &M : LoBlendMask)
9180       if (M >= 0)
9181         M /= 2;
9182     for (int &M : HiBlendMask)
9183       if (M >= 0)
9184         M /= 2;
9185   } else {
9186     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9187     // VHiHalf so that we can blend them as i16s.
9188     VLoHalf = DAG.getBitcast(
9189         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9190     VHiHalf = DAG.getBitcast(
9191         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9192   }
9193
9194   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9195   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9196
9197   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9198 }
9199
9200 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9201 ///
9202 /// This routine breaks down the specific type of 128-bit shuffle and
9203 /// dispatches to the lowering routines accordingly.
9204 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9205                                         MVT VT, const X86Subtarget *Subtarget,
9206                                         SelectionDAG &DAG) {
9207   switch (VT.SimpleTy) {
9208   case MVT::v2i64:
9209     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9210   case MVT::v2f64:
9211     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9212   case MVT::v4i32:
9213     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9214   case MVT::v4f32:
9215     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9216   case MVT::v8i16:
9217     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9218   case MVT::v16i8:
9219     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9220
9221   default:
9222     llvm_unreachable("Unimplemented!");
9223   }
9224 }
9225
9226 /// \brief Helper function to test whether a shuffle mask could be
9227 /// simplified by widening the elements being shuffled.
9228 ///
9229 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9230 /// leaves it in an unspecified state.
9231 ///
9232 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9233 /// shuffle masks. The latter have the special property of a '-2' representing
9234 /// a zero-ed lane of a vector.
9235 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9236                                     SmallVectorImpl<int> &WidenedMask) {
9237   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9238     // If both elements are undef, its trivial.
9239     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9240       WidenedMask.push_back(SM_SentinelUndef);
9241       continue;
9242     }
9243
9244     // Check for an undef mask and a mask value properly aligned to fit with
9245     // a pair of values. If we find such a case, use the non-undef mask's value.
9246     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9247       WidenedMask.push_back(Mask[i + 1] / 2);
9248       continue;
9249     }
9250     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9251       WidenedMask.push_back(Mask[i] / 2);
9252       continue;
9253     }
9254
9255     // When zeroing, we need to spread the zeroing across both lanes to widen.
9256     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9257       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9258           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9259         WidenedMask.push_back(SM_SentinelZero);
9260         continue;
9261       }
9262       return false;
9263     }
9264
9265     // Finally check if the two mask values are adjacent and aligned with
9266     // a pair.
9267     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9268       WidenedMask.push_back(Mask[i] / 2);
9269       continue;
9270     }
9271
9272     // Otherwise we can't safely widen the elements used in this shuffle.
9273     return false;
9274   }
9275   assert(WidenedMask.size() == Mask.size() / 2 &&
9276          "Incorrect size of mask after widening the elements!");
9277
9278   return true;
9279 }
9280
9281 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9282 ///
9283 /// This routine just extracts two subvectors, shuffles them independently, and
9284 /// then concatenates them back together. This should work effectively with all
9285 /// AVX vector shuffle types.
9286 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9287                                           SDValue V2, ArrayRef<int> Mask,
9288                                           SelectionDAG &DAG) {
9289   assert(VT.getSizeInBits() >= 256 &&
9290          "Only for 256-bit or wider vector shuffles!");
9291   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9292   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9293
9294   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9295   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9296
9297   int NumElements = VT.getVectorNumElements();
9298   int SplitNumElements = NumElements / 2;
9299   MVT ScalarVT = VT.getScalarType();
9300   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9301
9302   // Rather than splitting build-vectors, just build two narrower build
9303   // vectors. This helps shuffling with splats and zeros.
9304   auto SplitVector = [&](SDValue V) {
9305     while (V.getOpcode() == ISD::BITCAST)
9306       V = V->getOperand(0);
9307
9308     MVT OrigVT = V.getSimpleValueType();
9309     int OrigNumElements = OrigVT.getVectorNumElements();
9310     int OrigSplitNumElements = OrigNumElements / 2;
9311     MVT OrigScalarVT = OrigVT.getScalarType();
9312     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9313
9314     SDValue LoV, HiV;
9315
9316     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9317     if (!BV) {
9318       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9319                         DAG.getIntPtrConstant(0, DL));
9320       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9321                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9322     } else {
9323
9324       SmallVector<SDValue, 16> LoOps, HiOps;
9325       for (int i = 0; i < OrigSplitNumElements; ++i) {
9326         LoOps.push_back(BV->getOperand(i));
9327         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9328       }
9329       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9330       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9331     }
9332     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9333                           DAG.getBitcast(SplitVT, HiV));
9334   };
9335
9336   SDValue LoV1, HiV1, LoV2, HiV2;
9337   std::tie(LoV1, HiV1) = SplitVector(V1);
9338   std::tie(LoV2, HiV2) = SplitVector(V2);
9339
9340   // Now create two 4-way blends of these half-width vectors.
9341   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9342     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9343     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9344     for (int i = 0; i < SplitNumElements; ++i) {
9345       int M = HalfMask[i];
9346       if (M >= NumElements) {
9347         if (M >= NumElements + SplitNumElements)
9348           UseHiV2 = true;
9349         else
9350           UseLoV2 = true;
9351         V2BlendMask.push_back(M - NumElements);
9352         V1BlendMask.push_back(-1);
9353         BlendMask.push_back(SplitNumElements + i);
9354       } else if (M >= 0) {
9355         if (M >= SplitNumElements)
9356           UseHiV1 = true;
9357         else
9358           UseLoV1 = true;
9359         V2BlendMask.push_back(-1);
9360         V1BlendMask.push_back(M);
9361         BlendMask.push_back(i);
9362       } else {
9363         V2BlendMask.push_back(-1);
9364         V1BlendMask.push_back(-1);
9365         BlendMask.push_back(-1);
9366       }
9367     }
9368
9369     // Because the lowering happens after all combining takes place, we need to
9370     // manually combine these blend masks as much as possible so that we create
9371     // a minimal number of high-level vector shuffle nodes.
9372
9373     // First try just blending the halves of V1 or V2.
9374     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9375       return DAG.getUNDEF(SplitVT);
9376     if (!UseLoV2 && !UseHiV2)
9377       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9378     if (!UseLoV1 && !UseHiV1)
9379       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9380
9381     SDValue V1Blend, V2Blend;
9382     if (UseLoV1 && UseHiV1) {
9383       V1Blend =
9384         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9385     } else {
9386       // We only use half of V1 so map the usage down into the final blend mask.
9387       V1Blend = UseLoV1 ? LoV1 : HiV1;
9388       for (int i = 0; i < SplitNumElements; ++i)
9389         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9390           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9391     }
9392     if (UseLoV2 && UseHiV2) {
9393       V2Blend =
9394         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9395     } else {
9396       // We only use half of V2 so map the usage down into the final blend mask.
9397       V2Blend = UseLoV2 ? LoV2 : HiV2;
9398       for (int i = 0; i < SplitNumElements; ++i)
9399         if (BlendMask[i] >= SplitNumElements)
9400           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9401     }
9402     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9403   };
9404   SDValue Lo = HalfBlend(LoMask);
9405   SDValue Hi = HalfBlend(HiMask);
9406   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9407 }
9408
9409 /// \brief Either split a vector in halves or decompose the shuffles and the
9410 /// blend.
9411 ///
9412 /// This is provided as a good fallback for many lowerings of non-single-input
9413 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9414 /// between splitting the shuffle into 128-bit components and stitching those
9415 /// back together vs. extracting the single-input shuffles and blending those
9416 /// results.
9417 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9418                                                 SDValue V2, ArrayRef<int> Mask,
9419                                                 SelectionDAG &DAG) {
9420   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9421                                             "lower single-input shuffles as it "
9422                                             "could then recurse on itself.");
9423   int Size = Mask.size();
9424
9425   // If this can be modeled as a broadcast of two elements followed by a blend,
9426   // prefer that lowering. This is especially important because broadcasts can
9427   // often fold with memory operands.
9428   auto DoBothBroadcast = [&] {
9429     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9430     for (int M : Mask)
9431       if (M >= Size) {
9432         if (V2BroadcastIdx == -1)
9433           V2BroadcastIdx = M - Size;
9434         else if (M - Size != V2BroadcastIdx)
9435           return false;
9436       } else if (M >= 0) {
9437         if (V1BroadcastIdx == -1)
9438           V1BroadcastIdx = M;
9439         else if (M != V1BroadcastIdx)
9440           return false;
9441       }
9442     return true;
9443   };
9444   if (DoBothBroadcast())
9445     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9446                                                       DAG);
9447
9448   // If the inputs all stem from a single 128-bit lane of each input, then we
9449   // split them rather than blending because the split will decompose to
9450   // unusually few instructions.
9451   int LaneCount = VT.getSizeInBits() / 128;
9452   int LaneSize = Size / LaneCount;
9453   SmallBitVector LaneInputs[2];
9454   LaneInputs[0].resize(LaneCount, false);
9455   LaneInputs[1].resize(LaneCount, false);
9456   for (int i = 0; i < Size; ++i)
9457     if (Mask[i] >= 0)
9458       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9459   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9460     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9461
9462   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9463   // that the decomposed single-input shuffles don't end up here.
9464   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9465 }
9466
9467 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9468 /// a permutation and blend of those lanes.
9469 ///
9470 /// This essentially blends the out-of-lane inputs to each lane into the lane
9471 /// from a permuted copy of the vector. This lowering strategy results in four
9472 /// instructions in the worst case for a single-input cross lane shuffle which
9473 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9474 /// of. Special cases for each particular shuffle pattern should be handled
9475 /// prior to trying this lowering.
9476 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9477                                                        SDValue V1, SDValue V2,
9478                                                        ArrayRef<int> Mask,
9479                                                        SelectionDAG &DAG) {
9480   // FIXME: This should probably be generalized for 512-bit vectors as well.
9481   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9482   int LaneSize = Mask.size() / 2;
9483
9484   // If there are only inputs from one 128-bit lane, splitting will in fact be
9485   // less expensive. The flags track whether the given lane contains an element
9486   // that crosses to another lane.
9487   bool LaneCrossing[2] = {false, false};
9488   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9489     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9490       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9491   if (!LaneCrossing[0] || !LaneCrossing[1])
9492     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9493
9494   if (isSingleInputShuffleMask(Mask)) {
9495     SmallVector<int, 32> FlippedBlendMask;
9496     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9497       FlippedBlendMask.push_back(
9498           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9499                                   ? Mask[i]
9500                                   : Mask[i] % LaneSize +
9501                                         (i / LaneSize) * LaneSize + Size));
9502
9503     // Flip the vector, and blend the results which should now be in-lane. The
9504     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9505     // 5 for the high source. The value 3 selects the high half of source 2 and
9506     // the value 2 selects the low half of source 2. We only use source 2 to
9507     // allow folding it into a memory operand.
9508     unsigned PERMMask = 3 | 2 << 4;
9509     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9510                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9511     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9512   }
9513
9514   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9515   // will be handled by the above logic and a blend of the results, much like
9516   // other patterns in AVX.
9517   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9518 }
9519
9520 /// \brief Handle lowering 2-lane 128-bit shuffles.
9521 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9522                                         SDValue V2, ArrayRef<int> Mask,
9523                                         const X86Subtarget *Subtarget,
9524                                         SelectionDAG &DAG) {
9525   // TODO: If minimizing size and one of the inputs is a zero vector and the
9526   // the zero vector has only one use, we could use a VPERM2X128 to save the
9527   // instruction bytes needed to explicitly generate the zero vector.
9528
9529   // Blends are faster and handle all the non-lane-crossing cases.
9530   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9531                                                 Subtarget, DAG))
9532     return Blend;
9533
9534   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9535   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9536
9537   // If either input operand is a zero vector, use VPERM2X128 because its mask
9538   // allows us to replace the zero input with an implicit zero.
9539   if (!IsV1Zero && !IsV2Zero) {
9540     // Check for patterns which can be matched with a single insert of a 128-bit
9541     // subvector.
9542     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9543     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9544       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9545                                    VT.getVectorNumElements() / 2);
9546       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9547                                 DAG.getIntPtrConstant(0, DL));
9548       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9549                                 OnlyUsesV1 ? V1 : V2,
9550                                 DAG.getIntPtrConstant(0, DL));
9551       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9552     }
9553   }
9554
9555   // Otherwise form a 128-bit permutation. After accounting for undefs,
9556   // convert the 64-bit shuffle mask selection values into 128-bit
9557   // selection bits by dividing the indexes by 2 and shifting into positions
9558   // defined by a vperm2*128 instruction's immediate control byte.
9559
9560   // The immediate permute control byte looks like this:
9561   //    [1:0] - select 128 bits from sources for low half of destination
9562   //    [2]   - ignore
9563   //    [3]   - zero low half of destination
9564   //    [5:4] - select 128 bits from sources for high half of destination
9565   //    [6]   - ignore
9566   //    [7]   - zero high half of destination
9567
9568   int MaskLO = Mask[0];
9569   if (MaskLO == SM_SentinelUndef)
9570     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9571
9572   int MaskHI = Mask[2];
9573   if (MaskHI == SM_SentinelUndef)
9574     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9575
9576   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9577
9578   // If either input is a zero vector, replace it with an undef input.
9579   // Shuffle mask values <  4 are selecting elements of V1.
9580   // Shuffle mask values >= 4 are selecting elements of V2.
9581   // Adjust each half of the permute mask by clearing the half that was
9582   // selecting the zero vector and setting the zero mask bit.
9583   if (IsV1Zero) {
9584     V1 = DAG.getUNDEF(VT);
9585     if (MaskLO < 4)
9586       PermMask = (PermMask & 0xf0) | 0x08;
9587     if (MaskHI < 4)
9588       PermMask = (PermMask & 0x0f) | 0x80;
9589   }
9590   if (IsV2Zero) {
9591     V2 = DAG.getUNDEF(VT);
9592     if (MaskLO >= 4)
9593       PermMask = (PermMask & 0xf0) | 0x08;
9594     if (MaskHI >= 4)
9595       PermMask = (PermMask & 0x0f) | 0x80;
9596   }
9597
9598   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9599                      DAG.getConstant(PermMask, DL, MVT::i8));
9600 }
9601
9602 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9603 /// shuffling each lane.
9604 ///
9605 /// This will only succeed when the result of fixing the 128-bit lanes results
9606 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9607 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9608 /// the lane crosses early and then use simpler shuffles within each lane.
9609 ///
9610 /// FIXME: It might be worthwhile at some point to support this without
9611 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9612 /// in x86 only floating point has interesting non-repeating shuffles, and even
9613 /// those are still *marginally* more expensive.
9614 static SDValue lowerVectorShuffleByMerging128BitLanes(
9615     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9616     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9617   assert(!isSingleInputShuffleMask(Mask) &&
9618          "This is only useful with multiple inputs.");
9619
9620   int Size = Mask.size();
9621   int LaneSize = 128 / VT.getScalarSizeInBits();
9622   int NumLanes = Size / LaneSize;
9623   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9624
9625   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9626   // check whether the in-128-bit lane shuffles share a repeating pattern.
9627   SmallVector<int, 4> Lanes;
9628   Lanes.resize(NumLanes, -1);
9629   SmallVector<int, 4> InLaneMask;
9630   InLaneMask.resize(LaneSize, -1);
9631   for (int i = 0; i < Size; ++i) {
9632     if (Mask[i] < 0)
9633       continue;
9634
9635     int j = i / LaneSize;
9636
9637     if (Lanes[j] < 0) {
9638       // First entry we've seen for this lane.
9639       Lanes[j] = Mask[i] / LaneSize;
9640     } else if (Lanes[j] != Mask[i] / LaneSize) {
9641       // This doesn't match the lane selected previously!
9642       return SDValue();
9643     }
9644
9645     // Check that within each lane we have a consistent shuffle mask.
9646     int k = i % LaneSize;
9647     if (InLaneMask[k] < 0) {
9648       InLaneMask[k] = Mask[i] % LaneSize;
9649     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9650       // This doesn't fit a repeating in-lane mask.
9651       return SDValue();
9652     }
9653   }
9654
9655   // First shuffle the lanes into place.
9656   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9657                                 VT.getSizeInBits() / 64);
9658   SmallVector<int, 8> LaneMask;
9659   LaneMask.resize(NumLanes * 2, -1);
9660   for (int i = 0; i < NumLanes; ++i)
9661     if (Lanes[i] >= 0) {
9662       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9663       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9664     }
9665
9666   V1 = DAG.getBitcast(LaneVT, V1);
9667   V2 = DAG.getBitcast(LaneVT, V2);
9668   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9669
9670   // Cast it back to the type we actually want.
9671   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9672
9673   // Now do a simple shuffle that isn't lane crossing.
9674   SmallVector<int, 8> NewMask;
9675   NewMask.resize(Size, -1);
9676   for (int i = 0; i < Size; ++i)
9677     if (Mask[i] >= 0)
9678       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9679   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9680          "Must not introduce lane crosses at this point!");
9681
9682   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9683 }
9684
9685 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9686 /// given mask.
9687 ///
9688 /// This returns true if the elements from a particular input are already in the
9689 /// slot required by the given mask and require no permutation.
9690 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9691   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9692   int Size = Mask.size();
9693   for (int i = 0; i < Size; ++i)
9694     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9695       return false;
9696
9697   return true;
9698 }
9699
9700 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9701                                             ArrayRef<int> Mask, SDValue V1,
9702                                             SDValue V2, SelectionDAG &DAG) {
9703
9704   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9705   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9706   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9707   int NumElts = VT.getVectorNumElements();
9708   bool ShufpdMask = true;
9709   bool CommutableMask = true;
9710   unsigned Immediate = 0;
9711   for (int i = 0; i < NumElts; ++i) {
9712     if (Mask[i] < 0)
9713       continue;
9714     int Val = (i & 6) + NumElts * (i & 1);
9715     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9716     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9717       ShufpdMask = false;
9718     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9719       CommutableMask = false;
9720     Immediate |= (Mask[i] % 2) << i;
9721   }
9722   if (ShufpdMask)
9723     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9724                        DAG.getConstant(Immediate, DL, MVT::i8));
9725   if (CommutableMask)
9726     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9727                        DAG.getConstant(Immediate, DL, MVT::i8));
9728   return SDValue();
9729 }
9730
9731 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9732 ///
9733 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9734 /// isn't available.
9735 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9736                                        const X86Subtarget *Subtarget,
9737                                        SelectionDAG &DAG) {
9738   SDLoc DL(Op);
9739   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9740   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9741   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9742   ArrayRef<int> Mask = SVOp->getMask();
9743   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9744
9745   SmallVector<int, 4> WidenedMask;
9746   if (canWidenShuffleElements(Mask, WidenedMask))
9747     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9748                                     DAG);
9749
9750   if (isSingleInputShuffleMask(Mask)) {
9751     // Check for being able to broadcast a single element.
9752     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9753                                                           Mask, Subtarget, DAG))
9754       return Broadcast;
9755
9756     // Use low duplicate instructions for masks that match their pattern.
9757     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9758       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9759
9760     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9761       // Non-half-crossing single input shuffles can be lowerid with an
9762       // interleaved permutation.
9763       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9764                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9765       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9766                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9767     }
9768
9769     // With AVX2 we have direct support for this permutation.
9770     if (Subtarget->hasAVX2())
9771       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9772                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9773
9774     // Otherwise, fall back.
9775     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9776                                                    DAG);
9777   }
9778
9779   // X86 has dedicated unpack instructions that can handle specific blend
9780   // operations: UNPCKH and UNPCKL.
9781   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9782     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9783   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9784     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9785   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9786     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9787   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9788     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9789
9790   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9791                                                 Subtarget, DAG))
9792     return Blend;
9793
9794   // Check if the blend happens to exactly fit that of SHUFPD.
9795   if (SDValue Op =
9796       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9797     return Op;
9798
9799   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9800   // shuffle. However, if we have AVX2 and either inputs are already in place,
9801   // we will be able to shuffle even across lanes the other input in a single
9802   // instruction so skip this pattern.
9803   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9804                                  isShuffleMaskInputInPlace(1, Mask))))
9805     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9806             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9807       return Result;
9808
9809   // If we have AVX2 then we always want to lower with a blend because an v4 we
9810   // can fully permute the elements.
9811   if (Subtarget->hasAVX2())
9812     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9813                                                       Mask, DAG);
9814
9815   // Otherwise fall back on generic lowering.
9816   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9817 }
9818
9819 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9820 ///
9821 /// This routine is only called when we have AVX2 and thus a reasonable
9822 /// instruction set for v4i64 shuffling..
9823 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9824                                        const X86Subtarget *Subtarget,
9825                                        SelectionDAG &DAG) {
9826   SDLoc DL(Op);
9827   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9828   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9829   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9830   ArrayRef<int> Mask = SVOp->getMask();
9831   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9832   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9833
9834   SmallVector<int, 4> WidenedMask;
9835   if (canWidenShuffleElements(Mask, WidenedMask))
9836     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9837                                     DAG);
9838
9839   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9840                                                 Subtarget, DAG))
9841     return Blend;
9842
9843   // Check for being able to broadcast a single element.
9844   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9845                                                         Mask, Subtarget, DAG))
9846     return Broadcast;
9847
9848   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9849   // use lower latency instructions that will operate on both 128-bit lanes.
9850   SmallVector<int, 2> RepeatedMask;
9851   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9852     if (isSingleInputShuffleMask(Mask)) {
9853       int PSHUFDMask[] = {-1, -1, -1, -1};
9854       for (int i = 0; i < 2; ++i)
9855         if (RepeatedMask[i] >= 0) {
9856           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9857           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9858         }
9859       return DAG.getBitcast(
9860           MVT::v4i64,
9861           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9862                       DAG.getBitcast(MVT::v8i32, V1),
9863                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9864     }
9865   }
9866
9867   // AVX2 provides a direct instruction for permuting a single input across
9868   // lanes.
9869   if (isSingleInputShuffleMask(Mask))
9870     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9871                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9872
9873   // Try to use shift instructions.
9874   if (SDValue Shift =
9875           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9876     return Shift;
9877
9878   // Use dedicated unpack instructions for masks that match their pattern.
9879   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9880     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9881   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9882     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9883   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9884     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9885   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9886     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9887
9888   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9889   // shuffle. However, if we have AVX2 and either inputs are already in place,
9890   // we will be able to shuffle even across lanes the other input in a single
9891   // instruction so skip this pattern.
9892   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9893                                  isShuffleMaskInputInPlace(1, Mask))))
9894     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9895             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9896       return Result;
9897
9898   // Otherwise fall back on generic blend lowering.
9899   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9900                                                     Mask, DAG);
9901 }
9902
9903 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9904 ///
9905 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9906 /// isn't available.
9907 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9908                                        const X86Subtarget *Subtarget,
9909                                        SelectionDAG &DAG) {
9910   SDLoc DL(Op);
9911   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9912   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9913   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9914   ArrayRef<int> Mask = SVOp->getMask();
9915   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9916
9917   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9918                                                 Subtarget, DAG))
9919     return Blend;
9920
9921   // Check for being able to broadcast a single element.
9922   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9923                                                         Mask, Subtarget, DAG))
9924     return Broadcast;
9925
9926   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9927   // options to efficiently lower the shuffle.
9928   SmallVector<int, 4> RepeatedMask;
9929   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9930     assert(RepeatedMask.size() == 4 &&
9931            "Repeated masks must be half the mask width!");
9932
9933     // Use even/odd duplicate instructions for masks that match their pattern.
9934     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9935       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9936     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9937       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9938
9939     if (isSingleInputShuffleMask(Mask))
9940       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9941                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9942
9943     // Use dedicated unpack instructions for masks that match their pattern.
9944     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9945       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9946     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9947       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9948     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9949       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9950     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9951       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9952
9953     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9954     // have already handled any direct blends. We also need to squash the
9955     // repeated mask into a simulated v4f32 mask.
9956     for (int i = 0; i < 4; ++i)
9957       if (RepeatedMask[i] >= 8)
9958         RepeatedMask[i] -= 4;
9959     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9960   }
9961
9962   // If we have a single input shuffle with different shuffle patterns in the
9963   // two 128-bit lanes use the variable mask to VPERMILPS.
9964   if (isSingleInputShuffleMask(Mask)) {
9965     SDValue VPermMask[8];
9966     for (int i = 0; i < 8; ++i)
9967       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9968                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9969     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9970       return DAG.getNode(
9971           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9972           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9973
9974     if (Subtarget->hasAVX2())
9975       return DAG.getNode(
9976           X86ISD::VPERMV, DL, MVT::v8f32,
9977           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
9978                                                  MVT::v8i32, VPermMask)),
9979           V1);
9980
9981     // Otherwise, fall back.
9982     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9983                                                    DAG);
9984   }
9985
9986   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9987   // shuffle.
9988   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9989           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9990     return Result;
9991
9992   // If we have AVX2 then we always want to lower with a blend because at v8 we
9993   // can fully permute the elements.
9994   if (Subtarget->hasAVX2())
9995     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9996                                                       Mask, DAG);
9997
9998   // Otherwise fall back on generic lowering.
9999   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10000 }
10001
10002 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10003 ///
10004 /// This routine is only called when we have AVX2 and thus a reasonable
10005 /// instruction set for v8i32 shuffling..
10006 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10007                                        const X86Subtarget *Subtarget,
10008                                        SelectionDAG &DAG) {
10009   SDLoc DL(Op);
10010   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10011   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10012   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10013   ArrayRef<int> Mask = SVOp->getMask();
10014   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10015   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10016
10017   // Whenever we can lower this as a zext, that instruction is strictly faster
10018   // than any alternative. It also allows us to fold memory operands into the
10019   // shuffle in many cases.
10020   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10021                                                          Mask, Subtarget, DAG))
10022     return ZExt;
10023
10024   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10025                                                 Subtarget, DAG))
10026     return Blend;
10027
10028   // Check for being able to broadcast a single element.
10029   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10030                                                         Mask, Subtarget, DAG))
10031     return Broadcast;
10032
10033   // If the shuffle mask is repeated in each 128-bit lane we can use more
10034   // efficient instructions that mirror the shuffles across the two 128-bit
10035   // lanes.
10036   SmallVector<int, 4> RepeatedMask;
10037   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10038     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10039     if (isSingleInputShuffleMask(Mask))
10040       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10041                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10042
10043     // Use dedicated unpack instructions for masks that match their pattern.
10044     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10045       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10046     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10047       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10048     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10049       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10050     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10051       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10052   }
10053
10054   // Try to use shift instructions.
10055   if (SDValue Shift =
10056           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10057     return Shift;
10058
10059   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10060           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10061     return Rotate;
10062
10063   // If the shuffle patterns aren't repeated but it is a single input, directly
10064   // generate a cross-lane VPERMD instruction.
10065   if (isSingleInputShuffleMask(Mask)) {
10066     SDValue VPermMask[8];
10067     for (int i = 0; i < 8; ++i)
10068       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10069                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10070     return DAG.getNode(
10071         X86ISD::VPERMV, DL, MVT::v8i32,
10072         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10073   }
10074
10075   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10076   // shuffle.
10077   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10078           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10079     return Result;
10080
10081   // Otherwise fall back on generic blend lowering.
10082   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10083                                                     Mask, DAG);
10084 }
10085
10086 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10087 ///
10088 /// This routine is only called when we have AVX2 and thus a reasonable
10089 /// instruction set for v16i16 shuffling..
10090 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10091                                         const X86Subtarget *Subtarget,
10092                                         SelectionDAG &DAG) {
10093   SDLoc DL(Op);
10094   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10095   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10096   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10097   ArrayRef<int> Mask = SVOp->getMask();
10098   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10099   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10100
10101   // Whenever we can lower this as a zext, that instruction is strictly faster
10102   // than any alternative. It also allows us to fold memory operands into the
10103   // shuffle in many cases.
10104   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10105                                                          Mask, Subtarget, DAG))
10106     return ZExt;
10107
10108   // Check for being able to broadcast a single element.
10109   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10110                                                         Mask, Subtarget, DAG))
10111     return Broadcast;
10112
10113   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10114                                                 Subtarget, DAG))
10115     return Blend;
10116
10117   // Use dedicated unpack instructions for masks that match their pattern.
10118   if (isShuffleEquivalent(V1, V2, Mask,
10119                           {// First 128-bit lane:
10120                            0, 16, 1, 17, 2, 18, 3, 19,
10121                            // Second 128-bit lane:
10122                            8, 24, 9, 25, 10, 26, 11, 27}))
10123     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10124   if (isShuffleEquivalent(V1, V2, Mask,
10125                           {// First 128-bit lane:
10126                            4, 20, 5, 21, 6, 22, 7, 23,
10127                            // Second 128-bit lane:
10128                            12, 28, 13, 29, 14, 30, 15, 31}))
10129     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10130
10131   // Try to use shift instructions.
10132   if (SDValue Shift =
10133           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10134     return Shift;
10135
10136   // Try to use byte rotation instructions.
10137   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10138           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10139     return Rotate;
10140
10141   if (isSingleInputShuffleMask(Mask)) {
10142     // There are no generalized cross-lane shuffle operations available on i16
10143     // element types.
10144     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10145       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10146                                                      Mask, DAG);
10147
10148     SmallVector<int, 8> RepeatedMask;
10149     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10150       // As this is a single-input shuffle, the repeated mask should be
10151       // a strictly valid v8i16 mask that we can pass through to the v8i16
10152       // lowering to handle even the v16 case.
10153       return lowerV8I16GeneralSingleInputVectorShuffle(
10154           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10155     }
10156
10157     SDValue PSHUFBMask[32];
10158     for (int i = 0; i < 16; ++i) {
10159       if (Mask[i] == -1) {
10160         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10161         continue;
10162       }
10163
10164       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10165       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10166       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10167       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10168     }
10169     return DAG.getBitcast(MVT::v16i16,
10170                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10171                                       DAG.getBitcast(MVT::v32i8, V1),
10172                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10173                                                   MVT::v32i8, PSHUFBMask)));
10174   }
10175
10176   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10177   // shuffle.
10178   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10179           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10180     return Result;
10181
10182   // Otherwise fall back on generic lowering.
10183   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10184 }
10185
10186 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10187 ///
10188 /// This routine is only called when we have AVX2 and thus a reasonable
10189 /// instruction set for v32i8 shuffling..
10190 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10191                                        const X86Subtarget *Subtarget,
10192                                        SelectionDAG &DAG) {
10193   SDLoc DL(Op);
10194   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10195   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10196   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10197   ArrayRef<int> Mask = SVOp->getMask();
10198   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10199   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10200
10201   // Whenever we can lower this as a zext, that instruction is strictly faster
10202   // than any alternative. It also allows us to fold memory operands into the
10203   // shuffle in many cases.
10204   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10205                                                          Mask, Subtarget, DAG))
10206     return ZExt;
10207
10208   // Check for being able to broadcast a single element.
10209   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10210                                                         Mask, Subtarget, DAG))
10211     return Broadcast;
10212
10213   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10214                                                 Subtarget, DAG))
10215     return Blend;
10216
10217   // Use dedicated unpack instructions for masks that match their pattern.
10218   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10219   // 256-bit lanes.
10220   if (isShuffleEquivalent(
10221           V1, V2, Mask,
10222           {// First 128-bit lane:
10223            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10224            // Second 128-bit lane:
10225            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10226     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10227   if (isShuffleEquivalent(
10228           V1, V2, Mask,
10229           {// First 128-bit lane:
10230            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10231            // Second 128-bit lane:
10232            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10233     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10234
10235   // Try to use shift instructions.
10236   if (SDValue Shift =
10237           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10238     return Shift;
10239
10240   // Try to use byte rotation instructions.
10241   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10242           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10243     return Rotate;
10244
10245   if (isSingleInputShuffleMask(Mask)) {
10246     // There are no generalized cross-lane shuffle operations available on i8
10247     // element types.
10248     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10249       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10250                                                      Mask, DAG);
10251
10252     SDValue PSHUFBMask[32];
10253     for (int i = 0; i < 32; ++i)
10254       PSHUFBMask[i] =
10255           Mask[i] < 0
10256               ? DAG.getUNDEF(MVT::i8)
10257               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10258                                 MVT::i8);
10259
10260     return DAG.getNode(
10261         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10262         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10263   }
10264
10265   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10266   // shuffle.
10267   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10268           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10269     return Result;
10270
10271   // Otherwise fall back on generic lowering.
10272   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10273 }
10274
10275 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10276 ///
10277 /// This routine either breaks down the specific type of a 256-bit x86 vector
10278 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10279 /// together based on the available instructions.
10280 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10281                                         MVT VT, const X86Subtarget *Subtarget,
10282                                         SelectionDAG &DAG) {
10283   SDLoc DL(Op);
10284   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10285   ArrayRef<int> Mask = SVOp->getMask();
10286
10287   // If we have a single input to the zero element, insert that into V1 if we
10288   // can do so cheaply.
10289   int NumElts = VT.getVectorNumElements();
10290   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10291     return M >= NumElts;
10292   });
10293
10294   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10295     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10296                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10297       return Insertion;
10298
10299   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10300   // check for those subtargets here and avoid much of the subtarget querying in
10301   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10302   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10303   // floating point types there eventually, just immediately cast everything to
10304   // a float and operate entirely in that domain.
10305   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10306     int ElementBits = VT.getScalarSizeInBits();
10307     if (ElementBits < 32)
10308       // No floating point type available, decompose into 128-bit vectors.
10309       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10310
10311     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10312                                 VT.getVectorNumElements());
10313     V1 = DAG.getBitcast(FpVT, V1);
10314     V2 = DAG.getBitcast(FpVT, V2);
10315     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10316   }
10317
10318   switch (VT.SimpleTy) {
10319   case MVT::v4f64:
10320     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10321   case MVT::v4i64:
10322     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10323   case MVT::v8f32:
10324     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10325   case MVT::v8i32:
10326     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10327   case MVT::v16i16:
10328     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10329   case MVT::v32i8:
10330     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10331
10332   default:
10333     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10334   }
10335 }
10336
10337 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10338 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10339                                        const X86Subtarget *Subtarget,
10340                                        SelectionDAG &DAG) {
10341   SDLoc DL(Op);
10342   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10343   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10344   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10345   ArrayRef<int> Mask = SVOp->getMask();
10346   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10347
10348   // X86 has dedicated unpack instructions that can handle specific blend
10349   // operations: UNPCKH and UNPCKL.
10350   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10351     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10352   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10353     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10354
10355   // FIXME: Implement direct support for this type!
10356   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10357 }
10358
10359 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10360 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10361                                        const X86Subtarget *Subtarget,
10362                                        SelectionDAG &DAG) {
10363   SDLoc DL(Op);
10364   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10365   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10366   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10367   ArrayRef<int> Mask = SVOp->getMask();
10368   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10369
10370   // Use dedicated unpack instructions for masks that match their pattern.
10371   if (isShuffleEquivalent(V1, V2, Mask,
10372                           {// First 128-bit lane.
10373                            0, 16, 1, 17, 4, 20, 5, 21,
10374                            // Second 128-bit lane.
10375                            8, 24, 9, 25, 12, 28, 13, 29}))
10376     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10377   if (isShuffleEquivalent(V1, V2, Mask,
10378                           {// First 128-bit lane.
10379                            2, 18, 3, 19, 6, 22, 7, 23,
10380                            // Second 128-bit lane.
10381                            10, 26, 11, 27, 14, 30, 15, 31}))
10382     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10383
10384   // FIXME: Implement direct support for this type!
10385   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10386 }
10387
10388 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10389 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10390                                        const X86Subtarget *Subtarget,
10391                                        SelectionDAG &DAG) {
10392   SDLoc DL(Op);
10393   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10394   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10395   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10396   ArrayRef<int> Mask = SVOp->getMask();
10397   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10398
10399   // X86 has dedicated unpack instructions that can handle specific blend
10400   // operations: UNPCKH and UNPCKL.
10401   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10402     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10403   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10404     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10405
10406   // FIXME: Implement direct support for this type!
10407   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10408 }
10409
10410 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10411 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10412                                        const X86Subtarget *Subtarget,
10413                                        SelectionDAG &DAG) {
10414   SDLoc DL(Op);
10415   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10416   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10417   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10418   ArrayRef<int> Mask = SVOp->getMask();
10419   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10420
10421   // Use dedicated unpack instructions for masks that match their pattern.
10422   if (isShuffleEquivalent(V1, V2, Mask,
10423                           {// First 128-bit lane.
10424                            0, 16, 1, 17, 4, 20, 5, 21,
10425                            // Second 128-bit lane.
10426                            8, 24, 9, 25, 12, 28, 13, 29}))
10427     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10428   if (isShuffleEquivalent(V1, V2, Mask,
10429                           {// First 128-bit lane.
10430                            2, 18, 3, 19, 6, 22, 7, 23,
10431                            // Second 128-bit lane.
10432                            10, 26, 11, 27, 14, 30, 15, 31}))
10433     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10434
10435   // FIXME: Implement direct support for this type!
10436   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10437 }
10438
10439 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10440 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10441                                         const X86Subtarget *Subtarget,
10442                                         SelectionDAG &DAG) {
10443   SDLoc DL(Op);
10444   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10445   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10446   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10447   ArrayRef<int> Mask = SVOp->getMask();
10448   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10449   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10450
10451   // FIXME: Implement direct support for this type!
10452   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10453 }
10454
10455 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10456 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10457                                        const X86Subtarget *Subtarget,
10458                                        SelectionDAG &DAG) {
10459   SDLoc DL(Op);
10460   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10461   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10462   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10463   ArrayRef<int> Mask = SVOp->getMask();
10464   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10465   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10466
10467   // FIXME: Implement direct support for this type!
10468   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10469 }
10470
10471 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10472 ///
10473 /// This routine either breaks down the specific type of a 512-bit x86 vector
10474 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10475 /// together based on the available instructions.
10476 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10477                                         MVT VT, const X86Subtarget *Subtarget,
10478                                         SelectionDAG &DAG) {
10479   SDLoc DL(Op);
10480   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10481   ArrayRef<int> Mask = SVOp->getMask();
10482   assert(Subtarget->hasAVX512() &&
10483          "Cannot lower 512-bit vectors w/ basic ISA!");
10484
10485   // Check for being able to broadcast a single element.
10486   if (SDValue Broadcast =
10487           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10488     return Broadcast;
10489
10490   // Dispatch to each element type for lowering. If we don't have supprot for
10491   // specific element type shuffles at 512 bits, immediately split them and
10492   // lower them. Each lowering routine of a given type is allowed to assume that
10493   // the requisite ISA extensions for that element type are available.
10494   switch (VT.SimpleTy) {
10495   case MVT::v8f64:
10496     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10497   case MVT::v16f32:
10498     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10499   case MVT::v8i64:
10500     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10501   case MVT::v16i32:
10502     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10503   case MVT::v32i16:
10504     if (Subtarget->hasBWI())
10505       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10506     break;
10507   case MVT::v64i8:
10508     if (Subtarget->hasBWI())
10509       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10510     break;
10511
10512   default:
10513     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10514   }
10515
10516   // Otherwise fall back on splitting.
10517   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10518 }
10519
10520 /// \brief Top-level lowering for x86 vector shuffles.
10521 ///
10522 /// This handles decomposition, canonicalization, and lowering of all x86
10523 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10524 /// above in helper routines. The canonicalization attempts to widen shuffles
10525 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10526 /// s.t. only one of the two inputs needs to be tested, etc.
10527 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10528                                   SelectionDAG &DAG) {
10529   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10530   ArrayRef<int> Mask = SVOp->getMask();
10531   SDValue V1 = Op.getOperand(0);
10532   SDValue V2 = Op.getOperand(1);
10533   MVT VT = Op.getSimpleValueType();
10534   int NumElements = VT.getVectorNumElements();
10535   SDLoc dl(Op);
10536
10537   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10538
10539   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10540   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10541   if (V1IsUndef && V2IsUndef)
10542     return DAG.getUNDEF(VT);
10543
10544   // When we create a shuffle node we put the UNDEF node to second operand,
10545   // but in some cases the first operand may be transformed to UNDEF.
10546   // In this case we should just commute the node.
10547   if (V1IsUndef)
10548     return DAG.getCommutedVectorShuffle(*SVOp);
10549
10550   // Check for non-undef masks pointing at an undef vector and make the masks
10551   // undef as well. This makes it easier to match the shuffle based solely on
10552   // the mask.
10553   if (V2IsUndef)
10554     for (int M : Mask)
10555       if (M >= NumElements) {
10556         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10557         for (int &M : NewMask)
10558           if (M >= NumElements)
10559             M = -1;
10560         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10561       }
10562
10563   // We actually see shuffles that are entirely re-arrangements of a set of
10564   // zero inputs. This mostly happens while decomposing complex shuffles into
10565   // simple ones. Directly lower these as a buildvector of zeros.
10566   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10567   if (Zeroable.all())
10568     return getZeroVector(VT, Subtarget, DAG, dl);
10569
10570   // Try to collapse shuffles into using a vector type with fewer elements but
10571   // wider element types. We cap this to not form integers or floating point
10572   // elements wider than 64 bits, but it might be interesting to form i128
10573   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10574   SmallVector<int, 16> WidenedMask;
10575   if (VT.getScalarSizeInBits() < 64 &&
10576       canWidenShuffleElements(Mask, WidenedMask)) {
10577     MVT NewEltVT = VT.isFloatingPoint()
10578                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10579                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10580     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10581     // Make sure that the new vector type is legal. For example, v2f64 isn't
10582     // legal on SSE1.
10583     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10584       V1 = DAG.getBitcast(NewVT, V1);
10585       V2 = DAG.getBitcast(NewVT, V2);
10586       return DAG.getBitcast(
10587           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10588     }
10589   }
10590
10591   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10592   for (int M : SVOp->getMask())
10593     if (M < 0)
10594       ++NumUndefElements;
10595     else if (M < NumElements)
10596       ++NumV1Elements;
10597     else
10598       ++NumV2Elements;
10599
10600   // Commute the shuffle as needed such that more elements come from V1 than
10601   // V2. This allows us to match the shuffle pattern strictly on how many
10602   // elements come from V1 without handling the symmetric cases.
10603   if (NumV2Elements > NumV1Elements)
10604     return DAG.getCommutedVectorShuffle(*SVOp);
10605
10606   // When the number of V1 and V2 elements are the same, try to minimize the
10607   // number of uses of V2 in the low half of the vector. When that is tied,
10608   // ensure that the sum of indices for V1 is equal to or lower than the sum
10609   // indices for V2. When those are equal, try to ensure that the number of odd
10610   // indices for V1 is lower than the number of odd indices for V2.
10611   if (NumV1Elements == NumV2Elements) {
10612     int LowV1Elements = 0, LowV2Elements = 0;
10613     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10614       if (M >= NumElements)
10615         ++LowV2Elements;
10616       else if (M >= 0)
10617         ++LowV1Elements;
10618     if (LowV2Elements > LowV1Elements) {
10619       return DAG.getCommutedVectorShuffle(*SVOp);
10620     } else if (LowV2Elements == LowV1Elements) {
10621       int SumV1Indices = 0, SumV2Indices = 0;
10622       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10623         if (SVOp->getMask()[i] >= NumElements)
10624           SumV2Indices += i;
10625         else if (SVOp->getMask()[i] >= 0)
10626           SumV1Indices += i;
10627       if (SumV2Indices < SumV1Indices) {
10628         return DAG.getCommutedVectorShuffle(*SVOp);
10629       } else if (SumV2Indices == SumV1Indices) {
10630         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10631         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10632           if (SVOp->getMask()[i] >= NumElements)
10633             NumV2OddIndices += i % 2;
10634           else if (SVOp->getMask()[i] >= 0)
10635             NumV1OddIndices += i % 2;
10636         if (NumV2OddIndices < NumV1OddIndices)
10637           return DAG.getCommutedVectorShuffle(*SVOp);
10638       }
10639     }
10640   }
10641
10642   // For each vector width, delegate to a specialized lowering routine.
10643   if (VT.getSizeInBits() == 128)
10644     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10645
10646   if (VT.getSizeInBits() == 256)
10647     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10648
10649   // Force AVX-512 vectors to be scalarized for now.
10650   // FIXME: Implement AVX-512 support!
10651   if (VT.getSizeInBits() == 512)
10652     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10653
10654   llvm_unreachable("Unimplemented!");
10655 }
10656
10657 // This function assumes its argument is a BUILD_VECTOR of constants or
10658 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10659 // true.
10660 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10661                                     unsigned &MaskValue) {
10662   MaskValue = 0;
10663   unsigned NumElems = BuildVector->getNumOperands();
10664   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10665   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10666   unsigned NumElemsInLane = NumElems / NumLanes;
10667
10668   // Blend for v16i16 should be symetric for the both lanes.
10669   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10670     SDValue EltCond = BuildVector->getOperand(i);
10671     SDValue SndLaneEltCond =
10672         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10673
10674     int Lane1Cond = -1, Lane2Cond = -1;
10675     if (isa<ConstantSDNode>(EltCond))
10676       Lane1Cond = !isZero(EltCond);
10677     if (isa<ConstantSDNode>(SndLaneEltCond))
10678       Lane2Cond = !isZero(SndLaneEltCond);
10679
10680     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10681       // Lane1Cond != 0, means we want the first argument.
10682       // Lane1Cond == 0, means we want the second argument.
10683       // The encoding of this argument is 0 for the first argument, 1
10684       // for the second. Therefore, invert the condition.
10685       MaskValue |= !Lane1Cond << i;
10686     else if (Lane1Cond < 0)
10687       MaskValue |= !Lane2Cond << i;
10688     else
10689       return false;
10690   }
10691   return true;
10692 }
10693
10694 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10695 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10696                                            const X86Subtarget *Subtarget,
10697                                            SelectionDAG &DAG) {
10698   SDValue Cond = Op.getOperand(0);
10699   SDValue LHS = Op.getOperand(1);
10700   SDValue RHS = Op.getOperand(2);
10701   SDLoc dl(Op);
10702   MVT VT = Op.getSimpleValueType();
10703
10704   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10705     return SDValue();
10706   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10707
10708   // Only non-legal VSELECTs reach this lowering, convert those into generic
10709   // shuffles and re-use the shuffle lowering path for blends.
10710   SmallVector<int, 32> Mask;
10711   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10712     SDValue CondElt = CondBV->getOperand(i);
10713     Mask.push_back(
10714         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10715   }
10716   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10717 }
10718
10719 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10720   // A vselect where all conditions and data are constants can be optimized into
10721   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10722   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10723       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10724       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10725     return SDValue();
10726
10727   // Try to lower this to a blend-style vector shuffle. This can handle all
10728   // constant condition cases.
10729   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10730     return BlendOp;
10731
10732   // Variable blends are only legal from SSE4.1 onward.
10733   if (!Subtarget->hasSSE41())
10734     return SDValue();
10735
10736   // Only some types will be legal on some subtargets. If we can emit a legal
10737   // VSELECT-matching blend, return Op, and but if we need to expand, return
10738   // a null value.
10739   switch (Op.getSimpleValueType().SimpleTy) {
10740   default:
10741     // Most of the vector types have blends past SSE4.1.
10742     return Op;
10743
10744   case MVT::v32i8:
10745     // The byte blends for AVX vectors were introduced only in AVX2.
10746     if (Subtarget->hasAVX2())
10747       return Op;
10748
10749     return SDValue();
10750
10751   case MVT::v8i16:
10752   case MVT::v16i16:
10753     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10754     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10755       return Op;
10756
10757     // FIXME: We should custom lower this by fixing the condition and using i8
10758     // blends.
10759     return SDValue();
10760   }
10761 }
10762
10763 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10764   MVT VT = Op.getSimpleValueType();
10765   SDLoc dl(Op);
10766
10767   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10768     return SDValue();
10769
10770   if (VT.getSizeInBits() == 8) {
10771     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10772                                   Op.getOperand(0), Op.getOperand(1));
10773     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10774                                   DAG.getValueType(VT));
10775     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10776   }
10777
10778   if (VT.getSizeInBits() == 16) {
10779     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10780     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10781     if (Idx == 0)
10782       return DAG.getNode(
10783           ISD::TRUNCATE, dl, MVT::i16,
10784           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10785                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10786                       Op.getOperand(1)));
10787     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10788                                   Op.getOperand(0), Op.getOperand(1));
10789     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10790                                   DAG.getValueType(VT));
10791     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10792   }
10793
10794   if (VT == MVT::f32) {
10795     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10796     // the result back to FR32 register. It's only worth matching if the
10797     // result has a single use which is a store or a bitcast to i32.  And in
10798     // the case of a store, it's not worth it if the index is a constant 0,
10799     // because a MOVSSmr can be used instead, which is smaller and faster.
10800     if (!Op.hasOneUse())
10801       return SDValue();
10802     SDNode *User = *Op.getNode()->use_begin();
10803     if ((User->getOpcode() != ISD::STORE ||
10804          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10805           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10806         (User->getOpcode() != ISD::BITCAST ||
10807          User->getValueType(0) != MVT::i32))
10808       return SDValue();
10809     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10810                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10811                                   Op.getOperand(1));
10812     return DAG.getBitcast(MVT::f32, Extract);
10813   }
10814
10815   if (VT == MVT::i32 || VT == MVT::i64) {
10816     // ExtractPS/pextrq works with constant index.
10817     if (isa<ConstantSDNode>(Op.getOperand(1)))
10818       return Op;
10819   }
10820   return SDValue();
10821 }
10822
10823 /// Extract one bit from mask vector, like v16i1 or v8i1.
10824 /// AVX-512 feature.
10825 SDValue
10826 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10827   SDValue Vec = Op.getOperand(0);
10828   SDLoc dl(Vec);
10829   MVT VecVT = Vec.getSimpleValueType();
10830   SDValue Idx = Op.getOperand(1);
10831   MVT EltVT = Op.getSimpleValueType();
10832
10833   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10834   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10835          "Unexpected vector type in ExtractBitFromMaskVector");
10836
10837   // variable index can't be handled in mask registers,
10838   // extend vector to VR512
10839   if (!isa<ConstantSDNode>(Idx)) {
10840     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10841     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10842     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10843                               ExtVT.getVectorElementType(), Ext, Idx);
10844     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10845   }
10846
10847   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10848   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10849   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10850     rc = getRegClassFor(MVT::v16i1);
10851   unsigned MaxSift = rc->getSize()*8 - 1;
10852   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10853                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10854   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10855                     DAG.getConstant(MaxSift, dl, MVT::i8));
10856   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10857                        DAG.getIntPtrConstant(0, dl));
10858 }
10859
10860 SDValue
10861 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10862                                            SelectionDAG &DAG) const {
10863   SDLoc dl(Op);
10864   SDValue Vec = Op.getOperand(0);
10865   MVT VecVT = Vec.getSimpleValueType();
10866   SDValue Idx = Op.getOperand(1);
10867
10868   if (Op.getSimpleValueType() == MVT::i1)
10869     return ExtractBitFromMaskVector(Op, DAG);
10870
10871   if (!isa<ConstantSDNode>(Idx)) {
10872     if (VecVT.is512BitVector() ||
10873         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10874          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10875
10876       MVT MaskEltVT =
10877         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10878       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10879                                     MaskEltVT.getSizeInBits());
10880
10881       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10882       auto PtrVT = getPointerTy(DAG.getDataLayout());
10883       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10884                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10885                                  DAG.getConstant(0, dl, PtrVT));
10886       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10887       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10888                          DAG.getConstant(0, dl, PtrVT));
10889     }
10890     return SDValue();
10891   }
10892
10893   // If this is a 256-bit vector result, first extract the 128-bit vector and
10894   // then extract the element from the 128-bit vector.
10895   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10896
10897     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10898     // Get the 128-bit vector.
10899     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10900     MVT EltVT = VecVT.getVectorElementType();
10901
10902     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10903
10904     //if (IdxVal >= NumElems/2)
10905     //  IdxVal -= NumElems/2;
10906     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10907     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10908                        DAG.getConstant(IdxVal, dl, MVT::i32));
10909   }
10910
10911   assert(VecVT.is128BitVector() && "Unexpected vector length");
10912
10913   if (Subtarget->hasSSE41())
10914     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10915       return Res;
10916
10917   MVT VT = Op.getSimpleValueType();
10918   // TODO: handle v16i8.
10919   if (VT.getSizeInBits() == 16) {
10920     SDValue Vec = Op.getOperand(0);
10921     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10922     if (Idx == 0)
10923       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10924                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10925                                      DAG.getBitcast(MVT::v4i32, Vec),
10926                                      Op.getOperand(1)));
10927     // Transform it so it match pextrw which produces a 32-bit result.
10928     MVT EltVT = MVT::i32;
10929     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10930                                   Op.getOperand(0), Op.getOperand(1));
10931     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10932                                   DAG.getValueType(VT));
10933     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10934   }
10935
10936   if (VT.getSizeInBits() == 32) {
10937     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10938     if (Idx == 0)
10939       return Op;
10940
10941     // SHUFPS the element to the lowest double word, then movss.
10942     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10943     MVT VVT = Op.getOperand(0).getSimpleValueType();
10944     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10945                                        DAG.getUNDEF(VVT), Mask);
10946     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10947                        DAG.getIntPtrConstant(0, dl));
10948   }
10949
10950   if (VT.getSizeInBits() == 64) {
10951     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10952     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10953     //        to match extract_elt for f64.
10954     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10955     if (Idx == 0)
10956       return Op;
10957
10958     // UNPCKHPD the element to the lowest double word, then movsd.
10959     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10960     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10961     int Mask[2] = { 1, -1 };
10962     MVT VVT = Op.getOperand(0).getSimpleValueType();
10963     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10964                                        DAG.getUNDEF(VVT), Mask);
10965     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10966                        DAG.getIntPtrConstant(0, dl));
10967   }
10968
10969   return SDValue();
10970 }
10971
10972 /// Insert one bit to mask vector, like v16i1 or v8i1.
10973 /// AVX-512 feature.
10974 SDValue
10975 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10976   SDLoc dl(Op);
10977   SDValue Vec = Op.getOperand(0);
10978   SDValue Elt = Op.getOperand(1);
10979   SDValue Idx = Op.getOperand(2);
10980   MVT VecVT = Vec.getSimpleValueType();
10981
10982   if (!isa<ConstantSDNode>(Idx)) {
10983     // Non constant index. Extend source and destination,
10984     // insert element and then truncate the result.
10985     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10986     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10987     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10988       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10989       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10990     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10991   }
10992
10993   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10994   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10995   if (IdxVal)
10996     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10997                            DAG.getConstant(IdxVal, dl, MVT::i8));
10998   if (Vec.getOpcode() == ISD::UNDEF)
10999     return EltInVec;
11000   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11001 }
11002
11003 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11004                                                   SelectionDAG &DAG) const {
11005   MVT VT = Op.getSimpleValueType();
11006   MVT EltVT = VT.getVectorElementType();
11007
11008   if (EltVT == MVT::i1)
11009     return InsertBitToMaskVector(Op, DAG);
11010
11011   SDLoc dl(Op);
11012   SDValue N0 = Op.getOperand(0);
11013   SDValue N1 = Op.getOperand(1);
11014   SDValue N2 = Op.getOperand(2);
11015   if (!isa<ConstantSDNode>(N2))
11016     return SDValue();
11017   auto *N2C = cast<ConstantSDNode>(N2);
11018   unsigned IdxVal = N2C->getZExtValue();
11019
11020   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11021   // into that, and then insert the subvector back into the result.
11022   if (VT.is256BitVector() || VT.is512BitVector()) {
11023     // With a 256-bit vector, we can insert into the zero element efficiently
11024     // using a blend if we have AVX or AVX2 and the right data type.
11025     if (VT.is256BitVector() && IdxVal == 0) {
11026       // TODO: It is worthwhile to cast integer to floating point and back
11027       // and incur a domain crossing penalty if that's what we'll end up
11028       // doing anyway after extracting to a 128-bit vector.
11029       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11030           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11031         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11032         N2 = DAG.getIntPtrConstant(1, dl);
11033         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11034       }
11035     }
11036
11037     // Get the desired 128-bit vector chunk.
11038     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11039
11040     // Insert the element into the desired chunk.
11041     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11042     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11043
11044     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11045                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11046
11047     // Insert the changed part back into the bigger vector
11048     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11049   }
11050   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11051
11052   if (Subtarget->hasSSE41()) {
11053     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11054       unsigned Opc;
11055       if (VT == MVT::v8i16) {
11056         Opc = X86ISD::PINSRW;
11057       } else {
11058         assert(VT == MVT::v16i8);
11059         Opc = X86ISD::PINSRB;
11060       }
11061
11062       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11063       // argument.
11064       if (N1.getValueType() != MVT::i32)
11065         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11066       if (N2.getValueType() != MVT::i32)
11067         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11068       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11069     }
11070
11071     if (EltVT == MVT::f32) {
11072       // Bits [7:6] of the constant are the source select. This will always be
11073       //   zero here. The DAG Combiner may combine an extract_elt index into
11074       //   these bits. For example (insert (extract, 3), 2) could be matched by
11075       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11076       // Bits [5:4] of the constant are the destination select. This is the
11077       //   value of the incoming immediate.
11078       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11079       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11080
11081       const Function *F = DAG.getMachineFunction().getFunction();
11082       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11083       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11084         // If this is an insertion of 32-bits into the low 32-bits of
11085         // a vector, we prefer to generate a blend with immediate rather
11086         // than an insertps. Blends are simpler operations in hardware and so
11087         // will always have equal or better performance than insertps.
11088         // But if optimizing for size and there's a load folding opportunity,
11089         // generate insertps because blendps does not have a 32-bit memory
11090         // operand form.
11091         N2 = DAG.getIntPtrConstant(1, dl);
11092         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11093         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11094       }
11095       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11096       // Create this as a scalar to vector..
11097       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11098       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11099     }
11100
11101     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11102       // PINSR* works with constant index.
11103       return Op;
11104     }
11105   }
11106
11107   if (EltVT == MVT::i8)
11108     return SDValue();
11109
11110   if (EltVT.getSizeInBits() == 16) {
11111     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11112     // as its second argument.
11113     if (N1.getValueType() != MVT::i32)
11114       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11115     if (N2.getValueType() != MVT::i32)
11116       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11117     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11118   }
11119   return SDValue();
11120 }
11121
11122 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11123   SDLoc dl(Op);
11124   MVT OpVT = Op.getSimpleValueType();
11125
11126   // If this is a 256-bit vector result, first insert into a 128-bit
11127   // vector and then insert into the 256-bit vector.
11128   if (!OpVT.is128BitVector()) {
11129     // Insert into a 128-bit vector.
11130     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11131     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11132                                  OpVT.getVectorNumElements() / SizeFactor);
11133
11134     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11135
11136     // Insert the 128-bit vector.
11137     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11138   }
11139
11140   if (OpVT == MVT::v1i64 &&
11141       Op.getOperand(0).getValueType() == MVT::i64)
11142     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11143
11144   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11145   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11146   return DAG.getBitcast(
11147       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11148 }
11149
11150 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11151 // a simple subregister reference or explicit instructions to grab
11152 // upper bits of a vector.
11153 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11154                                       SelectionDAG &DAG) {
11155   SDLoc dl(Op);
11156   SDValue In =  Op.getOperand(0);
11157   SDValue Idx = Op.getOperand(1);
11158   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11159   MVT ResVT   = Op.getSimpleValueType();
11160   MVT InVT    = In.getSimpleValueType();
11161
11162   if (Subtarget->hasFp256()) {
11163     if (ResVT.is128BitVector() &&
11164         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11165         isa<ConstantSDNode>(Idx)) {
11166       return Extract128BitVector(In, IdxVal, DAG, dl);
11167     }
11168     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11169         isa<ConstantSDNode>(Idx)) {
11170       return Extract256BitVector(In, IdxVal, DAG, dl);
11171     }
11172   }
11173   return SDValue();
11174 }
11175
11176 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11177 // simple superregister reference or explicit instructions to insert
11178 // the upper bits of a vector.
11179 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11180                                      SelectionDAG &DAG) {
11181   if (!Subtarget->hasAVX())
11182     return SDValue();
11183
11184   SDLoc dl(Op);
11185   SDValue Vec = Op.getOperand(0);
11186   SDValue SubVec = Op.getOperand(1);
11187   SDValue Idx = Op.getOperand(2);
11188
11189   if (!isa<ConstantSDNode>(Idx))
11190     return SDValue();
11191
11192   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11193   MVT OpVT = Op.getSimpleValueType();
11194   MVT SubVecVT = SubVec.getSimpleValueType();
11195
11196   // Fold two 16-byte subvector loads into one 32-byte load:
11197   // (insert_subvector (insert_subvector undef, (load addr), 0),
11198   //                   (load addr + 16), Elts/2)
11199   // --> load32 addr
11200   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11201       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11202       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11203       !Subtarget->isUnalignedMem32Slow()) {
11204     SDValue SubVec2 = Vec.getOperand(1);
11205     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11206       if (Idx2->getZExtValue() == 0) {
11207         SDValue Ops[] = { SubVec2, SubVec };
11208         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11209           return Ld;
11210       }
11211     }
11212   }
11213
11214   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11215       SubVecVT.is128BitVector())
11216     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11217
11218   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11219     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11220
11221   if (OpVT.getVectorElementType() == MVT::i1) {
11222     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11223       return Op;
11224     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11225     SDValue Undef = DAG.getUNDEF(OpVT);
11226     unsigned NumElems = OpVT.getVectorNumElements();
11227     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11228
11229     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11230       // Zero upper bits of the Vec
11231       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11232       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11233
11234       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11235                                  SubVec, ZeroIdx);
11236       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11237       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11238     }
11239     if (IdxVal == 0) {
11240       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11241                                  SubVec, ZeroIdx);
11242       // Zero upper bits of the Vec2
11243       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11244       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11245       // Zero lower bits of the Vec
11246       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11247       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11248       // Merge them together
11249       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11250     }
11251   }
11252   return SDValue();
11253 }
11254
11255 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11256 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11257 // one of the above mentioned nodes. It has to be wrapped because otherwise
11258 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11259 // be used to form addressing mode. These wrapped nodes will be selected
11260 // into MOV32ri.
11261 SDValue
11262 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11263   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11264
11265   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11266   // global base reg.
11267   unsigned char OpFlag = 0;
11268   unsigned WrapperKind = X86ISD::Wrapper;
11269   CodeModel::Model M = DAG.getTarget().getCodeModel();
11270
11271   if (Subtarget->isPICStyleRIPRel() &&
11272       (M == CodeModel::Small || M == CodeModel::Kernel))
11273     WrapperKind = X86ISD::WrapperRIP;
11274   else if (Subtarget->isPICStyleGOT())
11275     OpFlag = X86II::MO_GOTOFF;
11276   else if (Subtarget->isPICStyleStubPIC())
11277     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11278
11279   auto PtrVT = getPointerTy(DAG.getDataLayout());
11280   SDValue Result = DAG.getTargetConstantPool(
11281       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11282   SDLoc DL(CP);
11283   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11284   // With PIC, the address is actually $g + Offset.
11285   if (OpFlag) {
11286     Result =
11287         DAG.getNode(ISD::ADD, DL, PtrVT,
11288                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11289   }
11290
11291   return Result;
11292 }
11293
11294 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11295   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11296
11297   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11298   // global base reg.
11299   unsigned char OpFlag = 0;
11300   unsigned WrapperKind = X86ISD::Wrapper;
11301   CodeModel::Model M = DAG.getTarget().getCodeModel();
11302
11303   if (Subtarget->isPICStyleRIPRel() &&
11304       (M == CodeModel::Small || M == CodeModel::Kernel))
11305     WrapperKind = X86ISD::WrapperRIP;
11306   else if (Subtarget->isPICStyleGOT())
11307     OpFlag = X86II::MO_GOTOFF;
11308   else if (Subtarget->isPICStyleStubPIC())
11309     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11310
11311   auto PtrVT = getPointerTy(DAG.getDataLayout());
11312   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11313   SDLoc DL(JT);
11314   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11315
11316   // With PIC, the address is actually $g + Offset.
11317   if (OpFlag)
11318     Result =
11319         DAG.getNode(ISD::ADD, DL, PtrVT,
11320                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11321
11322   return Result;
11323 }
11324
11325 SDValue
11326 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11327   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11328
11329   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11330   // global base reg.
11331   unsigned char OpFlag = 0;
11332   unsigned WrapperKind = X86ISD::Wrapper;
11333   CodeModel::Model M = DAG.getTarget().getCodeModel();
11334
11335   if (Subtarget->isPICStyleRIPRel() &&
11336       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11337     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11338       OpFlag = X86II::MO_GOTPCREL;
11339     WrapperKind = X86ISD::WrapperRIP;
11340   } else if (Subtarget->isPICStyleGOT()) {
11341     OpFlag = X86II::MO_GOT;
11342   } else if (Subtarget->isPICStyleStubPIC()) {
11343     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11344   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11345     OpFlag = X86II::MO_DARWIN_NONLAZY;
11346   }
11347
11348   auto PtrVT = getPointerTy(DAG.getDataLayout());
11349   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11350
11351   SDLoc DL(Op);
11352   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11353
11354   // With PIC, the address is actually $g + Offset.
11355   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11356       !Subtarget->is64Bit()) {
11357     Result =
11358         DAG.getNode(ISD::ADD, DL, PtrVT,
11359                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11360   }
11361
11362   // For symbols that require a load from a stub to get the address, emit the
11363   // load.
11364   if (isGlobalStubReference(OpFlag))
11365     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11366                          MachinePointerInfo::getGOT(), false, false, false, 0);
11367
11368   return Result;
11369 }
11370
11371 SDValue
11372 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11373   // Create the TargetBlockAddressAddress node.
11374   unsigned char OpFlags =
11375     Subtarget->ClassifyBlockAddressReference();
11376   CodeModel::Model M = DAG.getTarget().getCodeModel();
11377   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11378   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11379   SDLoc dl(Op);
11380   auto PtrVT = getPointerTy(DAG.getDataLayout());
11381   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11382
11383   if (Subtarget->isPICStyleRIPRel() &&
11384       (M == CodeModel::Small || M == CodeModel::Kernel))
11385     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11386   else
11387     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11388
11389   // With PIC, the address is actually $g + Offset.
11390   if (isGlobalRelativeToPICBase(OpFlags)) {
11391     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11392                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11393   }
11394
11395   return Result;
11396 }
11397
11398 SDValue
11399 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11400                                       int64_t Offset, SelectionDAG &DAG) const {
11401   // Create the TargetGlobalAddress node, folding in the constant
11402   // offset if it is legal.
11403   unsigned char OpFlags =
11404       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11405   CodeModel::Model M = DAG.getTarget().getCodeModel();
11406   auto PtrVT = getPointerTy(DAG.getDataLayout());
11407   SDValue Result;
11408   if (OpFlags == X86II::MO_NO_FLAG &&
11409       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11410     // A direct static reference to a global.
11411     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11412     Offset = 0;
11413   } else {
11414     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11415   }
11416
11417   if (Subtarget->isPICStyleRIPRel() &&
11418       (M == CodeModel::Small || M == CodeModel::Kernel))
11419     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11420   else
11421     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11422
11423   // With PIC, the address is actually $g + Offset.
11424   if (isGlobalRelativeToPICBase(OpFlags)) {
11425     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11426                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11427   }
11428
11429   // For globals that require a load from a stub to get the address, emit the
11430   // load.
11431   if (isGlobalStubReference(OpFlags))
11432     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11433                          MachinePointerInfo::getGOT(), false, false, false, 0);
11434
11435   // If there was a non-zero offset that we didn't fold, create an explicit
11436   // addition for it.
11437   if (Offset != 0)
11438     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11439                          DAG.getConstant(Offset, dl, PtrVT));
11440
11441   return Result;
11442 }
11443
11444 SDValue
11445 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11446   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11447   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11448   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11449 }
11450
11451 static SDValue
11452 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11453            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11454            unsigned char OperandFlags, bool LocalDynamic = false) {
11455   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11456   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11457   SDLoc dl(GA);
11458   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11459                                            GA->getValueType(0),
11460                                            GA->getOffset(),
11461                                            OperandFlags);
11462
11463   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11464                                            : X86ISD::TLSADDR;
11465
11466   if (InFlag) {
11467     SDValue Ops[] = { Chain,  TGA, *InFlag };
11468     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11469   } else {
11470     SDValue Ops[]  = { Chain, TGA };
11471     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11472   }
11473
11474   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11475   MFI->setAdjustsStack(true);
11476   MFI->setHasCalls(true);
11477
11478   SDValue Flag = Chain.getValue(1);
11479   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11480 }
11481
11482 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11483 static SDValue
11484 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11485                                 const EVT PtrVT) {
11486   SDValue InFlag;
11487   SDLoc dl(GA);  // ? function entry point might be better
11488   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11489                                    DAG.getNode(X86ISD::GlobalBaseReg,
11490                                                SDLoc(), PtrVT), InFlag);
11491   InFlag = Chain.getValue(1);
11492
11493   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11494 }
11495
11496 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11497 static SDValue
11498 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11499                                 const EVT PtrVT) {
11500   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11501                     X86::RAX, X86II::MO_TLSGD);
11502 }
11503
11504 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11505                                            SelectionDAG &DAG,
11506                                            const EVT PtrVT,
11507                                            bool is64Bit) {
11508   SDLoc dl(GA);
11509
11510   // Get the start address of the TLS block for this module.
11511   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11512       .getInfo<X86MachineFunctionInfo>();
11513   MFI->incNumLocalDynamicTLSAccesses();
11514
11515   SDValue Base;
11516   if (is64Bit) {
11517     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11518                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11519   } else {
11520     SDValue InFlag;
11521     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11522         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11523     InFlag = Chain.getValue(1);
11524     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11525                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11526   }
11527
11528   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11529   // of Base.
11530
11531   // Build x@dtpoff.
11532   unsigned char OperandFlags = X86II::MO_DTPOFF;
11533   unsigned WrapperKind = X86ISD::Wrapper;
11534   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11535                                            GA->getValueType(0),
11536                                            GA->getOffset(), OperandFlags);
11537   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11538
11539   // Add x@dtpoff with the base.
11540   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11541 }
11542
11543 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11544 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11545                                    const EVT PtrVT, TLSModel::Model model,
11546                                    bool is64Bit, bool isPIC) {
11547   SDLoc dl(GA);
11548
11549   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11550   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11551                                                          is64Bit ? 257 : 256));
11552
11553   SDValue ThreadPointer =
11554       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11555                   MachinePointerInfo(Ptr), false, false, false, 0);
11556
11557   unsigned char OperandFlags = 0;
11558   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11559   // initialexec.
11560   unsigned WrapperKind = X86ISD::Wrapper;
11561   if (model == TLSModel::LocalExec) {
11562     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11563   } else if (model == TLSModel::InitialExec) {
11564     if (is64Bit) {
11565       OperandFlags = X86II::MO_GOTTPOFF;
11566       WrapperKind = X86ISD::WrapperRIP;
11567     } else {
11568       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11569     }
11570   } else {
11571     llvm_unreachable("Unexpected model");
11572   }
11573
11574   // emit "addl x@ntpoff,%eax" (local exec)
11575   // or "addl x@indntpoff,%eax" (initial exec)
11576   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11577   SDValue TGA =
11578       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11579                                  GA->getOffset(), OperandFlags);
11580   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11581
11582   if (model == TLSModel::InitialExec) {
11583     if (isPIC && !is64Bit) {
11584       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11585                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11586                            Offset);
11587     }
11588
11589     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11590                          MachinePointerInfo::getGOT(), false, false, false, 0);
11591   }
11592
11593   // The address of the thread local variable is the add of the thread
11594   // pointer with the offset of the variable.
11595   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11596 }
11597
11598 SDValue
11599 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11600
11601   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11602   const GlobalValue *GV = GA->getGlobal();
11603   auto PtrVT = getPointerTy(DAG.getDataLayout());
11604
11605   if (Subtarget->isTargetELF()) {
11606     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11607     switch (model) {
11608       case TLSModel::GeneralDynamic:
11609         if (Subtarget->is64Bit())
11610           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11611         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11612       case TLSModel::LocalDynamic:
11613         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11614                                            Subtarget->is64Bit());
11615       case TLSModel::InitialExec:
11616       case TLSModel::LocalExec:
11617         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11618                                    DAG.getTarget().getRelocationModel() ==
11619                                        Reloc::PIC_);
11620     }
11621     llvm_unreachable("Unknown TLS model.");
11622   }
11623
11624   if (Subtarget->isTargetDarwin()) {
11625     // Darwin only has one model of TLS.  Lower to that.
11626     unsigned char OpFlag = 0;
11627     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11628                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11629
11630     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11631     // global base reg.
11632     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11633                  !Subtarget->is64Bit();
11634     if (PIC32)
11635       OpFlag = X86II::MO_TLVP_PIC_BASE;
11636     else
11637       OpFlag = X86II::MO_TLVP;
11638     SDLoc DL(Op);
11639     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11640                                                 GA->getValueType(0),
11641                                                 GA->getOffset(), OpFlag);
11642     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11643
11644     // With PIC32, the address is actually $g + Offset.
11645     if (PIC32)
11646       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11647                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11648                            Offset);
11649
11650     // Lowering the machine isd will make sure everything is in the right
11651     // location.
11652     SDValue Chain = DAG.getEntryNode();
11653     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11654     SDValue Args[] = { Chain, Offset };
11655     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11656
11657     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11658     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11659     MFI->setAdjustsStack(true);
11660
11661     // And our return value (tls address) is in the standard call return value
11662     // location.
11663     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11664     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11665   }
11666
11667   if (Subtarget->isTargetKnownWindowsMSVC() ||
11668       Subtarget->isTargetWindowsGNU()) {
11669     // Just use the implicit TLS architecture
11670     // Need to generate someting similar to:
11671     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11672     //                                  ; from TEB
11673     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11674     //   mov     rcx, qword [rdx+rcx*8]
11675     //   mov     eax, .tls$:tlsvar
11676     //   [rax+rcx] contains the address
11677     // Windows 64bit: gs:0x58
11678     // Windows 32bit: fs:__tls_array
11679
11680     SDLoc dl(GA);
11681     SDValue Chain = DAG.getEntryNode();
11682
11683     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11684     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11685     // use its literal value of 0x2C.
11686     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11687                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11688                                                              256)
11689                                         : Type::getInt32PtrTy(*DAG.getContext(),
11690                                                               257));
11691
11692     SDValue TlsArray = Subtarget->is64Bit()
11693                            ? DAG.getIntPtrConstant(0x58, dl)
11694                            : (Subtarget->isTargetWindowsGNU()
11695                                   ? DAG.getIntPtrConstant(0x2C, dl)
11696                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11697
11698     SDValue ThreadPointer =
11699         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11700                     false, false, 0);
11701
11702     SDValue res;
11703     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11704       res = ThreadPointer;
11705     } else {
11706       // Load the _tls_index variable
11707       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11708       if (Subtarget->is64Bit())
11709         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11710                              MachinePointerInfo(), MVT::i32, false, false,
11711                              false, 0);
11712       else
11713         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11714                           false, false, 0);
11715
11716       auto &DL = DAG.getDataLayout();
11717       SDValue Scale =
11718           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11719       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11720
11721       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11722     }
11723
11724     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11725                       false, 0);
11726
11727     // Get the offset of start of .tls section
11728     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11729                                              GA->getValueType(0),
11730                                              GA->getOffset(), X86II::MO_SECREL);
11731     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11732
11733     // The address of the thread local variable is the add of the thread
11734     // pointer with the offset of the variable.
11735     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11736   }
11737
11738   llvm_unreachable("TLS not implemented for this target.");
11739 }
11740
11741 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11742 /// and take a 2 x i32 value to shift plus a shift amount.
11743 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11744   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11745   MVT VT = Op.getSimpleValueType();
11746   unsigned VTBits = VT.getSizeInBits();
11747   SDLoc dl(Op);
11748   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11749   SDValue ShOpLo = Op.getOperand(0);
11750   SDValue ShOpHi = Op.getOperand(1);
11751   SDValue ShAmt  = Op.getOperand(2);
11752   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11753   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11754   // during isel.
11755   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11756                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11757   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11758                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11759                        : DAG.getConstant(0, dl, VT);
11760
11761   SDValue Tmp2, Tmp3;
11762   if (Op.getOpcode() == ISD::SHL_PARTS) {
11763     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11764     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11765   } else {
11766     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11767     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11768   }
11769
11770   // If the shift amount is larger or equal than the width of a part we can't
11771   // rely on the results of shld/shrd. Insert a test and select the appropriate
11772   // values for large shift amounts.
11773   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11774                                 DAG.getConstant(VTBits, dl, MVT::i8));
11775   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11776                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11777
11778   SDValue Hi, Lo;
11779   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11780   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11781   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11782
11783   if (Op.getOpcode() == ISD::SHL_PARTS) {
11784     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11785     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11786   } else {
11787     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11788     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11789   }
11790
11791   SDValue Ops[2] = { Lo, Hi };
11792   return DAG.getMergeValues(Ops, dl);
11793 }
11794
11795 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11796                                            SelectionDAG &DAG) const {
11797   SDValue Src = Op.getOperand(0);
11798   MVT SrcVT = Src.getSimpleValueType();
11799   MVT VT = Op.getSimpleValueType();
11800   SDLoc dl(Op);
11801
11802   if (SrcVT.isVector()) {
11803     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11804       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11805                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11806                          DAG.getUNDEF(SrcVT)));
11807     }
11808     if (SrcVT.getVectorElementType() == MVT::i1) {
11809       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11810       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11811                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11812     }
11813     return SDValue();
11814   }
11815
11816   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11817          "Unknown SINT_TO_FP to lower!");
11818
11819   // These are really Legal; return the operand so the caller accepts it as
11820   // Legal.
11821   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11822     return Op;
11823   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11824       Subtarget->is64Bit()) {
11825     return Op;
11826   }
11827
11828   unsigned Size = SrcVT.getSizeInBits()/8;
11829   MachineFunction &MF = DAG.getMachineFunction();
11830   auto PtrVT = getPointerTy(MF.getDataLayout());
11831   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11832   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11833   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11834                                StackSlot,
11835                                MachinePointerInfo::getFixedStack(SSFI),
11836                                false, false, 0);
11837   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11838 }
11839
11840 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11841                                      SDValue StackSlot,
11842                                      SelectionDAG &DAG) const {
11843   // Build the FILD
11844   SDLoc DL(Op);
11845   SDVTList Tys;
11846   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11847   if (useSSE)
11848     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11849   else
11850     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11851
11852   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11853
11854   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11855   MachineMemOperand *MMO;
11856   if (FI) {
11857     int SSFI = FI->getIndex();
11858     MMO =
11859       DAG.getMachineFunction()
11860       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11861                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11862   } else {
11863     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11864     StackSlot = StackSlot.getOperand(1);
11865   }
11866   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11867   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11868                                            X86ISD::FILD, DL,
11869                                            Tys, Ops, SrcVT, MMO);
11870
11871   if (useSSE) {
11872     Chain = Result.getValue(1);
11873     SDValue InFlag = Result.getValue(2);
11874
11875     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11876     // shouldn't be necessary except that RFP cannot be live across
11877     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11878     MachineFunction &MF = DAG.getMachineFunction();
11879     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11880     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11881     auto PtrVT = getPointerTy(MF.getDataLayout());
11882     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11883     Tys = DAG.getVTList(MVT::Other);
11884     SDValue Ops[] = {
11885       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11886     };
11887     MachineMemOperand *MMO =
11888       DAG.getMachineFunction()
11889       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11890                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11891
11892     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11893                                     Ops, Op.getValueType(), MMO);
11894     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11895                          MachinePointerInfo::getFixedStack(SSFI),
11896                          false, false, false, 0);
11897   }
11898
11899   return Result;
11900 }
11901
11902 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11903 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11904                                                SelectionDAG &DAG) const {
11905   // This algorithm is not obvious. Here it is what we're trying to output:
11906   /*
11907      movq       %rax,  %xmm0
11908      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11909      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11910      #ifdef __SSE3__
11911        haddpd   %xmm0, %xmm0
11912      #else
11913        pshufd   $0x4e, %xmm0, %xmm1
11914        addpd    %xmm1, %xmm0
11915      #endif
11916   */
11917
11918   SDLoc dl(Op);
11919   LLVMContext *Context = DAG.getContext();
11920
11921   // Build some magic constants.
11922   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11923   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11924   auto PtrVT = getPointerTy(DAG.getDataLayout());
11925   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11926
11927   SmallVector<Constant*,2> CV1;
11928   CV1.push_back(
11929     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11930                                       APInt(64, 0x4330000000000000ULL))));
11931   CV1.push_back(
11932     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11933                                       APInt(64, 0x4530000000000000ULL))));
11934   Constant *C1 = ConstantVector::get(CV1);
11935   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11936
11937   // Load the 64-bit value into an XMM register.
11938   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11939                             Op.getOperand(0));
11940   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11941                               MachinePointerInfo::getConstantPool(),
11942                               false, false, false, 16);
11943   SDValue Unpck1 =
11944       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11945
11946   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11947                               MachinePointerInfo::getConstantPool(),
11948                               false, false, false, 16);
11949   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11950   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11951   SDValue Result;
11952
11953   if (Subtarget->hasSSE3()) {
11954     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11955     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11956   } else {
11957     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11958     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11959                                            S2F, 0x4E, DAG);
11960     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11961                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11962   }
11963
11964   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11965                      DAG.getIntPtrConstant(0, dl));
11966 }
11967
11968 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11969 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11970                                                SelectionDAG &DAG) const {
11971   SDLoc dl(Op);
11972   // FP constant to bias correct the final result.
11973   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11974                                    MVT::f64);
11975
11976   // Load the 32-bit value into an XMM register.
11977   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11978                              Op.getOperand(0));
11979
11980   // Zero out the upper parts of the register.
11981   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11982
11983   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11984                      DAG.getBitcast(MVT::v2f64, Load),
11985                      DAG.getIntPtrConstant(0, dl));
11986
11987   // Or the load with the bias.
11988   SDValue Or = DAG.getNode(
11989       ISD::OR, dl, MVT::v2i64,
11990       DAG.getBitcast(MVT::v2i64,
11991                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
11992       DAG.getBitcast(MVT::v2i64,
11993                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
11994   Or =
11995       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11996                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
11997
11998   // Subtract the bias.
11999   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12000
12001   // Handle final rounding.
12002   EVT DestVT = Op.getValueType();
12003
12004   if (DestVT.bitsLT(MVT::f64))
12005     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12006                        DAG.getIntPtrConstant(0, dl));
12007   if (DestVT.bitsGT(MVT::f64))
12008     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12009
12010   // Handle final rounding.
12011   return Sub;
12012 }
12013
12014 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12015                                      const X86Subtarget &Subtarget) {
12016   // The algorithm is the following:
12017   // #ifdef __SSE4_1__
12018   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12019   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12020   //                                 (uint4) 0x53000000, 0xaa);
12021   // #else
12022   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12023   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12024   // #endif
12025   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12026   //     return (float4) lo + fhi;
12027
12028   SDLoc DL(Op);
12029   SDValue V = Op->getOperand(0);
12030   EVT VecIntVT = V.getValueType();
12031   bool Is128 = VecIntVT == MVT::v4i32;
12032   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12033   // If we convert to something else than the supported type, e.g., to v4f64,
12034   // abort early.
12035   if (VecFloatVT != Op->getValueType(0))
12036     return SDValue();
12037
12038   unsigned NumElts = VecIntVT.getVectorNumElements();
12039   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12040          "Unsupported custom type");
12041   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12042
12043   // In the #idef/#else code, we have in common:
12044   // - The vector of constants:
12045   // -- 0x4b000000
12046   // -- 0x53000000
12047   // - A shift:
12048   // -- v >> 16
12049
12050   // Create the splat vector for 0x4b000000.
12051   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12052   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12053                            CstLow, CstLow, CstLow, CstLow};
12054   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12055                                   makeArrayRef(&CstLowArray[0], NumElts));
12056   // Create the splat vector for 0x53000000.
12057   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12058   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12059                             CstHigh, CstHigh, CstHigh, CstHigh};
12060   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12061                                    makeArrayRef(&CstHighArray[0], NumElts));
12062
12063   // Create the right shift.
12064   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12065   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12066                              CstShift, CstShift, CstShift, CstShift};
12067   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12068                                     makeArrayRef(&CstShiftArray[0], NumElts));
12069   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12070
12071   SDValue Low, High;
12072   if (Subtarget.hasSSE41()) {
12073     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12074     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12075     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12076     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12077     // Low will be bitcasted right away, so do not bother bitcasting back to its
12078     // original type.
12079     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12080                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12081     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12082     //                                 (uint4) 0x53000000, 0xaa);
12083     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12084     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12085     // High will be bitcasted right away, so do not bother bitcasting back to
12086     // its original type.
12087     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12088                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12089   } else {
12090     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12091     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12092                                      CstMask, CstMask, CstMask);
12093     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12094     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12095     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12096
12097     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12098     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12099   }
12100
12101   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12102   SDValue CstFAdd = DAG.getConstantFP(
12103       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12104   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12105                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12106   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12107                                    makeArrayRef(&CstFAddArray[0], NumElts));
12108
12109   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12110   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12111   SDValue FHigh =
12112       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12113   //     return (float4) lo + fhi;
12114   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12115   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12116 }
12117
12118 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12119                                                SelectionDAG &DAG) const {
12120   SDValue N0 = Op.getOperand(0);
12121   MVT SVT = N0.getSimpleValueType();
12122   SDLoc dl(Op);
12123
12124   switch (SVT.SimpleTy) {
12125   default:
12126     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12127   case MVT::v4i8:
12128   case MVT::v4i16:
12129   case MVT::v8i8:
12130   case MVT::v8i16: {
12131     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12132     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12133                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12134   }
12135   case MVT::v4i32:
12136   case MVT::v8i32:
12137     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12138   case MVT::v16i8:
12139   case MVT::v16i16:
12140     if (Subtarget->hasAVX512())
12141       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12142                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12143   }
12144   llvm_unreachable(nullptr);
12145 }
12146
12147 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12148                                            SelectionDAG &DAG) const {
12149   SDValue N0 = Op.getOperand(0);
12150   SDLoc dl(Op);
12151   auto PtrVT = getPointerTy(DAG.getDataLayout());
12152
12153   if (Op.getValueType().isVector())
12154     return lowerUINT_TO_FP_vec(Op, DAG);
12155
12156   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12157   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12158   // the optimization here.
12159   if (DAG.SignBitIsZero(N0))
12160     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12161
12162   MVT SrcVT = N0.getSimpleValueType();
12163   MVT DstVT = Op.getSimpleValueType();
12164   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12165     return LowerUINT_TO_FP_i64(Op, DAG);
12166   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12167     return LowerUINT_TO_FP_i32(Op, DAG);
12168   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12169     return SDValue();
12170
12171   // Make a 64-bit buffer, and use it to build an FILD.
12172   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12173   if (SrcVT == MVT::i32) {
12174     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12175     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12176     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12177                                   StackSlot, MachinePointerInfo(),
12178                                   false, false, 0);
12179     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12180                                   OffsetSlot, MachinePointerInfo(),
12181                                   false, false, 0);
12182     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12183     return Fild;
12184   }
12185
12186   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12187   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12188                                StackSlot, MachinePointerInfo(),
12189                                false, false, 0);
12190   // For i64 source, we need to add the appropriate power of 2 if the input
12191   // was negative.  This is the same as the optimization in
12192   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12193   // we must be careful to do the computation in x87 extended precision, not
12194   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12195   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12196   MachineMemOperand *MMO =
12197     DAG.getMachineFunction()
12198     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12199                           MachineMemOperand::MOLoad, 8, 8);
12200
12201   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12202   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12203   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12204                                          MVT::i64, MMO);
12205
12206   APInt FF(32, 0x5F800000ULL);
12207
12208   // Check whether the sign bit is set.
12209   SDValue SignSet = DAG.getSetCC(
12210       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12211       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12212
12213   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12214   SDValue FudgePtr = DAG.getConstantPool(
12215       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12216
12217   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12218   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12219   SDValue Four = DAG.getIntPtrConstant(4, dl);
12220   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12221                                Zero, Four);
12222   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12223
12224   // Load the value out, extending it from f32 to f80.
12225   // FIXME: Avoid the extend by constructing the right constant pool?
12226   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12227                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12228                                  MVT::f32, false, false, false, 4);
12229   // Extend everything to 80 bits to force it to be done on x87.
12230   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12231   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12232                      DAG.getIntPtrConstant(0, dl));
12233 }
12234
12235 std::pair<SDValue,SDValue>
12236 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12237                                     bool IsSigned, bool IsReplace) const {
12238   SDLoc DL(Op);
12239
12240   EVT DstTy = Op.getValueType();
12241   auto PtrVT = getPointerTy(DAG.getDataLayout());
12242
12243   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12244     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12245     DstTy = MVT::i64;
12246   }
12247
12248   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12249          DstTy.getSimpleVT() >= MVT::i16 &&
12250          "Unknown FP_TO_INT to lower!");
12251
12252   // These are really Legal.
12253   if (DstTy == MVT::i32 &&
12254       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12255     return std::make_pair(SDValue(), SDValue());
12256   if (Subtarget->is64Bit() &&
12257       DstTy == MVT::i64 &&
12258       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12259     return std::make_pair(SDValue(), SDValue());
12260
12261   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12262   // stack slot, or into the FTOL runtime function.
12263   MachineFunction &MF = DAG.getMachineFunction();
12264   unsigned MemSize = DstTy.getSizeInBits()/8;
12265   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12266   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12267
12268   unsigned Opc;
12269   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12270     Opc = X86ISD::WIN_FTOL;
12271   else
12272     switch (DstTy.getSimpleVT().SimpleTy) {
12273     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12274     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12275     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12276     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12277     }
12278
12279   SDValue Chain = DAG.getEntryNode();
12280   SDValue Value = Op.getOperand(0);
12281   EVT TheVT = Op.getOperand(0).getValueType();
12282   // FIXME This causes a redundant load/store if the SSE-class value is already
12283   // in memory, such as if it is on the callstack.
12284   if (isScalarFPTypeInSSEReg(TheVT)) {
12285     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12286     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12287                          MachinePointerInfo::getFixedStack(SSFI),
12288                          false, false, 0);
12289     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12290     SDValue Ops[] = {
12291       Chain, StackSlot, DAG.getValueType(TheVT)
12292     };
12293
12294     MachineMemOperand *MMO =
12295       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12296                               MachineMemOperand::MOLoad, MemSize, MemSize);
12297     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12298     Chain = Value.getValue(1);
12299     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12300     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12301   }
12302
12303   MachineMemOperand *MMO =
12304     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12305                             MachineMemOperand::MOStore, MemSize, MemSize);
12306
12307   if (Opc != X86ISD::WIN_FTOL) {
12308     // Build the FP_TO_INT*_IN_MEM
12309     SDValue Ops[] = { Chain, Value, StackSlot };
12310     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12311                                            Ops, DstTy, MMO);
12312     return std::make_pair(FIST, StackSlot);
12313   } else {
12314     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12315       DAG.getVTList(MVT::Other, MVT::Glue),
12316       Chain, Value);
12317     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12318       MVT::i32, ftol.getValue(1));
12319     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12320       MVT::i32, eax.getValue(2));
12321     SDValue Ops[] = { eax, edx };
12322     SDValue pair = IsReplace
12323       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12324       : DAG.getMergeValues(Ops, DL);
12325     return std::make_pair(pair, SDValue());
12326   }
12327 }
12328
12329 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12330                               const X86Subtarget *Subtarget) {
12331   MVT VT = Op->getSimpleValueType(0);
12332   SDValue In = Op->getOperand(0);
12333   MVT InVT = In.getSimpleValueType();
12334   SDLoc dl(Op);
12335
12336   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12337     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12338
12339   // Optimize vectors in AVX mode:
12340   //
12341   //   v8i16 -> v8i32
12342   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12343   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12344   //   Concat upper and lower parts.
12345   //
12346   //   v4i32 -> v4i64
12347   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12348   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12349   //   Concat upper and lower parts.
12350   //
12351
12352   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12353       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12354       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12355     return SDValue();
12356
12357   if (Subtarget->hasInt256())
12358     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12359
12360   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12361   SDValue Undef = DAG.getUNDEF(InVT);
12362   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12363   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12364   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12365
12366   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12367                              VT.getVectorNumElements()/2);
12368
12369   OpLo = DAG.getBitcast(HVT, OpLo);
12370   OpHi = DAG.getBitcast(HVT, OpHi);
12371
12372   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12373 }
12374
12375 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12376                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12377   MVT VT = Op->getSimpleValueType(0);
12378   SDValue In = Op->getOperand(0);
12379   MVT InVT = In.getSimpleValueType();
12380   SDLoc DL(Op);
12381   unsigned int NumElts = VT.getVectorNumElements();
12382   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12383     return SDValue();
12384
12385   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12386     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12387
12388   assert(InVT.getVectorElementType() == MVT::i1);
12389   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12390   SDValue One =
12391    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12392   SDValue Zero =
12393    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12394
12395   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12396   if (VT.is512BitVector())
12397     return V;
12398   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12399 }
12400
12401 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12402                                SelectionDAG &DAG) {
12403   if (Subtarget->hasFp256())
12404     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12405       return Res;
12406
12407   return SDValue();
12408 }
12409
12410 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12411                                 SelectionDAG &DAG) {
12412   SDLoc DL(Op);
12413   MVT VT = Op.getSimpleValueType();
12414   SDValue In = Op.getOperand(0);
12415   MVT SVT = In.getSimpleValueType();
12416
12417   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12418     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12419
12420   if (Subtarget->hasFp256())
12421     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12422       return Res;
12423
12424   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12425          VT.getVectorNumElements() != SVT.getVectorNumElements());
12426   return SDValue();
12427 }
12428
12429 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12430   SDLoc DL(Op);
12431   MVT VT = Op.getSimpleValueType();
12432   SDValue In = Op.getOperand(0);
12433   MVT InVT = In.getSimpleValueType();
12434
12435   if (VT == MVT::i1) {
12436     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12437            "Invalid scalar TRUNCATE operation");
12438     if (InVT.getSizeInBits() >= 32)
12439       return SDValue();
12440     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12441     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12442   }
12443   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12444          "Invalid TRUNCATE operation");
12445
12446   // move vector to mask - truncate solution for SKX
12447   if (VT.getVectorElementType() == MVT::i1) {
12448     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12449         Subtarget->hasBWI())
12450       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12451     if ((InVT.is256BitVector() || InVT.is128BitVector())
12452         && InVT.getScalarSizeInBits() <= 16 &&
12453         Subtarget->hasBWI() && Subtarget->hasVLX())
12454       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12455     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12456         Subtarget->hasDQI())
12457       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12458     if ((InVT.is256BitVector() || InVT.is128BitVector())
12459         && InVT.getScalarSizeInBits() >= 32 &&
12460         Subtarget->hasDQI() && Subtarget->hasVLX())
12461       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12462   }
12463   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12464     if (VT.getVectorElementType().getSizeInBits() >=8)
12465       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12466
12467     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12468     unsigned NumElts = InVT.getVectorNumElements();
12469     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12470     if (InVT.getSizeInBits() < 512) {
12471       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12472       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12473       InVT = ExtVT;
12474     }
12475
12476     SDValue OneV =
12477      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12478     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12479     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12480   }
12481
12482   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12483     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12484     if (Subtarget->hasInt256()) {
12485       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12486       In = DAG.getBitcast(MVT::v8i32, In);
12487       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12488                                 ShufMask);
12489       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12490                          DAG.getIntPtrConstant(0, DL));
12491     }
12492
12493     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12494                                DAG.getIntPtrConstant(0, DL));
12495     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12496                                DAG.getIntPtrConstant(2, DL));
12497     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12498     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12499     static const int ShufMask[] = {0, 2, 4, 6};
12500     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12501   }
12502
12503   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12504     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12505     if (Subtarget->hasInt256()) {
12506       In = DAG.getBitcast(MVT::v32i8, In);
12507
12508       SmallVector<SDValue,32> pshufbMask;
12509       for (unsigned i = 0; i < 2; ++i) {
12510         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12511         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12512         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12513         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12514         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12515         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12516         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12517         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12518         for (unsigned j = 0; j < 8; ++j)
12519           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12520       }
12521       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12522       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12523       In = DAG.getBitcast(MVT::v4i64, In);
12524
12525       static const int ShufMask[] = {0,  2,  -1,  -1};
12526       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12527                                 &ShufMask[0]);
12528       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12529                        DAG.getIntPtrConstant(0, DL));
12530       return DAG.getBitcast(VT, In);
12531     }
12532
12533     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12534                                DAG.getIntPtrConstant(0, DL));
12535
12536     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12537                                DAG.getIntPtrConstant(4, DL));
12538
12539     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12540     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12541
12542     // The PSHUFB mask:
12543     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12544                                    -1, -1, -1, -1, -1, -1, -1, -1};
12545
12546     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12547     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12548     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12549
12550     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12551     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12552
12553     // The MOVLHPS Mask:
12554     static const int ShufMask2[] = {0, 1, 4, 5};
12555     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12556     return DAG.getBitcast(MVT::v8i16, res);
12557   }
12558
12559   // Handle truncation of V256 to V128 using shuffles.
12560   if (!VT.is128BitVector() || !InVT.is256BitVector())
12561     return SDValue();
12562
12563   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12564
12565   unsigned NumElems = VT.getVectorNumElements();
12566   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12567
12568   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12569   // Prepare truncation shuffle mask
12570   for (unsigned i = 0; i != NumElems; ++i)
12571     MaskVec[i] = i * 2;
12572   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12573                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12574   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12575                      DAG.getIntPtrConstant(0, DL));
12576 }
12577
12578 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12579                                            SelectionDAG &DAG) const {
12580   assert(!Op.getSimpleValueType().isVector());
12581
12582   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12583     /*IsSigned=*/ true, /*IsReplace=*/ false);
12584   SDValue FIST = Vals.first, StackSlot = Vals.second;
12585   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12586   if (!FIST.getNode()) return Op;
12587
12588   if (StackSlot.getNode())
12589     // Load the result.
12590     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12591                        FIST, StackSlot, MachinePointerInfo(),
12592                        false, false, false, 0);
12593
12594   // The node is the result.
12595   return FIST;
12596 }
12597
12598 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12599                                            SelectionDAG &DAG) const {
12600   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12601     /*IsSigned=*/ false, /*IsReplace=*/ false);
12602   SDValue FIST = Vals.first, StackSlot = Vals.second;
12603   assert(FIST.getNode() && "Unexpected failure");
12604
12605   if (StackSlot.getNode())
12606     // Load the result.
12607     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12608                        FIST, StackSlot, MachinePointerInfo(),
12609                        false, false, false, 0);
12610
12611   // The node is the result.
12612   return FIST;
12613 }
12614
12615 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12616   SDLoc DL(Op);
12617   MVT VT = Op.getSimpleValueType();
12618   SDValue In = Op.getOperand(0);
12619   MVT SVT = In.getSimpleValueType();
12620
12621   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12622
12623   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12624                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12625                                  In, DAG.getUNDEF(SVT)));
12626 }
12627
12628 /// The only differences between FABS and FNEG are the mask and the logic op.
12629 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12630 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12631   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12632          "Wrong opcode for lowering FABS or FNEG.");
12633
12634   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12635
12636   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12637   // into an FNABS. We'll lower the FABS after that if it is still in use.
12638   if (IsFABS)
12639     for (SDNode *User : Op->uses())
12640       if (User->getOpcode() == ISD::FNEG)
12641         return Op;
12642
12643   SDLoc dl(Op);
12644   MVT VT = Op.getSimpleValueType();
12645
12646   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12647   // decide if we should generate a 16-byte constant mask when we only need 4 or
12648   // 8 bytes for the scalar case.
12649
12650   MVT LogicVT;
12651   MVT EltVT;
12652   unsigned NumElts;
12653   
12654   if (VT.isVector()) {
12655     LogicVT = VT;
12656     EltVT = VT.getVectorElementType();
12657     NumElts = VT.getVectorNumElements();
12658   } else {
12659     // There are no scalar bitwise logical SSE/AVX instructions, so we
12660     // generate a 16-byte vector constant and logic op even for the scalar case.
12661     // Using a 16-byte mask allows folding the load of the mask with
12662     // the logic op, so it can save (~4 bytes) on code size.
12663     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12664     EltVT = VT;
12665     NumElts = (VT == MVT::f64) ? 2 : 4;
12666   }
12667
12668   unsigned EltBits = EltVT.getSizeInBits();
12669   LLVMContext *Context = DAG.getContext();
12670   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12671   APInt MaskElt =
12672     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12673   Constant *C = ConstantInt::get(*Context, MaskElt);
12674   C = ConstantVector::getSplat(NumElts, C);
12675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12676   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12677   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12678   SDValue Mask = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12679                              MachinePointerInfo::getConstantPool(),
12680                              false, false, false, Alignment);
12681
12682   SDValue Op0 = Op.getOperand(0);
12683   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12684   unsigned LogicOp =
12685     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12686   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12687
12688   if (VT.isVector())
12689     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12690
12691   // For the scalar case extend to a 128-bit vector, perform the logic op,
12692   // and extract the scalar result back out.
12693   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12694   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12695   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12696                      DAG.getIntPtrConstant(0, dl));
12697 }
12698
12699 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12701   LLVMContext *Context = DAG.getContext();
12702   SDValue Op0 = Op.getOperand(0);
12703   SDValue Op1 = Op.getOperand(1);
12704   SDLoc dl(Op);
12705   MVT VT = Op.getSimpleValueType();
12706   MVT SrcVT = Op1.getSimpleValueType();
12707
12708   // If second operand is smaller, extend it first.
12709   if (SrcVT.bitsLT(VT)) {
12710     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12711     SrcVT = VT;
12712   }
12713   // And if it is bigger, shrink it first.
12714   if (SrcVT.bitsGT(VT)) {
12715     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12716     SrcVT = VT;
12717   }
12718
12719   // At this point the operands and the result should have the same
12720   // type, and that won't be f80 since that is not custom lowered.
12721
12722   const fltSemantics &Sem =
12723       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12724   const unsigned SizeInBits = VT.getSizeInBits();
12725
12726   SmallVector<Constant *, 4> CV(
12727       VT == MVT::f64 ? 2 : 4,
12728       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12729
12730   // First, clear all bits but the sign bit from the second operand (sign).
12731   CV[0] = ConstantFP::get(*Context,
12732                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12733   Constant *C = ConstantVector::get(CV);
12734   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12735   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12736
12737   // Perform all logic operations as 16-byte vectors because there are no
12738   // scalar FP logic instructions in SSE. This allows load folding of the
12739   // constants into the logic instructions.
12740   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12741   SDValue Mask1 = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12742                               MachinePointerInfo::getConstantPool(),
12743                               false, false, false, 16);
12744   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12745   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12746
12747   // Next, clear the sign bit from the first operand (magnitude).
12748   // If it's a constant, we can clear it here.
12749   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12750     APFloat APF = Op0CN->getValueAPF();
12751     // If the magnitude is a positive zero, the sign bit alone is enough.
12752     if (APF.isPosZero())
12753       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12754                          DAG.getIntPtrConstant(0, dl));
12755     APF.clearSign();
12756     CV[0] = ConstantFP::get(*Context, APF);
12757   } else {
12758     CV[0] = ConstantFP::get(
12759         *Context,
12760         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12761   }
12762   C = ConstantVector::get(CV);
12763   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12764   SDValue Val = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12765                             MachinePointerInfo::getConstantPool(),
12766                             false, false, false, 16);
12767   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12768   if (!isa<ConstantFPSDNode>(Op0)) {
12769     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12770     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12771   }
12772   // OR the magnitude value with the sign bit.
12773   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12774   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12775                      DAG.getIntPtrConstant(0, dl));
12776 }
12777
12778 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12779   SDValue N0 = Op.getOperand(0);
12780   SDLoc dl(Op);
12781   MVT VT = Op.getSimpleValueType();
12782
12783   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12784   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12785                                   DAG.getConstant(1, dl, VT));
12786   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12787 }
12788
12789 // Check whether an OR'd tree is PTEST-able.
12790 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12791                                       SelectionDAG &DAG) {
12792   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12793
12794   if (!Subtarget->hasSSE41())
12795     return SDValue();
12796
12797   if (!Op->hasOneUse())
12798     return SDValue();
12799
12800   SDNode *N = Op.getNode();
12801   SDLoc DL(N);
12802
12803   SmallVector<SDValue, 8> Opnds;
12804   DenseMap<SDValue, unsigned> VecInMap;
12805   SmallVector<SDValue, 8> VecIns;
12806   EVT VT = MVT::Other;
12807
12808   // Recognize a special case where a vector is casted into wide integer to
12809   // test all 0s.
12810   Opnds.push_back(N->getOperand(0));
12811   Opnds.push_back(N->getOperand(1));
12812
12813   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12814     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12815     // BFS traverse all OR'd operands.
12816     if (I->getOpcode() == ISD::OR) {
12817       Opnds.push_back(I->getOperand(0));
12818       Opnds.push_back(I->getOperand(1));
12819       // Re-evaluate the number of nodes to be traversed.
12820       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12821       continue;
12822     }
12823
12824     // Quit if a non-EXTRACT_VECTOR_ELT
12825     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12826       return SDValue();
12827
12828     // Quit if without a constant index.
12829     SDValue Idx = I->getOperand(1);
12830     if (!isa<ConstantSDNode>(Idx))
12831       return SDValue();
12832
12833     SDValue ExtractedFromVec = I->getOperand(0);
12834     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12835     if (M == VecInMap.end()) {
12836       VT = ExtractedFromVec.getValueType();
12837       // Quit if not 128/256-bit vector.
12838       if (!VT.is128BitVector() && !VT.is256BitVector())
12839         return SDValue();
12840       // Quit if not the same type.
12841       if (VecInMap.begin() != VecInMap.end() &&
12842           VT != VecInMap.begin()->first.getValueType())
12843         return SDValue();
12844       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12845       VecIns.push_back(ExtractedFromVec);
12846     }
12847     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12848   }
12849
12850   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12851          "Not extracted from 128-/256-bit vector.");
12852
12853   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12854
12855   for (DenseMap<SDValue, unsigned>::const_iterator
12856         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12857     // Quit if not all elements are used.
12858     if (I->second != FullMask)
12859       return SDValue();
12860   }
12861
12862   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12863
12864   // Cast all vectors into TestVT for PTEST.
12865   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12866     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12867
12868   // If more than one full vectors are evaluated, OR them first before PTEST.
12869   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12870     // Each iteration will OR 2 nodes and append the result until there is only
12871     // 1 node left, i.e. the final OR'd value of all vectors.
12872     SDValue LHS = VecIns[Slot];
12873     SDValue RHS = VecIns[Slot + 1];
12874     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12875   }
12876
12877   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12878                      VecIns.back(), VecIns.back());
12879 }
12880
12881 /// \brief return true if \c Op has a use that doesn't just read flags.
12882 static bool hasNonFlagsUse(SDValue Op) {
12883   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12884        ++UI) {
12885     SDNode *User = *UI;
12886     unsigned UOpNo = UI.getOperandNo();
12887     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12888       // Look pass truncate.
12889       UOpNo = User->use_begin().getOperandNo();
12890       User = *User->use_begin();
12891     }
12892
12893     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12894         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12895       return true;
12896   }
12897   return false;
12898 }
12899
12900 /// Emit nodes that will be selected as "test Op0,Op0", or something
12901 /// equivalent.
12902 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12903                                     SelectionDAG &DAG) const {
12904   if (Op.getValueType() == MVT::i1) {
12905     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12906     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12907                        DAG.getConstant(0, dl, MVT::i8));
12908   }
12909   // CF and OF aren't always set the way we want. Determine which
12910   // of these we need.
12911   bool NeedCF = false;
12912   bool NeedOF = false;
12913   switch (X86CC) {
12914   default: break;
12915   case X86::COND_A: case X86::COND_AE:
12916   case X86::COND_B: case X86::COND_BE:
12917     NeedCF = true;
12918     break;
12919   case X86::COND_G: case X86::COND_GE:
12920   case X86::COND_L: case X86::COND_LE:
12921   case X86::COND_O: case X86::COND_NO: {
12922     // Check if we really need to set the
12923     // Overflow flag. If NoSignedWrap is present
12924     // that is not actually needed.
12925     switch (Op->getOpcode()) {
12926     case ISD::ADD:
12927     case ISD::SUB:
12928     case ISD::MUL:
12929     case ISD::SHL: {
12930       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12931       if (BinNode->Flags.hasNoSignedWrap())
12932         break;
12933     }
12934     default:
12935       NeedOF = true;
12936       break;
12937     }
12938     break;
12939   }
12940   }
12941   // See if we can use the EFLAGS value from the operand instead of
12942   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12943   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12944   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12945     // Emit a CMP with 0, which is the TEST pattern.
12946     //if (Op.getValueType() == MVT::i1)
12947     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12948     //                     DAG.getConstant(0, MVT::i1));
12949     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12950                        DAG.getConstant(0, dl, Op.getValueType()));
12951   }
12952   unsigned Opcode = 0;
12953   unsigned NumOperands = 0;
12954
12955   // Truncate operations may prevent the merge of the SETCC instruction
12956   // and the arithmetic instruction before it. Attempt to truncate the operands
12957   // of the arithmetic instruction and use a reduced bit-width instruction.
12958   bool NeedTruncation = false;
12959   SDValue ArithOp = Op;
12960   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12961     SDValue Arith = Op->getOperand(0);
12962     // Both the trunc and the arithmetic op need to have one user each.
12963     if (Arith->hasOneUse())
12964       switch (Arith.getOpcode()) {
12965         default: break;
12966         case ISD::ADD:
12967         case ISD::SUB:
12968         case ISD::AND:
12969         case ISD::OR:
12970         case ISD::XOR: {
12971           NeedTruncation = true;
12972           ArithOp = Arith;
12973         }
12974       }
12975   }
12976
12977   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12978   // which may be the result of a CAST.  We use the variable 'Op', which is the
12979   // non-casted variable when we check for possible users.
12980   switch (ArithOp.getOpcode()) {
12981   case ISD::ADD:
12982     // Due to an isel shortcoming, be conservative if this add is likely to be
12983     // selected as part of a load-modify-store instruction. When the root node
12984     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12985     // uses of other nodes in the match, such as the ADD in this case. This
12986     // leads to the ADD being left around and reselected, with the result being
12987     // two adds in the output.  Alas, even if none our users are stores, that
12988     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12989     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12990     // climbing the DAG back to the root, and it doesn't seem to be worth the
12991     // effort.
12992     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12993          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12994       if (UI->getOpcode() != ISD::CopyToReg &&
12995           UI->getOpcode() != ISD::SETCC &&
12996           UI->getOpcode() != ISD::STORE)
12997         goto default_case;
12998
12999     if (ConstantSDNode *C =
13000         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13001       // An add of one will be selected as an INC.
13002       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13003         Opcode = X86ISD::INC;
13004         NumOperands = 1;
13005         break;
13006       }
13007
13008       // An add of negative one (subtract of one) will be selected as a DEC.
13009       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13010         Opcode = X86ISD::DEC;
13011         NumOperands = 1;
13012         break;
13013       }
13014     }
13015
13016     // Otherwise use a regular EFLAGS-setting add.
13017     Opcode = X86ISD::ADD;
13018     NumOperands = 2;
13019     break;
13020   case ISD::SHL:
13021   case ISD::SRL:
13022     // If we have a constant logical shift that's only used in a comparison
13023     // against zero turn it into an equivalent AND. This allows turning it into
13024     // a TEST instruction later.
13025     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13026         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13027       EVT VT = Op.getValueType();
13028       unsigned BitWidth = VT.getSizeInBits();
13029       unsigned ShAmt = Op->getConstantOperandVal(1);
13030       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13031         break;
13032       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13033                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13034                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13035       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13036         break;
13037       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13038                                 DAG.getConstant(Mask, dl, VT));
13039       DAG.ReplaceAllUsesWith(Op, New);
13040       Op = New;
13041     }
13042     break;
13043
13044   case ISD::AND:
13045     // If the primary and result isn't used, don't bother using X86ISD::AND,
13046     // because a TEST instruction will be better.
13047     if (!hasNonFlagsUse(Op))
13048       break;
13049     // FALL THROUGH
13050   case ISD::SUB:
13051   case ISD::OR:
13052   case ISD::XOR:
13053     // Due to the ISEL shortcoming noted above, be conservative if this op is
13054     // likely to be selected as part of a load-modify-store instruction.
13055     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13056            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13057       if (UI->getOpcode() == ISD::STORE)
13058         goto default_case;
13059
13060     // Otherwise use a regular EFLAGS-setting instruction.
13061     switch (ArithOp.getOpcode()) {
13062     default: llvm_unreachable("unexpected operator!");
13063     case ISD::SUB: Opcode = X86ISD::SUB; break;
13064     case ISD::XOR: Opcode = X86ISD::XOR; break;
13065     case ISD::AND: Opcode = X86ISD::AND; break;
13066     case ISD::OR: {
13067       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13068         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13069         if (EFLAGS.getNode())
13070           return EFLAGS;
13071       }
13072       Opcode = X86ISD::OR;
13073       break;
13074     }
13075     }
13076
13077     NumOperands = 2;
13078     break;
13079   case X86ISD::ADD:
13080   case X86ISD::SUB:
13081   case X86ISD::INC:
13082   case X86ISD::DEC:
13083   case X86ISD::OR:
13084   case X86ISD::XOR:
13085   case X86ISD::AND:
13086     return SDValue(Op.getNode(), 1);
13087   default:
13088   default_case:
13089     break;
13090   }
13091
13092   // If we found that truncation is beneficial, perform the truncation and
13093   // update 'Op'.
13094   if (NeedTruncation) {
13095     EVT VT = Op.getValueType();
13096     SDValue WideVal = Op->getOperand(0);
13097     EVT WideVT = WideVal.getValueType();
13098     unsigned ConvertedOp = 0;
13099     // Use a target machine opcode to prevent further DAGCombine
13100     // optimizations that may separate the arithmetic operations
13101     // from the setcc node.
13102     switch (WideVal.getOpcode()) {
13103       default: break;
13104       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13105       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13106       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13107       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13108       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13109     }
13110
13111     if (ConvertedOp) {
13112       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13113       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13114         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13115         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13116         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13117       }
13118     }
13119   }
13120
13121   if (Opcode == 0)
13122     // Emit a CMP with 0, which is the TEST pattern.
13123     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13124                        DAG.getConstant(0, dl, Op.getValueType()));
13125
13126   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13127   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13128
13129   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13130   DAG.ReplaceAllUsesWith(Op, New);
13131   return SDValue(New.getNode(), 1);
13132 }
13133
13134 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13135 /// equivalent.
13136 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13137                                    SDLoc dl, SelectionDAG &DAG) const {
13138   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13139     if (C->getAPIntValue() == 0)
13140       return EmitTest(Op0, X86CC, dl, DAG);
13141
13142      if (Op0.getValueType() == MVT::i1)
13143        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13144   }
13145
13146   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13147        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13148     // Do the comparison at i32 if it's smaller, besides the Atom case.
13149     // This avoids subregister aliasing issues. Keep the smaller reference
13150     // if we're optimizing for size, however, as that'll allow better folding
13151     // of memory operations.
13152     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13153         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13154             Attribute::MinSize) &&
13155         !Subtarget->isAtom()) {
13156       unsigned ExtendOp =
13157           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13158       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13159       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13160     }
13161     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13162     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13163     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13164                               Op0, Op1);
13165     return SDValue(Sub.getNode(), 1);
13166   }
13167   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13168 }
13169
13170 /// Convert a comparison if required by the subtarget.
13171 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13172                                                  SelectionDAG &DAG) const {
13173   // If the subtarget does not support the FUCOMI instruction, floating-point
13174   // comparisons have to be converted.
13175   if (Subtarget->hasCMov() ||
13176       Cmp.getOpcode() != X86ISD::CMP ||
13177       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13178       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13179     return Cmp;
13180
13181   // The instruction selector will select an FUCOM instruction instead of
13182   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13183   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13184   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13185   SDLoc dl(Cmp);
13186   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13187   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13188   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13189                             DAG.getConstant(8, dl, MVT::i8));
13190   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13191   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13192 }
13193
13194 /// The minimum architected relative accuracy is 2^-12. We need one
13195 /// Newton-Raphson step to have a good float result (24 bits of precision).
13196 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13197                                             DAGCombinerInfo &DCI,
13198                                             unsigned &RefinementSteps,
13199                                             bool &UseOneConstNR) const {
13200   EVT VT = Op.getValueType();
13201   const char *RecipOp;
13202
13203   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13204   // TODO: Add support for AVX512 (v16f32).
13205   // It is likely not profitable to do this for f64 because a double-precision
13206   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13207   // instructions: convert to single, rsqrtss, convert back to double, refine
13208   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13209   // along with FMA, this could be a throughput win.
13210   if (VT == MVT::f32 && Subtarget->hasSSE1())
13211     RecipOp = "sqrtf";
13212   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13213            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13214     RecipOp = "vec-sqrtf";
13215   else
13216     return SDValue();
13217
13218   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13219   if (!Recips.isEnabled(RecipOp))
13220     return SDValue();
13221
13222   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13223   UseOneConstNR = false;
13224   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13225 }
13226
13227 /// The minimum architected relative accuracy is 2^-12. We need one
13228 /// Newton-Raphson step to have a good float result (24 bits of precision).
13229 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13230                                             DAGCombinerInfo &DCI,
13231                                             unsigned &RefinementSteps) const {
13232   EVT VT = Op.getValueType();
13233   const char *RecipOp;
13234
13235   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13236   // TODO: Add support for AVX512 (v16f32).
13237   // It is likely not profitable to do this for f64 because a double-precision
13238   // reciprocal estimate with refinement on x86 prior to FMA requires
13239   // 15 instructions: convert to single, rcpss, convert back to double, refine
13240   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13241   // along with FMA, this could be a throughput win.
13242   if (VT == MVT::f32 && Subtarget->hasSSE1())
13243     RecipOp = "divf";
13244   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13245            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13246     RecipOp = "vec-divf";
13247   else
13248     return SDValue();
13249
13250   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13251   if (!Recips.isEnabled(RecipOp))
13252     return SDValue();
13253
13254   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13255   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13256 }
13257
13258 /// If we have at least two divisions that use the same divisor, convert to
13259 /// multplication by a reciprocal. This may need to be adjusted for a given
13260 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13261 /// This is because we still need one division to calculate the reciprocal and
13262 /// then we need two multiplies by that reciprocal as replacements for the
13263 /// original divisions.
13264 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13265   return NumUsers > 1;
13266 }
13267
13268 static bool isAllOnes(SDValue V) {
13269   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13270   return C && C->isAllOnesValue();
13271 }
13272
13273 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13274 /// if it's possible.
13275 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13276                                      SDLoc dl, SelectionDAG &DAG) const {
13277   SDValue Op0 = And.getOperand(0);
13278   SDValue Op1 = And.getOperand(1);
13279   if (Op0.getOpcode() == ISD::TRUNCATE)
13280     Op0 = Op0.getOperand(0);
13281   if (Op1.getOpcode() == ISD::TRUNCATE)
13282     Op1 = Op1.getOperand(0);
13283
13284   SDValue LHS, RHS;
13285   if (Op1.getOpcode() == ISD::SHL)
13286     std::swap(Op0, Op1);
13287   if (Op0.getOpcode() == ISD::SHL) {
13288     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13289       if (And00C->getZExtValue() == 1) {
13290         // If we looked past a truncate, check that it's only truncating away
13291         // known zeros.
13292         unsigned BitWidth = Op0.getValueSizeInBits();
13293         unsigned AndBitWidth = And.getValueSizeInBits();
13294         if (BitWidth > AndBitWidth) {
13295           APInt Zeros, Ones;
13296           DAG.computeKnownBits(Op0, Zeros, Ones);
13297           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13298             return SDValue();
13299         }
13300         LHS = Op1;
13301         RHS = Op0.getOperand(1);
13302       }
13303   } else if (Op1.getOpcode() == ISD::Constant) {
13304     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13305     uint64_t AndRHSVal = AndRHS->getZExtValue();
13306     SDValue AndLHS = Op0;
13307
13308     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13309       LHS = AndLHS.getOperand(0);
13310       RHS = AndLHS.getOperand(1);
13311     }
13312
13313     // Use BT if the immediate can't be encoded in a TEST instruction.
13314     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13315       LHS = AndLHS;
13316       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13317     }
13318   }
13319
13320   if (LHS.getNode()) {
13321     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13322     // instruction.  Since the shift amount is in-range-or-undefined, we know
13323     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13324     // the encoding for the i16 version is larger than the i32 version.
13325     // Also promote i16 to i32 for performance / code size reason.
13326     if (LHS.getValueType() == MVT::i8 ||
13327         LHS.getValueType() == MVT::i16)
13328       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13329
13330     // If the operand types disagree, extend the shift amount to match.  Since
13331     // BT ignores high bits (like shifts) we can use anyextend.
13332     if (LHS.getValueType() != RHS.getValueType())
13333       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13334
13335     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13336     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13337     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13338                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13339   }
13340
13341   return SDValue();
13342 }
13343
13344 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13345 /// mask CMPs.
13346 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13347                               SDValue &Op1) {
13348   unsigned SSECC;
13349   bool Swap = false;
13350
13351   // SSE Condition code mapping:
13352   //  0 - EQ
13353   //  1 - LT
13354   //  2 - LE
13355   //  3 - UNORD
13356   //  4 - NEQ
13357   //  5 - NLT
13358   //  6 - NLE
13359   //  7 - ORD
13360   switch (SetCCOpcode) {
13361   default: llvm_unreachable("Unexpected SETCC condition");
13362   case ISD::SETOEQ:
13363   case ISD::SETEQ:  SSECC = 0; break;
13364   case ISD::SETOGT:
13365   case ISD::SETGT:  Swap = true; // Fallthrough
13366   case ISD::SETLT:
13367   case ISD::SETOLT: SSECC = 1; break;
13368   case ISD::SETOGE:
13369   case ISD::SETGE:  Swap = true; // Fallthrough
13370   case ISD::SETLE:
13371   case ISD::SETOLE: SSECC = 2; break;
13372   case ISD::SETUO:  SSECC = 3; break;
13373   case ISD::SETUNE:
13374   case ISD::SETNE:  SSECC = 4; break;
13375   case ISD::SETULE: Swap = true; // Fallthrough
13376   case ISD::SETUGE: SSECC = 5; break;
13377   case ISD::SETULT: Swap = true; // Fallthrough
13378   case ISD::SETUGT: SSECC = 6; break;
13379   case ISD::SETO:   SSECC = 7; break;
13380   case ISD::SETUEQ:
13381   case ISD::SETONE: SSECC = 8; break;
13382   }
13383   if (Swap)
13384     std::swap(Op0, Op1);
13385
13386   return SSECC;
13387 }
13388
13389 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13390 // ones, and then concatenate the result back.
13391 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13392   MVT VT = Op.getSimpleValueType();
13393
13394   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13395          "Unsupported value type for operation");
13396
13397   unsigned NumElems = VT.getVectorNumElements();
13398   SDLoc dl(Op);
13399   SDValue CC = Op.getOperand(2);
13400
13401   // Extract the LHS vectors
13402   SDValue LHS = Op.getOperand(0);
13403   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13404   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13405
13406   // Extract the RHS vectors
13407   SDValue RHS = Op.getOperand(1);
13408   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13409   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13410
13411   // Issue the operation on the smaller types and concatenate the result back
13412   MVT EltVT = VT.getVectorElementType();
13413   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13414   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13415                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13416                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13417 }
13418
13419 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13420   SDValue Op0 = Op.getOperand(0);
13421   SDValue Op1 = Op.getOperand(1);
13422   SDValue CC = Op.getOperand(2);
13423   MVT VT = Op.getSimpleValueType();
13424   SDLoc dl(Op);
13425
13426   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13427          "Unexpected type for boolean compare operation");
13428   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13429   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13430                                DAG.getConstant(-1, dl, VT));
13431   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13432                                DAG.getConstant(-1, dl, VT));
13433   switch (SetCCOpcode) {
13434   default: llvm_unreachable("Unexpected SETCC condition");
13435   case ISD::SETEQ:
13436     // (x == y) -> ~(x ^ y)
13437     return DAG.getNode(ISD::XOR, dl, VT,
13438                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13439                        DAG.getConstant(-1, dl, VT));
13440   case ISD::SETNE:
13441     // (x != y) -> (x ^ y)
13442     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13443   case ISD::SETUGT:
13444   case ISD::SETGT:
13445     // (x > y) -> (x & ~y)
13446     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13447   case ISD::SETULT:
13448   case ISD::SETLT:
13449     // (x < y) -> (~x & y)
13450     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13451   case ISD::SETULE:
13452   case ISD::SETLE:
13453     // (x <= y) -> (~x | y)
13454     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13455   case ISD::SETUGE:
13456   case ISD::SETGE:
13457     // (x >=y) -> (x | ~y)
13458     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13459   }
13460 }
13461
13462 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13463                                      const X86Subtarget *Subtarget) {
13464   SDValue Op0 = Op.getOperand(0);
13465   SDValue Op1 = Op.getOperand(1);
13466   SDValue CC = Op.getOperand(2);
13467   MVT VT = Op.getSimpleValueType();
13468   SDLoc dl(Op);
13469
13470   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13471          Op.getValueType().getScalarType() == MVT::i1 &&
13472          "Cannot set masked compare for this operation");
13473
13474   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13475   unsigned  Opc = 0;
13476   bool Unsigned = false;
13477   bool Swap = false;
13478   unsigned SSECC;
13479   switch (SetCCOpcode) {
13480   default: llvm_unreachable("Unexpected SETCC condition");
13481   case ISD::SETNE:  SSECC = 4; break;
13482   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13483   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13484   case ISD::SETLT:  Swap = true; //fall-through
13485   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13486   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13487   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13488   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13489   case ISD::SETULE: Unsigned = true; //fall-through
13490   case ISD::SETLE:  SSECC = 2; break;
13491   }
13492
13493   if (Swap)
13494     std::swap(Op0, Op1);
13495   if (Opc)
13496     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13497   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13498   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13499                      DAG.getConstant(SSECC, dl, MVT::i8));
13500 }
13501
13502 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13503 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13504 /// return an empty value.
13505 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13506 {
13507   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13508   if (!BV)
13509     return SDValue();
13510
13511   MVT VT = Op1.getSimpleValueType();
13512   MVT EVT = VT.getVectorElementType();
13513   unsigned n = VT.getVectorNumElements();
13514   SmallVector<SDValue, 8> ULTOp1;
13515
13516   for (unsigned i = 0; i < n; ++i) {
13517     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13518     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13519       return SDValue();
13520
13521     // Avoid underflow.
13522     APInt Val = Elt->getAPIntValue();
13523     if (Val == 0)
13524       return SDValue();
13525
13526     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13527   }
13528
13529   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13530 }
13531
13532 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13533                            SelectionDAG &DAG) {
13534   SDValue Op0 = Op.getOperand(0);
13535   SDValue Op1 = Op.getOperand(1);
13536   SDValue CC = Op.getOperand(2);
13537   MVT VT = Op.getSimpleValueType();
13538   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13539   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13540   SDLoc dl(Op);
13541
13542   if (isFP) {
13543 #ifndef NDEBUG
13544     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13545     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13546 #endif
13547
13548     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13549     unsigned Opc = X86ISD::CMPP;
13550     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13551       assert(VT.getVectorNumElements() <= 16);
13552       Opc = X86ISD::CMPM;
13553     }
13554     // In the two special cases we can't handle, emit two comparisons.
13555     if (SSECC == 8) {
13556       unsigned CC0, CC1;
13557       unsigned CombineOpc;
13558       if (SetCCOpcode == ISD::SETUEQ) {
13559         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13560       } else {
13561         assert(SetCCOpcode == ISD::SETONE);
13562         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13563       }
13564
13565       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13566                                  DAG.getConstant(CC0, dl, MVT::i8));
13567       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13568                                  DAG.getConstant(CC1, dl, MVT::i8));
13569       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13570     }
13571     // Handle all other FP comparisons here.
13572     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13573                        DAG.getConstant(SSECC, dl, MVT::i8));
13574   }
13575
13576   MVT VTOp0 = Op0.getSimpleValueType();
13577   assert(VTOp0 == Op1.getSimpleValueType() &&
13578          "Expected operands with same type!");
13579   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
13580          "Invalid number of packed elements for source and destination!");
13581
13582   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
13583     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
13584     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
13585     // legalizer firstly checks if the first operand in input to the setcc has
13586     // a legal type. If so, then it promotes the return type to that same type.
13587     // Otherwise, the return type is promoted to the 'next legal type' which,
13588     // for a vector of MVT::i1 is always a 128-bit integer vector type.
13589     //
13590     // We reach this code only if the following two conditions are met:
13591     // 1. Both return type and operand type have been promoted to wider types
13592     //    by the type legalizer.
13593     // 2. The original operand type has been promoted to a 256-bit vector.
13594     //
13595     // Note that condition 2. only applies for AVX targets.
13596     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
13597     return DAG.getZExtOrTrunc(NewOp, dl, VT);
13598   }
13599
13600   // The non-AVX512 code below works under the assumption that source and
13601   // destination types are the same.
13602   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
13603          "Value types for source and destination must be the same!");
13604
13605   // Break 256-bit integer vector compare into smaller ones.
13606   if (VT.is256BitVector() && !Subtarget->hasInt256())
13607     return Lower256IntVSETCC(Op, DAG);
13608
13609   EVT OpVT = Op1.getValueType();
13610   if (OpVT.getVectorElementType() == MVT::i1)
13611     return LowerBoolVSETCC_AVX512(Op, DAG);
13612
13613   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13614   if (Subtarget->hasAVX512()) {
13615     if (Op1.getValueType().is512BitVector() ||
13616         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13617         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13618       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13619
13620     // In AVX-512 architecture setcc returns mask with i1 elements,
13621     // But there is no compare instruction for i8 and i16 elements in KNL.
13622     // We are not talking about 512-bit operands in this case, these
13623     // types are illegal.
13624     if (MaskResult &&
13625         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13626          OpVT.getVectorElementType().getSizeInBits() >= 8))
13627       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13628                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13629   }
13630
13631   // We are handling one of the integer comparisons here.  Since SSE only has
13632   // GT and EQ comparisons for integer, swapping operands and multiple
13633   // operations may be required for some comparisons.
13634   unsigned Opc;
13635   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13636   bool Subus = false;
13637
13638   switch (SetCCOpcode) {
13639   default: llvm_unreachable("Unexpected SETCC condition");
13640   case ISD::SETNE:  Invert = true;
13641   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13642   case ISD::SETLT:  Swap = true;
13643   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13644   case ISD::SETGE:  Swap = true;
13645   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13646                     Invert = true; break;
13647   case ISD::SETULT: Swap = true;
13648   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13649                     FlipSigns = true; break;
13650   case ISD::SETUGE: Swap = true;
13651   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13652                     FlipSigns = true; Invert = true; break;
13653   }
13654
13655   // Special case: Use min/max operations for SETULE/SETUGE
13656   MVT VET = VT.getVectorElementType();
13657   bool hasMinMax =
13658        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13659     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13660
13661   if (hasMinMax) {
13662     switch (SetCCOpcode) {
13663     default: break;
13664     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13665     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13666     }
13667
13668     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13669   }
13670
13671   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13672   if (!MinMax && hasSubus) {
13673     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13674     // Op0 u<= Op1:
13675     //   t = psubus Op0, Op1
13676     //   pcmpeq t, <0..0>
13677     switch (SetCCOpcode) {
13678     default: break;
13679     case ISD::SETULT: {
13680       // If the comparison is against a constant we can turn this into a
13681       // setule.  With psubus, setule does not require a swap.  This is
13682       // beneficial because the constant in the register is no longer
13683       // destructed as the destination so it can be hoisted out of a loop.
13684       // Only do this pre-AVX since vpcmp* is no longer destructive.
13685       if (Subtarget->hasAVX())
13686         break;
13687       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13688       if (ULEOp1.getNode()) {
13689         Op1 = ULEOp1;
13690         Subus = true; Invert = false; Swap = false;
13691       }
13692       break;
13693     }
13694     // Psubus is better than flip-sign because it requires no inversion.
13695     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13696     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13697     }
13698
13699     if (Subus) {
13700       Opc = X86ISD::SUBUS;
13701       FlipSigns = false;
13702     }
13703   }
13704
13705   if (Swap)
13706     std::swap(Op0, Op1);
13707
13708   // Check that the operation in question is available (most are plain SSE2,
13709   // but PCMPGTQ and PCMPEQQ have different requirements).
13710   if (VT == MVT::v2i64) {
13711     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13712       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13713
13714       // First cast everything to the right type.
13715       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13716       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13717
13718       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13719       // bits of the inputs before performing those operations. The lower
13720       // compare is always unsigned.
13721       SDValue SB;
13722       if (FlipSigns) {
13723         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13724       } else {
13725         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13726         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13727         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13728                          Sign, Zero, Sign, Zero);
13729       }
13730       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13731       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13732
13733       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13734       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13735       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13736
13737       // Create masks for only the low parts/high parts of the 64 bit integers.
13738       static const int MaskHi[] = { 1, 1, 3, 3 };
13739       static const int MaskLo[] = { 0, 0, 2, 2 };
13740       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13741       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13742       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13743
13744       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13745       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13746
13747       if (Invert)
13748         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13749
13750       return DAG.getBitcast(VT, Result);
13751     }
13752
13753     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13754       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13755       // pcmpeqd + pshufd + pand.
13756       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13757
13758       // First cast everything to the right type.
13759       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13760       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13761
13762       // Do the compare.
13763       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13764
13765       // Make sure the lower and upper halves are both all-ones.
13766       static const int Mask[] = { 1, 0, 3, 2 };
13767       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13768       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13769
13770       if (Invert)
13771         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13772
13773       return DAG.getBitcast(VT, Result);
13774     }
13775   }
13776
13777   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13778   // bits of the inputs before performing those operations.
13779   if (FlipSigns) {
13780     EVT EltVT = VT.getVectorElementType();
13781     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13782                                  VT);
13783     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13784     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13785   }
13786
13787   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13788
13789   // If the logical-not of the result is required, perform that now.
13790   if (Invert)
13791     Result = DAG.getNOT(dl, Result, VT);
13792
13793   if (MinMax)
13794     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13795
13796   if (Subus)
13797     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13798                          getZeroVector(VT, Subtarget, DAG, dl));
13799
13800   return Result;
13801 }
13802
13803 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13804
13805   MVT VT = Op.getSimpleValueType();
13806
13807   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13808
13809   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13810          && "SetCC type must be 8-bit or 1-bit integer");
13811   SDValue Op0 = Op.getOperand(0);
13812   SDValue Op1 = Op.getOperand(1);
13813   SDLoc dl(Op);
13814   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13815
13816   // Optimize to BT if possible.
13817   // Lower (X & (1 << N)) == 0 to BT(X, N).
13818   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13819   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13820   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13821       Op1.getOpcode() == ISD::Constant &&
13822       cast<ConstantSDNode>(Op1)->isNullValue() &&
13823       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13824     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13825     if (NewSetCC.getNode()) {
13826       if (VT == MVT::i1)
13827         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13828       return NewSetCC;
13829     }
13830   }
13831
13832   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13833   // these.
13834   if (Op1.getOpcode() == ISD::Constant &&
13835       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13836        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13837       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13838
13839     // If the input is a setcc, then reuse the input setcc or use a new one with
13840     // the inverted condition.
13841     if (Op0.getOpcode() == X86ISD::SETCC) {
13842       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13843       bool Invert = (CC == ISD::SETNE) ^
13844         cast<ConstantSDNode>(Op1)->isNullValue();
13845       if (!Invert)
13846         return Op0;
13847
13848       CCode = X86::GetOppositeBranchCondition(CCode);
13849       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13850                                   DAG.getConstant(CCode, dl, MVT::i8),
13851                                   Op0.getOperand(1));
13852       if (VT == MVT::i1)
13853         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13854       return SetCC;
13855     }
13856   }
13857   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13858       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13859       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13860
13861     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13862     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13863   }
13864
13865   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13866   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13867   if (X86CC == X86::COND_INVALID)
13868     return SDValue();
13869
13870   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13871   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13872   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13873                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13874   if (VT == MVT::i1)
13875     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13876   return SetCC;
13877 }
13878
13879 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13880 static bool isX86LogicalCmp(SDValue Op) {
13881   unsigned Opc = Op.getNode()->getOpcode();
13882   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13883       Opc == X86ISD::SAHF)
13884     return true;
13885   if (Op.getResNo() == 1 &&
13886       (Opc == X86ISD::ADD ||
13887        Opc == X86ISD::SUB ||
13888        Opc == X86ISD::ADC ||
13889        Opc == X86ISD::SBB ||
13890        Opc == X86ISD::SMUL ||
13891        Opc == X86ISD::UMUL ||
13892        Opc == X86ISD::INC ||
13893        Opc == X86ISD::DEC ||
13894        Opc == X86ISD::OR ||
13895        Opc == X86ISD::XOR ||
13896        Opc == X86ISD::AND))
13897     return true;
13898
13899   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13900     return true;
13901
13902   return false;
13903 }
13904
13905 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13906   if (V.getOpcode() != ISD::TRUNCATE)
13907     return false;
13908
13909   SDValue VOp0 = V.getOperand(0);
13910   unsigned InBits = VOp0.getValueSizeInBits();
13911   unsigned Bits = V.getValueSizeInBits();
13912   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13913 }
13914
13915 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13916   bool addTest = true;
13917   SDValue Cond  = Op.getOperand(0);
13918   SDValue Op1 = Op.getOperand(1);
13919   SDValue Op2 = Op.getOperand(2);
13920   SDLoc DL(Op);
13921   EVT VT = Op1.getValueType();
13922   SDValue CC;
13923
13924   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13925   // are available or VBLENDV if AVX is available.
13926   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13927   if (Cond.getOpcode() == ISD::SETCC &&
13928       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13929        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13930       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13931     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13932     int SSECC = translateX86FSETCC(
13933         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13934
13935     if (SSECC != 8) {
13936       if (Subtarget->hasAVX512()) {
13937         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13938                                   DAG.getConstant(SSECC, DL, MVT::i8));
13939         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13940       }
13941
13942       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13943                                 DAG.getConstant(SSECC, DL, MVT::i8));
13944
13945       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13946       // of 3 logic instructions for size savings and potentially speed.
13947       // Unfortunately, there is no scalar form of VBLENDV.
13948
13949       // If either operand is a constant, don't try this. We can expect to
13950       // optimize away at least one of the logic instructions later in that
13951       // case, so that sequence would be faster than a variable blend.
13952
13953       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13954       // uses XMM0 as the selection register. That may need just as many
13955       // instructions as the AND/ANDN/OR sequence due to register moves, so
13956       // don't bother.
13957
13958       if (Subtarget->hasAVX() &&
13959           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13960
13961         // Convert to vectors, do a VSELECT, and convert back to scalar.
13962         // All of the conversions should be optimized away.
13963
13964         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13965         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13966         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13967         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13968
13969         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13970         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13971
13972         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13973
13974         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13975                            VSel, DAG.getIntPtrConstant(0, DL));
13976       }
13977       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13978       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13979       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13980     }
13981   }
13982
13983     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13984       SDValue Op1Scalar;
13985       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13986         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13987       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13988         Op1Scalar = Op1.getOperand(0);
13989       SDValue Op2Scalar;
13990       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13991         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13992       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13993         Op2Scalar = Op2.getOperand(0);
13994       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13995         SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13996                                         Op1Scalar.getValueType(),
13997                                         Cond, Op1Scalar, Op2Scalar);
13998         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13999           return DAG.getBitcast(VT, newSelect);
14000         SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14001         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14002                            DAG.getIntPtrConstant(0, DL));
14003     }
14004   }
14005
14006   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14007     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14008     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14009                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14010     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14011                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14012     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14013                                     Cond, Op1, Op2);
14014     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14015   }
14016
14017   if (Cond.getOpcode() == ISD::SETCC) {
14018     SDValue NewCond = LowerSETCC(Cond, DAG);
14019     if (NewCond.getNode())
14020       Cond = NewCond;
14021   }
14022
14023   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14024   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14025   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14026   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14027   if (Cond.getOpcode() == X86ISD::SETCC &&
14028       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14029       isZero(Cond.getOperand(1).getOperand(1))) {
14030     SDValue Cmp = Cond.getOperand(1);
14031
14032     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14033
14034     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14035         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14036       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14037
14038       SDValue CmpOp0 = Cmp.getOperand(0);
14039       // Apply further optimizations for special cases
14040       // (select (x != 0), -1, 0) -> neg & sbb
14041       // (select (x == 0), 0, -1) -> neg & sbb
14042       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14043         if (YC->isNullValue() &&
14044             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14045           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14046           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14047                                     DAG.getConstant(0, DL,
14048                                                     CmpOp0.getValueType()),
14049                                     CmpOp0);
14050           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14051                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14052                                     SDValue(Neg.getNode(), 1));
14053           return Res;
14054         }
14055
14056       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14057                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14058       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14059
14060       SDValue Res =   // Res = 0 or -1.
14061         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14062                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14063
14064       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14065         Res = DAG.getNOT(DL, Res, Res.getValueType());
14066
14067       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14068       if (!N2C || !N2C->isNullValue())
14069         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14070       return Res;
14071     }
14072   }
14073
14074   // Look past (and (setcc_carry (cmp ...)), 1).
14075   if (Cond.getOpcode() == ISD::AND &&
14076       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14077     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14078     if (C && C->getAPIntValue() == 1)
14079       Cond = Cond.getOperand(0);
14080   }
14081
14082   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14083   // setting operand in place of the X86ISD::SETCC.
14084   unsigned CondOpcode = Cond.getOpcode();
14085   if (CondOpcode == X86ISD::SETCC ||
14086       CondOpcode == X86ISD::SETCC_CARRY) {
14087     CC = Cond.getOperand(0);
14088
14089     SDValue Cmp = Cond.getOperand(1);
14090     unsigned Opc = Cmp.getOpcode();
14091     MVT VT = Op.getSimpleValueType();
14092
14093     bool IllegalFPCMov = false;
14094     if (VT.isFloatingPoint() && !VT.isVector() &&
14095         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14096       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14097
14098     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14099         Opc == X86ISD::BT) { // FIXME
14100       Cond = Cmp;
14101       addTest = false;
14102     }
14103   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14104              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14105              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14106               Cond.getOperand(0).getValueType() != MVT::i8)) {
14107     SDValue LHS = Cond.getOperand(0);
14108     SDValue RHS = Cond.getOperand(1);
14109     unsigned X86Opcode;
14110     unsigned X86Cond;
14111     SDVTList VTs;
14112     switch (CondOpcode) {
14113     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14114     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14115     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14116     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14117     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14118     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14119     default: llvm_unreachable("unexpected overflowing operator");
14120     }
14121     if (CondOpcode == ISD::UMULO)
14122       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14123                           MVT::i32);
14124     else
14125       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14126
14127     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14128
14129     if (CondOpcode == ISD::UMULO)
14130       Cond = X86Op.getValue(2);
14131     else
14132       Cond = X86Op.getValue(1);
14133
14134     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14135     addTest = false;
14136   }
14137
14138   if (addTest) {
14139     // Look pass the truncate if the high bits are known zero.
14140     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14141         Cond = Cond.getOperand(0);
14142
14143     // We know the result of AND is compared against zero. Try to match
14144     // it to BT.
14145     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14146       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14147       if (NewSetCC.getNode()) {
14148         CC = NewSetCC.getOperand(0);
14149         Cond = NewSetCC.getOperand(1);
14150         addTest = false;
14151       }
14152     }
14153   }
14154
14155   if (addTest) {
14156     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14157     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14158   }
14159
14160   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14161   // a <  b ?  0 : -1 -> RES = setcc_carry
14162   // a >= b ? -1 :  0 -> RES = setcc_carry
14163   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14164   if (Cond.getOpcode() == X86ISD::SUB) {
14165     Cond = ConvertCmpIfNecessary(Cond, DAG);
14166     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14167
14168     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14169         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14170       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14171                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14172                                 Cond);
14173       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14174         return DAG.getNOT(DL, Res, Res.getValueType());
14175       return Res;
14176     }
14177   }
14178
14179   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14180   // widen the cmov and push the truncate through. This avoids introducing a new
14181   // branch during isel and doesn't add any extensions.
14182   if (Op.getValueType() == MVT::i8 &&
14183       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14184     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14185     if (T1.getValueType() == T2.getValueType() &&
14186         // Blacklist CopyFromReg to avoid partial register stalls.
14187         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14188       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14189       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14190       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14191     }
14192   }
14193
14194   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14195   // condition is true.
14196   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14197   SDValue Ops[] = { Op2, Op1, CC, Cond };
14198   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14199 }
14200
14201 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14202                                        const X86Subtarget *Subtarget,
14203                                        SelectionDAG &DAG) {
14204   MVT VT = Op->getSimpleValueType(0);
14205   SDValue In = Op->getOperand(0);
14206   MVT InVT = In.getSimpleValueType();
14207   MVT VTElt = VT.getVectorElementType();
14208   MVT InVTElt = InVT.getVectorElementType();
14209   SDLoc dl(Op);
14210
14211   // SKX processor
14212   if ((InVTElt == MVT::i1) &&
14213       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14214         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14215
14216        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14217         VTElt.getSizeInBits() <= 16)) ||
14218
14219        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14220         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14221
14222        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14223         VTElt.getSizeInBits() >= 32))))
14224     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14225
14226   unsigned int NumElts = VT.getVectorNumElements();
14227
14228   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14229     return SDValue();
14230
14231   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14232     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14233       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14234     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14235   }
14236
14237   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14238   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14239   SDValue NegOne =
14240    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14241                    ExtVT);
14242   SDValue Zero =
14243    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14244
14245   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14246   if (VT.is512BitVector())
14247     return V;
14248   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14249 }
14250
14251 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14252                                              const X86Subtarget *Subtarget,
14253                                              SelectionDAG &DAG) {
14254   SDValue In = Op->getOperand(0);
14255   MVT VT = Op->getSimpleValueType(0);
14256   MVT InVT = In.getSimpleValueType();
14257   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14258
14259   MVT InSVT = InVT.getScalarType();
14260   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14261
14262   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14263     return SDValue();
14264   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14265     return SDValue();
14266
14267   SDLoc dl(Op);
14268
14269   // SSE41 targets can use the pmovsx* instructions directly.
14270   if (Subtarget->hasSSE41())
14271     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14272
14273   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14274   SDValue Curr = In;
14275   MVT CurrVT = InVT;
14276
14277   // As SRAI is only available on i16/i32 types, we expand only up to i32
14278   // and handle i64 separately.
14279   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14280     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14281     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14282     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14283     Curr = DAG.getBitcast(CurrVT, Curr);
14284   }
14285
14286   SDValue SignExt = Curr;
14287   if (CurrVT != InVT) {
14288     unsigned SignExtShift =
14289         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14290     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14291                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14292   }
14293
14294   if (CurrVT == VT)
14295     return SignExt;
14296
14297   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14298     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14299                                DAG.getConstant(31, dl, MVT::i8));
14300     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14301     return DAG.getBitcast(VT, Ext);
14302   }
14303
14304   return SDValue();
14305 }
14306
14307 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14308                                 SelectionDAG &DAG) {
14309   MVT VT = Op->getSimpleValueType(0);
14310   SDValue In = Op->getOperand(0);
14311   MVT InVT = In.getSimpleValueType();
14312   SDLoc dl(Op);
14313
14314   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14315     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14316
14317   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14318       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14319       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14320     return SDValue();
14321
14322   if (Subtarget->hasInt256())
14323     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14324
14325   // Optimize vectors in AVX mode
14326   // Sign extend  v8i16 to v8i32 and
14327   //              v4i32 to v4i64
14328   //
14329   // Divide input vector into two parts
14330   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14331   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14332   // concat the vectors to original VT
14333
14334   unsigned NumElems = InVT.getVectorNumElements();
14335   SDValue Undef = DAG.getUNDEF(InVT);
14336
14337   SmallVector<int,8> ShufMask1(NumElems, -1);
14338   for (unsigned i = 0; i != NumElems/2; ++i)
14339     ShufMask1[i] = i;
14340
14341   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14342
14343   SmallVector<int,8> ShufMask2(NumElems, -1);
14344   for (unsigned i = 0; i != NumElems/2; ++i)
14345     ShufMask2[i] = i + NumElems/2;
14346
14347   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14348
14349   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14350                                 VT.getVectorNumElements()/2);
14351
14352   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14353   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14354
14355   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14356 }
14357
14358 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14359 // may emit an illegal shuffle but the expansion is still better than scalar
14360 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14361 // we'll emit a shuffle and a arithmetic shift.
14362 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14363 // TODO: It is possible to support ZExt by zeroing the undef values during
14364 // the shuffle phase or after the shuffle.
14365 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14366                                  SelectionDAG &DAG) {
14367   MVT RegVT = Op.getSimpleValueType();
14368   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14369   assert(RegVT.isInteger() &&
14370          "We only custom lower integer vector sext loads.");
14371
14372   // Nothing useful we can do without SSE2 shuffles.
14373   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14374
14375   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14376   SDLoc dl(Ld);
14377   EVT MemVT = Ld->getMemoryVT();
14378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14379   unsigned RegSz = RegVT.getSizeInBits();
14380
14381   ISD::LoadExtType Ext = Ld->getExtensionType();
14382
14383   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14384          && "Only anyext and sext are currently implemented.");
14385   assert(MemVT != RegVT && "Cannot extend to the same type");
14386   assert(MemVT.isVector() && "Must load a vector from memory");
14387
14388   unsigned NumElems = RegVT.getVectorNumElements();
14389   unsigned MemSz = MemVT.getSizeInBits();
14390   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14391
14392   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14393     // The only way in which we have a legal 256-bit vector result but not the
14394     // integer 256-bit operations needed to directly lower a sextload is if we
14395     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14396     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14397     // correctly legalized. We do this late to allow the canonical form of
14398     // sextload to persist throughout the rest of the DAG combiner -- it wants
14399     // to fold together any extensions it can, and so will fuse a sign_extend
14400     // of an sextload into a sextload targeting a wider value.
14401     SDValue Load;
14402     if (MemSz == 128) {
14403       // Just switch this to a normal load.
14404       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14405                                        "it must be a legal 128-bit vector "
14406                                        "type!");
14407       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14408                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14409                   Ld->isInvariant(), Ld->getAlignment());
14410     } else {
14411       assert(MemSz < 128 &&
14412              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14413       // Do an sext load to a 128-bit vector type. We want to use the same
14414       // number of elements, but elements half as wide. This will end up being
14415       // recursively lowered by this routine, but will succeed as we definitely
14416       // have all the necessary features if we're using AVX1.
14417       EVT HalfEltVT =
14418           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14419       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14420       Load =
14421           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14422                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14423                          Ld->isNonTemporal(), Ld->isInvariant(),
14424                          Ld->getAlignment());
14425     }
14426
14427     // Replace chain users with the new chain.
14428     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14429     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14430
14431     // Finally, do a normal sign-extend to the desired register.
14432     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14433   }
14434
14435   // All sizes must be a power of two.
14436   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14437          "Non-power-of-two elements are not custom lowered!");
14438
14439   // Attempt to load the original value using scalar loads.
14440   // Find the largest scalar type that divides the total loaded size.
14441   MVT SclrLoadTy = MVT::i8;
14442   for (MVT Tp : MVT::integer_valuetypes()) {
14443     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14444       SclrLoadTy = Tp;
14445     }
14446   }
14447
14448   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14449   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14450       (64 <= MemSz))
14451     SclrLoadTy = MVT::f64;
14452
14453   // Calculate the number of scalar loads that we need to perform
14454   // in order to load our vector from memory.
14455   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14456
14457   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14458          "Can only lower sext loads with a single scalar load!");
14459
14460   unsigned loadRegZize = RegSz;
14461   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14462     loadRegZize = 128;
14463
14464   // Represent our vector as a sequence of elements which are the
14465   // largest scalar that we can load.
14466   EVT LoadUnitVecVT = EVT::getVectorVT(
14467       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14468
14469   // Represent the data using the same element type that is stored in
14470   // memory. In practice, we ''widen'' MemVT.
14471   EVT WideVecVT =
14472       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14473                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14474
14475   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14476          "Invalid vector type");
14477
14478   // We can't shuffle using an illegal type.
14479   assert(TLI.isTypeLegal(WideVecVT) &&
14480          "We only lower types that form legal widened vector types");
14481
14482   SmallVector<SDValue, 8> Chains;
14483   SDValue Ptr = Ld->getBasePtr();
14484   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14485                                       TLI.getPointerTy(DAG.getDataLayout()));
14486   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14487
14488   for (unsigned i = 0; i < NumLoads; ++i) {
14489     // Perform a single load.
14490     SDValue ScalarLoad =
14491         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14492                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14493                     Ld->getAlignment());
14494     Chains.push_back(ScalarLoad.getValue(1));
14495     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14496     // another round of DAGCombining.
14497     if (i == 0)
14498       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14499     else
14500       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14501                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14502
14503     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14504   }
14505
14506   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14507
14508   // Bitcast the loaded value to a vector of the original element type, in
14509   // the size of the target vector type.
14510   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14511   unsigned SizeRatio = RegSz / MemSz;
14512
14513   if (Ext == ISD::SEXTLOAD) {
14514     // If we have SSE4.1, we can directly emit a VSEXT node.
14515     if (Subtarget->hasSSE41()) {
14516       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14517       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14518       return Sext;
14519     }
14520
14521     // Otherwise we'll shuffle the small elements in the high bits of the
14522     // larger type and perform an arithmetic shift. If the shift is not legal
14523     // it's better to scalarize.
14524     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14525            "We can't implement a sext load without an arithmetic right shift!");
14526
14527     // Redistribute the loaded elements into the different locations.
14528     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14529     for (unsigned i = 0; i != NumElems; ++i)
14530       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14531
14532     SDValue Shuff = DAG.getVectorShuffle(
14533         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14534
14535     Shuff = DAG.getBitcast(RegVT, Shuff);
14536
14537     // Build the arithmetic shift.
14538     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14539                    MemVT.getVectorElementType().getSizeInBits();
14540     Shuff =
14541         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14542                     DAG.getConstant(Amt, dl, RegVT));
14543
14544     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14545     return Shuff;
14546   }
14547
14548   // Redistribute the loaded elements into the different locations.
14549   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14550   for (unsigned i = 0; i != NumElems; ++i)
14551     ShuffleVec[i * SizeRatio] = i;
14552
14553   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14554                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14555
14556   // Bitcast to the requested type.
14557   Shuff = DAG.getBitcast(RegVT, Shuff);
14558   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14559   return Shuff;
14560 }
14561
14562 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14563 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14564 // from the AND / OR.
14565 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14566   Opc = Op.getOpcode();
14567   if (Opc != ISD::OR && Opc != ISD::AND)
14568     return false;
14569   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14570           Op.getOperand(0).hasOneUse() &&
14571           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14572           Op.getOperand(1).hasOneUse());
14573 }
14574
14575 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14576 // 1 and that the SETCC node has a single use.
14577 static bool isXor1OfSetCC(SDValue Op) {
14578   if (Op.getOpcode() != ISD::XOR)
14579     return false;
14580   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14581   if (N1C && N1C->getAPIntValue() == 1) {
14582     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14583       Op.getOperand(0).hasOneUse();
14584   }
14585   return false;
14586 }
14587
14588 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14589   bool addTest = true;
14590   SDValue Chain = Op.getOperand(0);
14591   SDValue Cond  = Op.getOperand(1);
14592   SDValue Dest  = Op.getOperand(2);
14593   SDLoc dl(Op);
14594   SDValue CC;
14595   bool Inverted = false;
14596
14597   if (Cond.getOpcode() == ISD::SETCC) {
14598     // Check for setcc([su]{add,sub,mul}o == 0).
14599     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14600         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14601         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14602         Cond.getOperand(0).getResNo() == 1 &&
14603         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14604          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14605          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14606          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14607          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14608          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14609       Inverted = true;
14610       Cond = Cond.getOperand(0);
14611     } else {
14612       SDValue NewCond = LowerSETCC(Cond, DAG);
14613       if (NewCond.getNode())
14614         Cond = NewCond;
14615     }
14616   }
14617 #if 0
14618   // FIXME: LowerXALUO doesn't handle these!!
14619   else if (Cond.getOpcode() == X86ISD::ADD  ||
14620            Cond.getOpcode() == X86ISD::SUB  ||
14621            Cond.getOpcode() == X86ISD::SMUL ||
14622            Cond.getOpcode() == X86ISD::UMUL)
14623     Cond = LowerXALUO(Cond, DAG);
14624 #endif
14625
14626   // Look pass (and (setcc_carry (cmp ...)), 1).
14627   if (Cond.getOpcode() == ISD::AND &&
14628       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14629     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14630     if (C && C->getAPIntValue() == 1)
14631       Cond = Cond.getOperand(0);
14632   }
14633
14634   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14635   // setting operand in place of the X86ISD::SETCC.
14636   unsigned CondOpcode = Cond.getOpcode();
14637   if (CondOpcode == X86ISD::SETCC ||
14638       CondOpcode == X86ISD::SETCC_CARRY) {
14639     CC = Cond.getOperand(0);
14640
14641     SDValue Cmp = Cond.getOperand(1);
14642     unsigned Opc = Cmp.getOpcode();
14643     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14644     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14645       Cond = Cmp;
14646       addTest = false;
14647     } else {
14648       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14649       default: break;
14650       case X86::COND_O:
14651       case X86::COND_B:
14652         // These can only come from an arithmetic instruction with overflow,
14653         // e.g. SADDO, UADDO.
14654         Cond = Cond.getNode()->getOperand(1);
14655         addTest = false;
14656         break;
14657       }
14658     }
14659   }
14660   CondOpcode = Cond.getOpcode();
14661   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14662       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14663       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14664        Cond.getOperand(0).getValueType() != MVT::i8)) {
14665     SDValue LHS = Cond.getOperand(0);
14666     SDValue RHS = Cond.getOperand(1);
14667     unsigned X86Opcode;
14668     unsigned X86Cond;
14669     SDVTList VTs;
14670     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14671     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14672     // X86ISD::INC).
14673     switch (CondOpcode) {
14674     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14675     case ISD::SADDO:
14676       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14677         if (C->isOne()) {
14678           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14679           break;
14680         }
14681       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14682     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14683     case ISD::SSUBO:
14684       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14685         if (C->isOne()) {
14686           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14687           break;
14688         }
14689       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14690     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14691     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14692     default: llvm_unreachable("unexpected overflowing operator");
14693     }
14694     if (Inverted)
14695       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14696     if (CondOpcode == ISD::UMULO)
14697       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14698                           MVT::i32);
14699     else
14700       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14701
14702     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14703
14704     if (CondOpcode == ISD::UMULO)
14705       Cond = X86Op.getValue(2);
14706     else
14707       Cond = X86Op.getValue(1);
14708
14709     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14710     addTest = false;
14711   } else {
14712     unsigned CondOpc;
14713     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14714       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14715       if (CondOpc == ISD::OR) {
14716         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14717         // two branches instead of an explicit OR instruction with a
14718         // separate test.
14719         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14720             isX86LogicalCmp(Cmp)) {
14721           CC = Cond.getOperand(0).getOperand(0);
14722           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14723                               Chain, Dest, CC, Cmp);
14724           CC = Cond.getOperand(1).getOperand(0);
14725           Cond = Cmp;
14726           addTest = false;
14727         }
14728       } else { // ISD::AND
14729         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14730         // two branches instead of an explicit AND instruction with a
14731         // separate test. However, we only do this if this block doesn't
14732         // have a fall-through edge, because this requires an explicit
14733         // jmp when the condition is false.
14734         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14735             isX86LogicalCmp(Cmp) &&
14736             Op.getNode()->hasOneUse()) {
14737           X86::CondCode CCode =
14738             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14739           CCode = X86::GetOppositeBranchCondition(CCode);
14740           CC = DAG.getConstant(CCode, dl, MVT::i8);
14741           SDNode *User = *Op.getNode()->use_begin();
14742           // Look for an unconditional branch following this conditional branch.
14743           // We need this because we need to reverse the successors in order
14744           // to implement FCMP_OEQ.
14745           if (User->getOpcode() == ISD::BR) {
14746             SDValue FalseBB = User->getOperand(1);
14747             SDNode *NewBR =
14748               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14749             assert(NewBR == User);
14750             (void)NewBR;
14751             Dest = FalseBB;
14752
14753             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14754                                 Chain, Dest, CC, Cmp);
14755             X86::CondCode CCode =
14756               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14757             CCode = X86::GetOppositeBranchCondition(CCode);
14758             CC = DAG.getConstant(CCode, dl, MVT::i8);
14759             Cond = Cmp;
14760             addTest = false;
14761           }
14762         }
14763       }
14764     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14765       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14766       // It should be transformed during dag combiner except when the condition
14767       // is set by a arithmetics with overflow node.
14768       X86::CondCode CCode =
14769         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14770       CCode = X86::GetOppositeBranchCondition(CCode);
14771       CC = DAG.getConstant(CCode, dl, MVT::i8);
14772       Cond = Cond.getOperand(0).getOperand(1);
14773       addTest = false;
14774     } else if (Cond.getOpcode() == ISD::SETCC &&
14775                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14776       // For FCMP_OEQ, we can emit
14777       // two branches instead of an explicit AND instruction with a
14778       // separate test. However, we only do this if this block doesn't
14779       // have a fall-through edge, because this requires an explicit
14780       // jmp when the condition is false.
14781       if (Op.getNode()->hasOneUse()) {
14782         SDNode *User = *Op.getNode()->use_begin();
14783         // Look for an unconditional branch following this conditional branch.
14784         // We need this because we need to reverse the successors in order
14785         // to implement FCMP_OEQ.
14786         if (User->getOpcode() == ISD::BR) {
14787           SDValue FalseBB = User->getOperand(1);
14788           SDNode *NewBR =
14789             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14790           assert(NewBR == User);
14791           (void)NewBR;
14792           Dest = FalseBB;
14793
14794           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14795                                     Cond.getOperand(0), Cond.getOperand(1));
14796           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14797           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14798           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14799                               Chain, Dest, CC, Cmp);
14800           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14801           Cond = Cmp;
14802           addTest = false;
14803         }
14804       }
14805     } else if (Cond.getOpcode() == ISD::SETCC &&
14806                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14807       // For FCMP_UNE, we can emit
14808       // two branches instead of an explicit AND instruction with a
14809       // separate test. However, we only do this if this block doesn't
14810       // have a fall-through edge, because this requires an explicit
14811       // jmp when the condition is false.
14812       if (Op.getNode()->hasOneUse()) {
14813         SDNode *User = *Op.getNode()->use_begin();
14814         // Look for an unconditional branch following this conditional branch.
14815         // We need this because we need to reverse the successors in order
14816         // to implement FCMP_UNE.
14817         if (User->getOpcode() == ISD::BR) {
14818           SDValue FalseBB = User->getOperand(1);
14819           SDNode *NewBR =
14820             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14821           assert(NewBR == User);
14822           (void)NewBR;
14823
14824           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14825                                     Cond.getOperand(0), Cond.getOperand(1));
14826           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14827           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14828           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14829                               Chain, Dest, CC, Cmp);
14830           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14831           Cond = Cmp;
14832           addTest = false;
14833           Dest = FalseBB;
14834         }
14835       }
14836     }
14837   }
14838
14839   if (addTest) {
14840     // Look pass the truncate if the high bits are known zero.
14841     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14842         Cond = Cond.getOperand(0);
14843
14844     // We know the result of AND is compared against zero. Try to match
14845     // it to BT.
14846     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14847       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14848       if (NewSetCC.getNode()) {
14849         CC = NewSetCC.getOperand(0);
14850         Cond = NewSetCC.getOperand(1);
14851         addTest = false;
14852       }
14853     }
14854   }
14855
14856   if (addTest) {
14857     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14858     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14859     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14860   }
14861   Cond = ConvertCmpIfNecessary(Cond, DAG);
14862   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14863                      Chain, Dest, CC, Cond);
14864 }
14865
14866 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14867 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14868 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14869 // that the guard pages used by the OS virtual memory manager are allocated in
14870 // correct sequence.
14871 SDValue
14872 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14873                                            SelectionDAG &DAG) const {
14874   MachineFunction &MF = DAG.getMachineFunction();
14875   bool SplitStack = MF.shouldSplitStack();
14876   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14877                SplitStack;
14878   SDLoc dl(Op);
14879
14880   if (!Lower) {
14881     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14882     SDNode* Node = Op.getNode();
14883
14884     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14885     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14886         " not tell us which reg is the stack pointer!");
14887     EVT VT = Node->getValueType(0);
14888     SDValue Tmp1 = SDValue(Node, 0);
14889     SDValue Tmp2 = SDValue(Node, 1);
14890     SDValue Tmp3 = Node->getOperand(2);
14891     SDValue Chain = Tmp1.getOperand(0);
14892
14893     // Chain the dynamic stack allocation so that it doesn't modify the stack
14894     // pointer when other instructions are using the stack.
14895     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14896         SDLoc(Node));
14897
14898     SDValue Size = Tmp2.getOperand(1);
14899     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14900     Chain = SP.getValue(1);
14901     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14902     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14903     unsigned StackAlign = TFI.getStackAlignment();
14904     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14905     if (Align > StackAlign)
14906       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14907           DAG.getConstant(-(uint64_t)Align, dl, VT));
14908     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14909
14910     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14911         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14912         SDLoc(Node));
14913
14914     SDValue Ops[2] = { Tmp1, Tmp2 };
14915     return DAG.getMergeValues(Ops, dl);
14916   }
14917
14918   // Get the inputs.
14919   SDValue Chain = Op.getOperand(0);
14920   SDValue Size  = Op.getOperand(1);
14921   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14922   EVT VT = Op.getNode()->getValueType(0);
14923
14924   bool Is64Bit = Subtarget->is64Bit();
14925   MVT SPTy = getPointerTy(DAG.getDataLayout());
14926
14927   if (SplitStack) {
14928     MachineRegisterInfo &MRI = MF.getRegInfo();
14929
14930     if (Is64Bit) {
14931       // The 64 bit implementation of segmented stacks needs to clobber both r10
14932       // r11. This makes it impossible to use it along with nested parameters.
14933       const Function *F = MF.getFunction();
14934
14935       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14936            I != E; ++I)
14937         if (I->hasNestAttr())
14938           report_fatal_error("Cannot use segmented stacks with functions that "
14939                              "have nested arguments.");
14940     }
14941
14942     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14943     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14944     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14945     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14946                                 DAG.getRegister(Vreg, SPTy));
14947     SDValue Ops1[2] = { Value, Chain };
14948     return DAG.getMergeValues(Ops1, dl);
14949   } else {
14950     SDValue Flag;
14951     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14952
14953     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14954     Flag = Chain.getValue(1);
14955     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14956
14957     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14958
14959     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14960     unsigned SPReg = RegInfo->getStackRegister();
14961     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14962     Chain = SP.getValue(1);
14963
14964     if (Align) {
14965       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14966                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14967       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14968     }
14969
14970     SDValue Ops1[2] = { SP, Chain };
14971     return DAG.getMergeValues(Ops1, dl);
14972   }
14973 }
14974
14975 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14976   MachineFunction &MF = DAG.getMachineFunction();
14977   auto PtrVT = getPointerTy(MF.getDataLayout());
14978   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14979
14980   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14981   SDLoc DL(Op);
14982
14983   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14984     // vastart just stores the address of the VarArgsFrameIndex slot into the
14985     // memory location argument.
14986     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14987     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14988                         MachinePointerInfo(SV), false, false, 0);
14989   }
14990
14991   // __va_list_tag:
14992   //   gp_offset         (0 - 6 * 8)
14993   //   fp_offset         (48 - 48 + 8 * 16)
14994   //   overflow_arg_area (point to parameters coming in memory).
14995   //   reg_save_area
14996   SmallVector<SDValue, 8> MemOps;
14997   SDValue FIN = Op.getOperand(1);
14998   // Store gp_offset
14999   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15000                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15001                                                DL, MVT::i32),
15002                                FIN, MachinePointerInfo(SV), false, false, 0);
15003   MemOps.push_back(Store);
15004
15005   // Store fp_offset
15006   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15007   Store = DAG.getStore(Op.getOperand(0), DL,
15008                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15009                                        MVT::i32),
15010                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15011   MemOps.push_back(Store);
15012
15013   // Store ptr to overflow_arg_area
15014   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15015   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15016   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15017                        MachinePointerInfo(SV, 8),
15018                        false, false, 0);
15019   MemOps.push_back(Store);
15020
15021   // Store ptr to reg_save_area.
15022   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15023   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15024   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15025                        MachinePointerInfo(SV, 16), false, false, 0);
15026   MemOps.push_back(Store);
15027   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15028 }
15029
15030 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15031   assert(Subtarget->is64Bit() &&
15032          "LowerVAARG only handles 64-bit va_arg!");
15033   assert((Subtarget->isTargetLinux() ||
15034           Subtarget->isTargetDarwin()) &&
15035           "Unhandled target in LowerVAARG");
15036   assert(Op.getNode()->getNumOperands() == 4);
15037   SDValue Chain = Op.getOperand(0);
15038   SDValue SrcPtr = Op.getOperand(1);
15039   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15040   unsigned Align = Op.getConstantOperandVal(3);
15041   SDLoc dl(Op);
15042
15043   EVT ArgVT = Op.getNode()->getValueType(0);
15044   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15045   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15046   uint8_t ArgMode;
15047
15048   // Decide which area this value should be read from.
15049   // TODO: Implement the AMD64 ABI in its entirety. This simple
15050   // selection mechanism works only for the basic types.
15051   if (ArgVT == MVT::f80) {
15052     llvm_unreachable("va_arg for f80 not yet implemented");
15053   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15054     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15055   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15056     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15057   } else {
15058     llvm_unreachable("Unhandled argument type in LowerVAARG");
15059   }
15060
15061   if (ArgMode == 2) {
15062     // Sanity Check: Make sure using fp_offset makes sense.
15063     assert(!Subtarget->useSoftFloat() &&
15064            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15065                Attribute::NoImplicitFloat)) &&
15066            Subtarget->hasSSE1());
15067   }
15068
15069   // Insert VAARG_64 node into the DAG
15070   // VAARG_64 returns two values: Variable Argument Address, Chain
15071   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15072                        DAG.getConstant(ArgMode, dl, MVT::i8),
15073                        DAG.getConstant(Align, dl, MVT::i32)};
15074   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15075   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15076                                           VTs, InstOps, MVT::i64,
15077                                           MachinePointerInfo(SV),
15078                                           /*Align=*/0,
15079                                           /*Volatile=*/false,
15080                                           /*ReadMem=*/true,
15081                                           /*WriteMem=*/true);
15082   Chain = VAARG.getValue(1);
15083
15084   // Load the next argument and return it
15085   return DAG.getLoad(ArgVT, dl,
15086                      Chain,
15087                      VAARG,
15088                      MachinePointerInfo(),
15089                      false, false, false, 0);
15090 }
15091
15092 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15093                            SelectionDAG &DAG) {
15094   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15095   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15096   SDValue Chain = Op.getOperand(0);
15097   SDValue DstPtr = Op.getOperand(1);
15098   SDValue SrcPtr = Op.getOperand(2);
15099   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15100   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15101   SDLoc DL(Op);
15102
15103   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15104                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15105                        false, false,
15106                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15107 }
15108
15109 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15110 // amount is a constant. Takes immediate version of shift as input.
15111 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15112                                           SDValue SrcOp, uint64_t ShiftAmt,
15113                                           SelectionDAG &DAG) {
15114   MVT ElementType = VT.getVectorElementType();
15115
15116   // Fold this packed shift into its first operand if ShiftAmt is 0.
15117   if (ShiftAmt == 0)
15118     return SrcOp;
15119
15120   // Check for ShiftAmt >= element width
15121   if (ShiftAmt >= ElementType.getSizeInBits()) {
15122     if (Opc == X86ISD::VSRAI)
15123       ShiftAmt = ElementType.getSizeInBits() - 1;
15124     else
15125       return DAG.getConstant(0, dl, VT);
15126   }
15127
15128   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15129          && "Unknown target vector shift-by-constant node");
15130
15131   // Fold this packed vector shift into a build vector if SrcOp is a
15132   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15133   if (VT == SrcOp.getSimpleValueType() &&
15134       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15135     SmallVector<SDValue, 8> Elts;
15136     unsigned NumElts = SrcOp->getNumOperands();
15137     ConstantSDNode *ND;
15138
15139     switch(Opc) {
15140     default: llvm_unreachable(nullptr);
15141     case X86ISD::VSHLI:
15142       for (unsigned i=0; i!=NumElts; ++i) {
15143         SDValue CurrentOp = SrcOp->getOperand(i);
15144         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15145           Elts.push_back(CurrentOp);
15146           continue;
15147         }
15148         ND = cast<ConstantSDNode>(CurrentOp);
15149         const APInt &C = ND->getAPIntValue();
15150         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15151       }
15152       break;
15153     case X86ISD::VSRLI:
15154       for (unsigned i=0; i!=NumElts; ++i) {
15155         SDValue CurrentOp = SrcOp->getOperand(i);
15156         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15157           Elts.push_back(CurrentOp);
15158           continue;
15159         }
15160         ND = cast<ConstantSDNode>(CurrentOp);
15161         const APInt &C = ND->getAPIntValue();
15162         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15163       }
15164       break;
15165     case X86ISD::VSRAI:
15166       for (unsigned i=0; i!=NumElts; ++i) {
15167         SDValue CurrentOp = SrcOp->getOperand(i);
15168         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15169           Elts.push_back(CurrentOp);
15170           continue;
15171         }
15172         ND = cast<ConstantSDNode>(CurrentOp);
15173         const APInt &C = ND->getAPIntValue();
15174         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15175       }
15176       break;
15177     }
15178
15179     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15180   }
15181
15182   return DAG.getNode(Opc, dl, VT, SrcOp,
15183                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15184 }
15185
15186 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15187 // may or may not be a constant. Takes immediate version of shift as input.
15188 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15189                                    SDValue SrcOp, SDValue ShAmt,
15190                                    SelectionDAG &DAG) {
15191   MVT SVT = ShAmt.getSimpleValueType();
15192   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15193
15194   // Catch shift-by-constant.
15195   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15196     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15197                                       CShAmt->getZExtValue(), DAG);
15198
15199   // Change opcode to non-immediate version
15200   switch (Opc) {
15201     default: llvm_unreachable("Unknown target vector shift node");
15202     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15203     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15204     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15205   }
15206
15207   const X86Subtarget &Subtarget =
15208       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15209   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15210       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15211     // Let the shuffle legalizer expand this shift amount node.
15212     SDValue Op0 = ShAmt.getOperand(0);
15213     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15214     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15215   } else {
15216     // Need to build a vector containing shift amount.
15217     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15218     SmallVector<SDValue, 4> ShOps;
15219     ShOps.push_back(ShAmt);
15220     if (SVT == MVT::i32) {
15221       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15222       ShOps.push_back(DAG.getUNDEF(SVT));
15223     }
15224     ShOps.push_back(DAG.getUNDEF(SVT));
15225
15226     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15227     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15228   }
15229
15230   // The return type has to be a 128-bit type with the same element
15231   // type as the input type.
15232   MVT EltVT = VT.getVectorElementType();
15233   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15234
15235   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15236   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15237 }
15238
15239 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15240 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15241 /// necessary casting for \p Mask when lowering masking intrinsics.
15242 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15243                                     SDValue PreservedSrc,
15244                                     const X86Subtarget *Subtarget,
15245                                     SelectionDAG &DAG) {
15246     EVT VT = Op.getValueType();
15247     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15248                                   MVT::i1, VT.getVectorNumElements());
15249     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15250                                      Mask.getValueType().getSizeInBits());
15251     SDLoc dl(Op);
15252
15253     assert(MaskVT.isSimple() && "invalid mask type");
15254
15255     if (isAllOnes(Mask))
15256       return Op;
15257
15258     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15259     // are extracted by EXTRACT_SUBVECTOR.
15260     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15261                                 DAG.getBitcast(BitcastVT, Mask),
15262                                 DAG.getIntPtrConstant(0, dl));
15263
15264     switch (Op.getOpcode()) {
15265       default: break;
15266       case X86ISD::PCMPEQM:
15267       case X86ISD::PCMPGTM:
15268       case X86ISD::CMPM:
15269       case X86ISD::CMPMU:
15270         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15271     }
15272     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15273       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15274     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15275 }
15276
15277 /// \brief Creates an SDNode for a predicated scalar operation.
15278 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15279 /// The mask is comming as MVT::i8 and it should be truncated
15280 /// to MVT::i1 while lowering masking intrinsics.
15281 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15282 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15283 /// a scalar instruction.
15284 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15285                                     SDValue PreservedSrc,
15286                                     const X86Subtarget *Subtarget,
15287                                     SelectionDAG &DAG) {
15288     if (isAllOnes(Mask))
15289       return Op;
15290
15291     EVT VT = Op.getValueType();
15292     SDLoc dl(Op);
15293     // The mask should be of type MVT::i1
15294     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15295
15296     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15297       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15298     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15299 }
15300
15301 static int getSEHRegistrationNodeSize(const Function *Fn) {
15302   if (!Fn->hasPersonalityFn())
15303     report_fatal_error(
15304         "querying registration node size for function without personality");
15305   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15306   // WinEHStatePass for the full struct definition.
15307   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15308   case EHPersonality::MSVC_X86SEH: return 24;
15309   case EHPersonality::MSVC_CXX: return 16;
15310   default: break;
15311   }
15312   report_fatal_error("can only recover FP for MSVC EH personality functions");
15313 }
15314
15315 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15316 /// function or when returning to a parent frame after catching an exception, we
15317 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15318 /// Here's the math:
15319 ///   RegNodeBase = EntryEBP - RegNodeSize
15320 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15321 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15322 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15323 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15324                                    SDValue EntryEBP) {
15325   MachineFunction &MF = DAG.getMachineFunction();
15326   SDLoc dl;
15327
15328   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15329   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15330
15331   // It's possible that the parent function no longer has a personality function
15332   // if the exceptional code was optimized away, in which case we just return
15333   // the incoming EBP.
15334   if (!Fn->hasPersonalityFn())
15335     return EntryEBP;
15336
15337   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15338
15339   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15340   // registration.
15341   MCSymbol *OffsetSym =
15342       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15343           GlobalValue::getRealLinkageName(Fn->getName()));
15344   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15345   SDValue RegNodeFrameOffset =
15346       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15347
15348   // RegNodeBase = EntryEBP - RegNodeSize
15349   // ParentFP = RegNodeBase - RegNodeFrameOffset
15350   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15351                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15352   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15353 }
15354
15355 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15356                                        SelectionDAG &DAG) {
15357   SDLoc dl(Op);
15358   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15359   EVT VT = Op.getValueType();
15360   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15361   if (IntrData) {
15362     switch(IntrData->Type) {
15363     case INTR_TYPE_1OP:
15364       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15365     case INTR_TYPE_2OP:
15366       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15367         Op.getOperand(2));
15368     case INTR_TYPE_3OP:
15369       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15370         Op.getOperand(2), Op.getOperand(3));
15371     case INTR_TYPE_4OP:
15372       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15373         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15374     case INTR_TYPE_1OP_MASK_RM: {
15375       SDValue Src = Op.getOperand(1);
15376       SDValue PassThru = Op.getOperand(2);
15377       SDValue Mask = Op.getOperand(3);
15378       SDValue RoundingMode;
15379       if (Op.getNumOperands() == 4)
15380         RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15381       else
15382         RoundingMode = Op.getOperand(4);
15383       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15384       if (IntrWithRoundingModeOpcode != 0) {
15385         unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15386         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15387           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15388                                       dl, Op.getValueType(), Src, RoundingMode),
15389                                       Mask, PassThru, Subtarget, DAG);
15390       }
15391       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15392                                               RoundingMode),
15393                                   Mask, PassThru, Subtarget, DAG);
15394     }
15395     case INTR_TYPE_1OP_MASK: {
15396       SDValue Src = Op.getOperand(1);
15397       SDValue Passthru = Op.getOperand(2);
15398       SDValue Mask = Op.getOperand(3);
15399       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15400                                   Mask, Passthru, Subtarget, DAG);
15401     }
15402     case INTR_TYPE_SCALAR_MASK_RM: {
15403       SDValue Src1 = Op.getOperand(1);
15404       SDValue Src2 = Op.getOperand(2);
15405       SDValue Src0 = Op.getOperand(3);
15406       SDValue Mask = Op.getOperand(4);
15407       // There are 2 kinds of intrinsics in this group:
15408       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15409       // (2) With rounding mode and sae - 7 operands.
15410       if (Op.getNumOperands() == 6) {
15411         SDValue Sae  = Op.getOperand(5);
15412         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15413         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15414                                                 Sae),
15415                                     Mask, Src0, Subtarget, DAG);
15416       }
15417       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15418       SDValue RoundingMode  = Op.getOperand(5);
15419       SDValue Sae  = Op.getOperand(6);
15420       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15421                                               RoundingMode, Sae),
15422                                   Mask, Src0, Subtarget, DAG);
15423     }
15424     case INTR_TYPE_2OP_MASK: {
15425       SDValue Src1 = Op.getOperand(1);
15426       SDValue Src2 = Op.getOperand(2);
15427       SDValue PassThru = Op.getOperand(3);
15428       SDValue Mask = Op.getOperand(4);
15429       // We specify 2 possible opcodes for intrinsics with rounding modes.
15430       // First, we check if the intrinsic may have non-default rounding mode,
15431       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15432       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15433       if (IntrWithRoundingModeOpcode != 0) {
15434         SDValue Rnd = Op.getOperand(5);
15435         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15436         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15437           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15438                                       dl, Op.getValueType(),
15439                                       Src1, Src2, Rnd),
15440                                       Mask, PassThru, Subtarget, DAG);
15441         }
15442       }
15443       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15444                                               Src1,Src2),
15445                                   Mask, PassThru, Subtarget, DAG);
15446     }
15447     case INTR_TYPE_2OP_MASK_RM: {
15448       SDValue Src1 = Op.getOperand(1);
15449       SDValue Src2 = Op.getOperand(2);
15450       SDValue PassThru = Op.getOperand(3);
15451       SDValue Mask = Op.getOperand(4);
15452       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15453       // First, we check if the intrinsic have rounding mode (6 operands),
15454       // if not, we set rounding mode to "current".
15455       SDValue Rnd;
15456       if (Op.getNumOperands() == 6)
15457         Rnd = Op.getOperand(5);
15458       else
15459         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15460       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15461                                               Src1, Src2, Rnd),
15462                                   Mask, PassThru, Subtarget, DAG);
15463     }
15464     case INTR_TYPE_3OP_MASK: {
15465       SDValue Src1 = Op.getOperand(1);
15466       SDValue Src2 = Op.getOperand(2);
15467       SDValue Src3 = Op.getOperand(3);
15468       SDValue PassThru = Op.getOperand(4);
15469       SDValue Mask = Op.getOperand(5);
15470       // We specify 2 possible opcodes for intrinsics with rounding modes.
15471       // First, we check if the intrinsic may have non-default rounding mode,
15472       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15473       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15474       if (IntrWithRoundingModeOpcode != 0) {
15475         SDValue Rnd = Op.getOperand(6);
15476         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15477         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15478           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15479                                       dl, Op.getValueType(),
15480                                       Src1, Src2, Src3, Rnd),
15481                                       Mask, PassThru, Subtarget, DAG);
15482         }
15483       }
15484       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15485                                               Src1, Src2, Src3),
15486                                   Mask, PassThru, Subtarget, DAG);
15487     }
15488     case VPERM_3OP_MASKZ:
15489     case VPERM_3OP_MASK:
15490     case FMA_OP_MASK3:
15491     case FMA_OP_MASKZ:
15492     case FMA_OP_MASK: {
15493       SDValue Src1 = Op.getOperand(1);
15494       SDValue Src2 = Op.getOperand(2);
15495       SDValue Src3 = Op.getOperand(3);
15496       SDValue Mask = Op.getOperand(4);
15497       EVT VT = Op.getValueType();
15498       SDValue PassThru = SDValue();
15499
15500       // set PassThru element
15501       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15502         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15503       else if (IntrData->Type == FMA_OP_MASK3)
15504         PassThru = Src3;
15505       else
15506         PassThru = Src1;
15507
15508       // We specify 2 possible opcodes for intrinsics with rounding modes.
15509       // First, we check if the intrinsic may have non-default rounding mode,
15510       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15511       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15512       if (IntrWithRoundingModeOpcode != 0) {
15513         SDValue Rnd = Op.getOperand(5);
15514         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15515             X86::STATIC_ROUNDING::CUR_DIRECTION)
15516           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15517                                                   dl, Op.getValueType(),
15518                                                   Src1, Src2, Src3, Rnd),
15519                                       Mask, PassThru, Subtarget, DAG);
15520       }
15521       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15522                                               dl, Op.getValueType(),
15523                                               Src1, Src2, Src3),
15524                                   Mask, PassThru, Subtarget, DAG);
15525     }
15526     case CMP_MASK:
15527     case CMP_MASK_CC: {
15528       // Comparison intrinsics with masks.
15529       // Example of transformation:
15530       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15531       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15532       // (i8 (bitcast
15533       //   (v8i1 (insert_subvector undef,
15534       //           (v2i1 (and (PCMPEQM %a, %b),
15535       //                      (extract_subvector
15536       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15537       EVT VT = Op.getOperand(1).getValueType();
15538       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15539                                     VT.getVectorNumElements());
15540       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15541       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15542                                        Mask.getValueType().getSizeInBits());
15543       SDValue Cmp;
15544       if (IntrData->Type == CMP_MASK_CC) {
15545         SDValue CC = Op.getOperand(3);
15546         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15547         // We specify 2 possible opcodes for intrinsics with rounding modes.
15548         // First, we check if the intrinsic may have non-default rounding mode,
15549         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15550         if (IntrData->Opc1 != 0) {
15551           SDValue Rnd = Op.getOperand(5);
15552           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15553               X86::STATIC_ROUNDING::CUR_DIRECTION)
15554             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15555                               Op.getOperand(2), CC, Rnd);
15556         }
15557         //default rounding mode
15558         if(!Cmp.getNode())
15559             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15560                               Op.getOperand(2), CC);
15561
15562       } else {
15563         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15564         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15565                           Op.getOperand(2));
15566       }
15567       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15568                                              DAG.getTargetConstant(0, dl,
15569                                                                    MaskVT),
15570                                              Subtarget, DAG);
15571       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15572                                 DAG.getUNDEF(BitcastVT), CmpMask,
15573                                 DAG.getIntPtrConstant(0, dl));
15574       return DAG.getBitcast(Op.getValueType(), Res);
15575     }
15576     case COMI: { // Comparison intrinsics
15577       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15578       SDValue LHS = Op.getOperand(1);
15579       SDValue RHS = Op.getOperand(2);
15580       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15581       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15582       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15583       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15584                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15585       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15586     }
15587     case VSHIFT:
15588       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15589                                  Op.getOperand(1), Op.getOperand(2), DAG);
15590     case VSHIFT_MASK:
15591       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15592                                                       Op.getSimpleValueType(),
15593                                                       Op.getOperand(1),
15594                                                       Op.getOperand(2), DAG),
15595                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15596                                   DAG);
15597     case COMPRESS_EXPAND_IN_REG: {
15598       SDValue Mask = Op.getOperand(3);
15599       SDValue DataToCompress = Op.getOperand(1);
15600       SDValue PassThru = Op.getOperand(2);
15601       if (isAllOnes(Mask)) // return data as is
15602         return Op.getOperand(1);
15603
15604       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15605                                               DataToCompress),
15606                                   Mask, PassThru, Subtarget, DAG);
15607     }
15608     case BLEND: {
15609       SDValue Mask = Op.getOperand(3);
15610       EVT VT = Op.getValueType();
15611       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15612                                     VT.getVectorNumElements());
15613       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15614                                        Mask.getValueType().getSizeInBits());
15615       SDLoc dl(Op);
15616       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15617                                   DAG.getBitcast(BitcastVT, Mask),
15618                                   DAG.getIntPtrConstant(0, dl));
15619       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15620                          Op.getOperand(2));
15621     }
15622     default:
15623       break;
15624     }
15625   }
15626
15627   switch (IntNo) {
15628   default: return SDValue();    // Don't custom lower most intrinsics.
15629
15630   case Intrinsic::x86_avx2_permd:
15631   case Intrinsic::x86_avx2_permps:
15632     // Operands intentionally swapped. Mask is last operand to intrinsic,
15633     // but second operand for node/instruction.
15634     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15635                        Op.getOperand(2), Op.getOperand(1));
15636
15637   // ptest and testp intrinsics. The intrinsic these come from are designed to
15638   // return an integer value, not just an instruction so lower it to the ptest
15639   // or testp pattern and a setcc for the result.
15640   case Intrinsic::x86_sse41_ptestz:
15641   case Intrinsic::x86_sse41_ptestc:
15642   case Intrinsic::x86_sse41_ptestnzc:
15643   case Intrinsic::x86_avx_ptestz_256:
15644   case Intrinsic::x86_avx_ptestc_256:
15645   case Intrinsic::x86_avx_ptestnzc_256:
15646   case Intrinsic::x86_avx_vtestz_ps:
15647   case Intrinsic::x86_avx_vtestc_ps:
15648   case Intrinsic::x86_avx_vtestnzc_ps:
15649   case Intrinsic::x86_avx_vtestz_pd:
15650   case Intrinsic::x86_avx_vtestc_pd:
15651   case Intrinsic::x86_avx_vtestnzc_pd:
15652   case Intrinsic::x86_avx_vtestz_ps_256:
15653   case Intrinsic::x86_avx_vtestc_ps_256:
15654   case Intrinsic::x86_avx_vtestnzc_ps_256:
15655   case Intrinsic::x86_avx_vtestz_pd_256:
15656   case Intrinsic::x86_avx_vtestc_pd_256:
15657   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15658     bool IsTestPacked = false;
15659     unsigned X86CC;
15660     switch (IntNo) {
15661     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15662     case Intrinsic::x86_avx_vtestz_ps:
15663     case Intrinsic::x86_avx_vtestz_pd:
15664     case Intrinsic::x86_avx_vtestz_ps_256:
15665     case Intrinsic::x86_avx_vtestz_pd_256:
15666       IsTestPacked = true; // Fallthrough
15667     case Intrinsic::x86_sse41_ptestz:
15668     case Intrinsic::x86_avx_ptestz_256:
15669       // ZF = 1
15670       X86CC = X86::COND_E;
15671       break;
15672     case Intrinsic::x86_avx_vtestc_ps:
15673     case Intrinsic::x86_avx_vtestc_pd:
15674     case Intrinsic::x86_avx_vtestc_ps_256:
15675     case Intrinsic::x86_avx_vtestc_pd_256:
15676       IsTestPacked = true; // Fallthrough
15677     case Intrinsic::x86_sse41_ptestc:
15678     case Intrinsic::x86_avx_ptestc_256:
15679       // CF = 1
15680       X86CC = X86::COND_B;
15681       break;
15682     case Intrinsic::x86_avx_vtestnzc_ps:
15683     case Intrinsic::x86_avx_vtestnzc_pd:
15684     case Intrinsic::x86_avx_vtestnzc_ps_256:
15685     case Intrinsic::x86_avx_vtestnzc_pd_256:
15686       IsTestPacked = true; // Fallthrough
15687     case Intrinsic::x86_sse41_ptestnzc:
15688     case Intrinsic::x86_avx_ptestnzc_256:
15689       // ZF and CF = 0
15690       X86CC = X86::COND_A;
15691       break;
15692     }
15693
15694     SDValue LHS = Op.getOperand(1);
15695     SDValue RHS = Op.getOperand(2);
15696     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15697     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15698     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15699     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15700     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15701   }
15702   case Intrinsic::x86_avx512_kortestz_w:
15703   case Intrinsic::x86_avx512_kortestc_w: {
15704     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15705     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15706     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15707     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15708     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15709     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15710     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15711   }
15712
15713   case Intrinsic::x86_sse42_pcmpistria128:
15714   case Intrinsic::x86_sse42_pcmpestria128:
15715   case Intrinsic::x86_sse42_pcmpistric128:
15716   case Intrinsic::x86_sse42_pcmpestric128:
15717   case Intrinsic::x86_sse42_pcmpistrio128:
15718   case Intrinsic::x86_sse42_pcmpestrio128:
15719   case Intrinsic::x86_sse42_pcmpistris128:
15720   case Intrinsic::x86_sse42_pcmpestris128:
15721   case Intrinsic::x86_sse42_pcmpistriz128:
15722   case Intrinsic::x86_sse42_pcmpestriz128: {
15723     unsigned Opcode;
15724     unsigned X86CC;
15725     switch (IntNo) {
15726     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15727     case Intrinsic::x86_sse42_pcmpistria128:
15728       Opcode = X86ISD::PCMPISTRI;
15729       X86CC = X86::COND_A;
15730       break;
15731     case Intrinsic::x86_sse42_pcmpestria128:
15732       Opcode = X86ISD::PCMPESTRI;
15733       X86CC = X86::COND_A;
15734       break;
15735     case Intrinsic::x86_sse42_pcmpistric128:
15736       Opcode = X86ISD::PCMPISTRI;
15737       X86CC = X86::COND_B;
15738       break;
15739     case Intrinsic::x86_sse42_pcmpestric128:
15740       Opcode = X86ISD::PCMPESTRI;
15741       X86CC = X86::COND_B;
15742       break;
15743     case Intrinsic::x86_sse42_pcmpistrio128:
15744       Opcode = X86ISD::PCMPISTRI;
15745       X86CC = X86::COND_O;
15746       break;
15747     case Intrinsic::x86_sse42_pcmpestrio128:
15748       Opcode = X86ISD::PCMPESTRI;
15749       X86CC = X86::COND_O;
15750       break;
15751     case Intrinsic::x86_sse42_pcmpistris128:
15752       Opcode = X86ISD::PCMPISTRI;
15753       X86CC = X86::COND_S;
15754       break;
15755     case Intrinsic::x86_sse42_pcmpestris128:
15756       Opcode = X86ISD::PCMPESTRI;
15757       X86CC = X86::COND_S;
15758       break;
15759     case Intrinsic::x86_sse42_pcmpistriz128:
15760       Opcode = X86ISD::PCMPISTRI;
15761       X86CC = X86::COND_E;
15762       break;
15763     case Intrinsic::x86_sse42_pcmpestriz128:
15764       Opcode = X86ISD::PCMPESTRI;
15765       X86CC = X86::COND_E;
15766       break;
15767     }
15768     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15769     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15770     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15771     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15772                                 DAG.getConstant(X86CC, dl, MVT::i8),
15773                                 SDValue(PCMP.getNode(), 1));
15774     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15775   }
15776
15777   case Intrinsic::x86_sse42_pcmpistri128:
15778   case Intrinsic::x86_sse42_pcmpestri128: {
15779     unsigned Opcode;
15780     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15781       Opcode = X86ISD::PCMPISTRI;
15782     else
15783       Opcode = X86ISD::PCMPESTRI;
15784
15785     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15786     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15787     return DAG.getNode(Opcode, dl, VTs, NewOps);
15788   }
15789
15790   case Intrinsic::x86_seh_lsda: {
15791     // Compute the symbol for the LSDA. We know it'll get emitted later.
15792     MachineFunction &MF = DAG.getMachineFunction();
15793     SDValue Op1 = Op.getOperand(1);
15794     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15795     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15796         GlobalValue::getRealLinkageName(Fn->getName()));
15797
15798     // Generate a simple absolute symbol reference. This intrinsic is only
15799     // supported on 32-bit Windows, which isn't PIC.
15800     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15801     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15802   }
15803
15804   case Intrinsic::x86_seh_recoverfp: {
15805     SDValue FnOp = Op.getOperand(1);
15806     SDValue IncomingFPOp = Op.getOperand(2);
15807     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15808     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15809     if (!Fn)
15810       report_fatal_error(
15811           "llvm.x86.seh.recoverfp must take a function as the first argument");
15812     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15813   }
15814
15815   case Intrinsic::localaddress: {
15816     // Returns one of the stack, base, or frame pointer registers, depending on
15817     // which is used to reference local variables.
15818     MachineFunction &MF = DAG.getMachineFunction();
15819     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15820     unsigned Reg;
15821     if (RegInfo->hasBasePointer(MF))
15822       Reg = RegInfo->getBaseRegister();
15823     else // This function handles the SP or FP case.
15824       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15825     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15826   }
15827   }
15828 }
15829
15830 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15831                               SDValue Src, SDValue Mask, SDValue Base,
15832                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15833                               const X86Subtarget * Subtarget) {
15834   SDLoc dl(Op);
15835   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15836   if (!C)
15837     llvm_unreachable("Invalid scale type");
15838   unsigned ScaleVal = C->getZExtValue();
15839   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15840     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15841
15842   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15843   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15844                              Index.getSimpleValueType().getVectorNumElements());
15845   SDValue MaskInReg;
15846   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15847   if (MaskC)
15848     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15849   else {
15850     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15851                                      Mask.getValueType().getSizeInBits());
15852
15853     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15854     // are extracted by EXTRACT_SUBVECTOR.
15855     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15856                             DAG.getBitcast(BitcastVT, Mask),
15857                             DAG.getIntPtrConstant(0, dl));
15858   }
15859   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15860   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15861   SDValue Segment = DAG.getRegister(0, MVT::i32);
15862   if (Src.getOpcode() == ISD::UNDEF)
15863     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15864   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15865   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15866   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15867   return DAG.getMergeValues(RetOps, dl);
15868 }
15869
15870 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15871                                SDValue Src, SDValue Mask, SDValue Base,
15872                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15873   SDLoc dl(Op);
15874   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15875   if (!C)
15876     llvm_unreachable("Invalid scale type");
15877   unsigned ScaleVal = C->getZExtValue();
15878   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15879     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15880
15881   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15882   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15883   SDValue Segment = DAG.getRegister(0, MVT::i32);
15884   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15885                              Index.getSimpleValueType().getVectorNumElements());
15886   SDValue MaskInReg;
15887   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15888   if (MaskC)
15889     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15890   else {
15891     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15892                                      Mask.getValueType().getSizeInBits());
15893
15894     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15895     // are extracted by EXTRACT_SUBVECTOR.
15896     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15897                             DAG.getBitcast(BitcastVT, Mask),
15898                             DAG.getIntPtrConstant(0, dl));
15899   }
15900   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15901   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15902   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15903   return SDValue(Res, 1);
15904 }
15905
15906 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15907                                SDValue Mask, SDValue Base, SDValue Index,
15908                                SDValue ScaleOp, SDValue Chain) {
15909   SDLoc dl(Op);
15910   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15911   assert(C && "Invalid scale type");
15912   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15913   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15914   SDValue Segment = DAG.getRegister(0, MVT::i32);
15915   EVT MaskVT =
15916     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15917   SDValue MaskInReg;
15918   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15919   if (MaskC)
15920     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15921   else
15922     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15923   //SDVTList VTs = DAG.getVTList(MVT::Other);
15924   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15925   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15926   return SDValue(Res, 0);
15927 }
15928
15929 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15930 // read performance monitor counters (x86_rdpmc).
15931 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15932                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15933                               SmallVectorImpl<SDValue> &Results) {
15934   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15935   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15936   SDValue LO, HI;
15937
15938   // The ECX register is used to select the index of the performance counter
15939   // to read.
15940   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15941                                    N->getOperand(2));
15942   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15943
15944   // Reads the content of a 64-bit performance counter and returns it in the
15945   // registers EDX:EAX.
15946   if (Subtarget->is64Bit()) {
15947     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15948     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15949                             LO.getValue(2));
15950   } else {
15951     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15952     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15953                             LO.getValue(2));
15954   }
15955   Chain = HI.getValue(1);
15956
15957   if (Subtarget->is64Bit()) {
15958     // The EAX register is loaded with the low-order 32 bits. The EDX register
15959     // is loaded with the supported high-order bits of the counter.
15960     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15961                               DAG.getConstant(32, DL, MVT::i8));
15962     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15963     Results.push_back(Chain);
15964     return;
15965   }
15966
15967   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15968   SDValue Ops[] = { LO, HI };
15969   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15970   Results.push_back(Pair);
15971   Results.push_back(Chain);
15972 }
15973
15974 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15975 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15976 // also used to custom lower READCYCLECOUNTER nodes.
15977 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15978                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15979                               SmallVectorImpl<SDValue> &Results) {
15980   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15981   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15982   SDValue LO, HI;
15983
15984   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15985   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15986   // and the EAX register is loaded with the low-order 32 bits.
15987   if (Subtarget->is64Bit()) {
15988     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15989     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15990                             LO.getValue(2));
15991   } else {
15992     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15993     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15994                             LO.getValue(2));
15995   }
15996   SDValue Chain = HI.getValue(1);
15997
15998   if (Opcode == X86ISD::RDTSCP_DAG) {
15999     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16000
16001     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16002     // the ECX register. Add 'ecx' explicitly to the chain.
16003     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16004                                      HI.getValue(2));
16005     // Explicitly store the content of ECX at the location passed in input
16006     // to the 'rdtscp' intrinsic.
16007     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16008                          MachinePointerInfo(), false, false, 0);
16009   }
16010
16011   if (Subtarget->is64Bit()) {
16012     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16013     // the EAX register is loaded with the low-order 32 bits.
16014     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16015                               DAG.getConstant(32, DL, MVT::i8));
16016     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16017     Results.push_back(Chain);
16018     return;
16019   }
16020
16021   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16022   SDValue Ops[] = { LO, HI };
16023   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16024   Results.push_back(Pair);
16025   Results.push_back(Chain);
16026 }
16027
16028 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16029                                      SelectionDAG &DAG) {
16030   SmallVector<SDValue, 2> Results;
16031   SDLoc DL(Op);
16032   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16033                           Results);
16034   return DAG.getMergeValues(Results, DL);
16035 }
16036
16037 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16038                                     SelectionDAG &DAG) {
16039   MachineFunction &MF = DAG.getMachineFunction();
16040   const Function *Fn = MF.getFunction();
16041   SDLoc dl(Op);
16042   SDValue Chain = Op.getOperand(0);
16043
16044   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16045          "using llvm.x86.seh.restoreframe requires a frame pointer");
16046
16047   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16048   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16049
16050   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16051   unsigned FrameReg =
16052       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16053   unsigned SPReg = RegInfo->getStackRegister();
16054   unsigned SlotSize = RegInfo->getSlotSize();
16055
16056   // Get incoming EBP.
16057   SDValue IncomingEBP =
16058       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16059
16060   // SP is saved in the first field of every registration node, so load
16061   // [EBP-RegNodeSize] into SP.
16062   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16063   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16064                                DAG.getConstant(-RegNodeSize, dl, VT));
16065   SDValue NewSP =
16066       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16067                   false, VT.getScalarSizeInBits() / 8);
16068   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16069
16070   if (!RegInfo->needsStackRealignment(MF)) {
16071     // Adjust EBP to point back to the original frame position.
16072     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16073     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16074   } else {
16075     assert(RegInfo->hasBasePointer(MF) &&
16076            "functions with Win32 EH must use frame or base pointer register");
16077
16078     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16079     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16080     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16081
16082     // Reload the spilled EBP value, now that the stack and base pointers are
16083     // set up.
16084     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16085     X86FI->setHasSEHFramePtrSave(true);
16086     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16087     X86FI->setSEHFramePtrSaveIndex(FI);
16088     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16089                                 MachinePointerInfo(), false, false, false,
16090                                 VT.getScalarSizeInBits() / 8);
16091     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16092   }
16093
16094   return Chain;
16095 }
16096
16097 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16098                                       SelectionDAG &DAG) {
16099   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16100
16101   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16102   if (!IntrData) {
16103     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16104       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16105     return SDValue();
16106   }
16107
16108   SDLoc dl(Op);
16109   switch(IntrData->Type) {
16110   default:
16111     llvm_unreachable("Unknown Intrinsic Type");
16112     break;
16113   case RDSEED:
16114   case RDRAND: {
16115     // Emit the node with the right value type.
16116     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16117     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16118
16119     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16120     // Otherwise return the value from Rand, which is always 0, casted to i32.
16121     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16122                       DAG.getConstant(1, dl, Op->getValueType(1)),
16123                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16124                       SDValue(Result.getNode(), 1) };
16125     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16126                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16127                                   Ops);
16128
16129     // Return { result, isValid, chain }.
16130     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16131                        SDValue(Result.getNode(), 2));
16132   }
16133   case GATHER: {
16134   //gather(v1, mask, index, base, scale);
16135     SDValue Chain = Op.getOperand(0);
16136     SDValue Src   = Op.getOperand(2);
16137     SDValue Base  = Op.getOperand(3);
16138     SDValue Index = Op.getOperand(4);
16139     SDValue Mask  = Op.getOperand(5);
16140     SDValue Scale = Op.getOperand(6);
16141     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16142                          Chain, Subtarget);
16143   }
16144   case SCATTER: {
16145   //scatter(base, mask, index, v1, scale);
16146     SDValue Chain = Op.getOperand(0);
16147     SDValue Base  = Op.getOperand(2);
16148     SDValue Mask  = Op.getOperand(3);
16149     SDValue Index = Op.getOperand(4);
16150     SDValue Src   = Op.getOperand(5);
16151     SDValue Scale = Op.getOperand(6);
16152     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16153                           Scale, Chain);
16154   }
16155   case PREFETCH: {
16156     SDValue Hint = Op.getOperand(6);
16157     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16158     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16159     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16160     SDValue Chain = Op.getOperand(0);
16161     SDValue Mask  = Op.getOperand(2);
16162     SDValue Index = Op.getOperand(3);
16163     SDValue Base  = Op.getOperand(4);
16164     SDValue Scale = Op.getOperand(5);
16165     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16166   }
16167   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16168   case RDTSC: {
16169     SmallVector<SDValue, 2> Results;
16170     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16171                             Results);
16172     return DAG.getMergeValues(Results, dl);
16173   }
16174   // Read Performance Monitoring Counters.
16175   case RDPMC: {
16176     SmallVector<SDValue, 2> Results;
16177     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16178     return DAG.getMergeValues(Results, dl);
16179   }
16180   // XTEST intrinsics.
16181   case XTEST: {
16182     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16183     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16184     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16185                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16186                                 InTrans);
16187     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16188     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16189                        Ret, SDValue(InTrans.getNode(), 1));
16190   }
16191   // ADC/ADCX/SBB
16192   case ADX: {
16193     SmallVector<SDValue, 2> Results;
16194     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16195     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16196     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16197                                 DAG.getConstant(-1, dl, MVT::i8));
16198     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16199                               Op.getOperand(4), GenCF.getValue(1));
16200     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16201                                  Op.getOperand(5), MachinePointerInfo(),
16202                                  false, false, 0);
16203     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16204                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16205                                 Res.getValue(1));
16206     Results.push_back(SetCC);
16207     Results.push_back(Store);
16208     return DAG.getMergeValues(Results, dl);
16209   }
16210   case COMPRESS_TO_MEM: {
16211     SDLoc dl(Op);
16212     SDValue Mask = Op.getOperand(4);
16213     SDValue DataToCompress = Op.getOperand(3);
16214     SDValue Addr = Op.getOperand(2);
16215     SDValue Chain = Op.getOperand(0);
16216
16217     EVT VT = DataToCompress.getValueType();
16218     if (isAllOnes(Mask)) // return just a store
16219       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16220                           MachinePointerInfo(), false, false,
16221                           VT.getScalarSizeInBits()/8);
16222
16223     SDValue Compressed =
16224       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16225                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16226     return DAG.getStore(Chain, dl, Compressed, Addr,
16227                         MachinePointerInfo(), false, false,
16228                         VT.getScalarSizeInBits()/8);
16229   }
16230   case EXPAND_FROM_MEM: {
16231     SDLoc dl(Op);
16232     SDValue Mask = Op.getOperand(4);
16233     SDValue PassThru = Op.getOperand(3);
16234     SDValue Addr = Op.getOperand(2);
16235     SDValue Chain = Op.getOperand(0);
16236     EVT VT = Op.getValueType();
16237
16238     if (isAllOnes(Mask)) // return just a load
16239       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16240                          false, VT.getScalarSizeInBits()/8);
16241
16242     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16243                                        false, false, false,
16244                                        VT.getScalarSizeInBits()/8);
16245
16246     SDValue Results[] = {
16247       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16248                            Mask, PassThru, Subtarget, DAG), Chain};
16249     return DAG.getMergeValues(Results, dl);
16250   }
16251   }
16252 }
16253
16254 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16255                                            SelectionDAG &DAG) const {
16256   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16257   MFI->setReturnAddressIsTaken(true);
16258
16259   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16260     return SDValue();
16261
16262   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16263   SDLoc dl(Op);
16264   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16265
16266   if (Depth > 0) {
16267     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16268     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16269     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16270     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16271                        DAG.getNode(ISD::ADD, dl, PtrVT,
16272                                    FrameAddr, Offset),
16273                        MachinePointerInfo(), false, false, false, 0);
16274   }
16275
16276   // Just load the return address.
16277   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16278   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16279                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16280 }
16281
16282 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16283   MachineFunction &MF = DAG.getMachineFunction();
16284   MachineFrameInfo *MFI = MF.getFrameInfo();
16285   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16286   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16287   EVT VT = Op.getValueType();
16288
16289   MFI->setFrameAddressIsTaken(true);
16290
16291   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16292     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16293     // is not possible to crawl up the stack without looking at the unwind codes
16294     // simultaneously.
16295     int FrameAddrIndex = FuncInfo->getFAIndex();
16296     if (!FrameAddrIndex) {
16297       // Set up a frame object for the return address.
16298       unsigned SlotSize = RegInfo->getSlotSize();
16299       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16300           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16301       FuncInfo->setFAIndex(FrameAddrIndex);
16302     }
16303     return DAG.getFrameIndex(FrameAddrIndex, VT);
16304   }
16305
16306   unsigned FrameReg =
16307       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16308   SDLoc dl(Op);  // FIXME probably not meaningful
16309   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16310   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16311           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16312          "Invalid Frame Register!");
16313   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16314   while (Depth--)
16315     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16316                             MachinePointerInfo(),
16317                             false, false, false, 0);
16318   return FrameAddr;
16319 }
16320
16321 // FIXME? Maybe this could be a TableGen attribute on some registers and
16322 // this table could be generated automatically from RegInfo.
16323 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16324                                               SelectionDAG &DAG) const {
16325   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16326   const MachineFunction &MF = DAG.getMachineFunction();
16327
16328   unsigned Reg = StringSwitch<unsigned>(RegName)
16329                        .Case("esp", X86::ESP)
16330                        .Case("rsp", X86::RSP)
16331                        .Case("ebp", X86::EBP)
16332                        .Case("rbp", X86::RBP)
16333                        .Default(0);
16334
16335   if (Reg == X86::EBP || Reg == X86::RBP) {
16336     if (!TFI.hasFP(MF))
16337       report_fatal_error("register " + StringRef(RegName) +
16338                          " is allocatable: function has no frame pointer");
16339 #ifndef NDEBUG
16340     else {
16341       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16342       unsigned FrameReg =
16343           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16344       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16345              "Invalid Frame Register!");
16346     }
16347 #endif
16348   }
16349
16350   if (Reg)
16351     return Reg;
16352
16353   report_fatal_error("Invalid register name global variable");
16354 }
16355
16356 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16357                                                      SelectionDAG &DAG) const {
16358   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16359   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16360 }
16361
16362 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16363   SDValue Chain     = Op.getOperand(0);
16364   SDValue Offset    = Op.getOperand(1);
16365   SDValue Handler   = Op.getOperand(2);
16366   SDLoc dl      (Op);
16367
16368   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16369   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16370   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16371   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16372           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16373          "Invalid Frame Register!");
16374   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16375   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16376
16377   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16378                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16379                                                        dl));
16380   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16381   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16382                        false, false, 0);
16383   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16384
16385   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16386                      DAG.getRegister(StoreAddrReg, PtrVT));
16387 }
16388
16389 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16390                                                SelectionDAG &DAG) const {
16391   SDLoc DL(Op);
16392   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16393                      DAG.getVTList(MVT::i32, MVT::Other),
16394                      Op.getOperand(0), Op.getOperand(1));
16395 }
16396
16397 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16398                                                 SelectionDAG &DAG) const {
16399   SDLoc DL(Op);
16400   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16401                      Op.getOperand(0), Op.getOperand(1));
16402 }
16403
16404 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16405   return Op.getOperand(0);
16406 }
16407
16408 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16409                                                 SelectionDAG &DAG) const {
16410   SDValue Root = Op.getOperand(0);
16411   SDValue Trmp = Op.getOperand(1); // trampoline
16412   SDValue FPtr = Op.getOperand(2); // nested function
16413   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16414   SDLoc dl (Op);
16415
16416   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16417   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16418
16419   if (Subtarget->is64Bit()) {
16420     SDValue OutChains[6];
16421
16422     // Large code-model.
16423     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16424     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16425
16426     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16427     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16428
16429     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16430
16431     // Load the pointer to the nested function into R11.
16432     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16433     SDValue Addr = Trmp;
16434     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16435                                 Addr, MachinePointerInfo(TrmpAddr),
16436                                 false, false, 0);
16437
16438     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16439                        DAG.getConstant(2, dl, MVT::i64));
16440     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16441                                 MachinePointerInfo(TrmpAddr, 2),
16442                                 false, false, 2);
16443
16444     // Load the 'nest' parameter value into R10.
16445     // R10 is specified in X86CallingConv.td
16446     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16447     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16448                        DAG.getConstant(10, dl, MVT::i64));
16449     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16450                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16451                                 false, false, 0);
16452
16453     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16454                        DAG.getConstant(12, dl, MVT::i64));
16455     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16456                                 MachinePointerInfo(TrmpAddr, 12),
16457                                 false, false, 2);
16458
16459     // Jump to the nested function.
16460     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16461     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16462                        DAG.getConstant(20, dl, MVT::i64));
16463     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16464                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16465                                 false, false, 0);
16466
16467     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16468     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16469                        DAG.getConstant(22, dl, MVT::i64));
16470     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16471                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16472                                 false, false, 0);
16473
16474     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16475   } else {
16476     const Function *Func =
16477       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16478     CallingConv::ID CC = Func->getCallingConv();
16479     unsigned NestReg;
16480
16481     switch (CC) {
16482     default:
16483       llvm_unreachable("Unsupported calling convention");
16484     case CallingConv::C:
16485     case CallingConv::X86_StdCall: {
16486       // Pass 'nest' parameter in ECX.
16487       // Must be kept in sync with X86CallingConv.td
16488       NestReg = X86::ECX;
16489
16490       // Check that ECX wasn't needed by an 'inreg' parameter.
16491       FunctionType *FTy = Func->getFunctionType();
16492       const AttributeSet &Attrs = Func->getAttributes();
16493
16494       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16495         unsigned InRegCount = 0;
16496         unsigned Idx = 1;
16497
16498         for (FunctionType::param_iterator I = FTy->param_begin(),
16499              E = FTy->param_end(); I != E; ++I, ++Idx)
16500           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16501             // FIXME: should only count parameters that are lowered to integers.
16502             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16503
16504         if (InRegCount > 2) {
16505           report_fatal_error("Nest register in use - reduce number of inreg"
16506                              " parameters!");
16507         }
16508       }
16509       break;
16510     }
16511     case CallingConv::X86_FastCall:
16512     case CallingConv::X86_ThisCall:
16513     case CallingConv::Fast:
16514       // Pass 'nest' parameter in EAX.
16515       // Must be kept in sync with X86CallingConv.td
16516       NestReg = X86::EAX;
16517       break;
16518     }
16519
16520     SDValue OutChains[4];
16521     SDValue Addr, Disp;
16522
16523     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16524                        DAG.getConstant(10, dl, MVT::i32));
16525     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16526
16527     // This is storing the opcode for MOV32ri.
16528     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16529     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16530     OutChains[0] = DAG.getStore(Root, dl,
16531                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16532                                 Trmp, MachinePointerInfo(TrmpAddr),
16533                                 false, false, 0);
16534
16535     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16536                        DAG.getConstant(1, dl, MVT::i32));
16537     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16538                                 MachinePointerInfo(TrmpAddr, 1),
16539                                 false, false, 1);
16540
16541     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16542     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16543                        DAG.getConstant(5, dl, MVT::i32));
16544     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16545                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16546                                 false, false, 1);
16547
16548     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16549                        DAG.getConstant(6, dl, MVT::i32));
16550     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16551                                 MachinePointerInfo(TrmpAddr, 6),
16552                                 false, false, 1);
16553
16554     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16555   }
16556 }
16557
16558 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16559                                             SelectionDAG &DAG) const {
16560   /*
16561    The rounding mode is in bits 11:10 of FPSR, and has the following
16562    settings:
16563      00 Round to nearest
16564      01 Round to -inf
16565      10 Round to +inf
16566      11 Round to 0
16567
16568   FLT_ROUNDS, on the other hand, expects the following:
16569     -1 Undefined
16570      0 Round to 0
16571      1 Round to nearest
16572      2 Round to +inf
16573      3 Round to -inf
16574
16575   To perform the conversion, we do:
16576     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16577   */
16578
16579   MachineFunction &MF = DAG.getMachineFunction();
16580   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16581   unsigned StackAlignment = TFI.getStackAlignment();
16582   MVT VT = Op.getSimpleValueType();
16583   SDLoc DL(Op);
16584
16585   // Save FP Control Word to stack slot
16586   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16587   SDValue StackSlot =
16588       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16589
16590   MachineMemOperand *MMO =
16591    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16592                            MachineMemOperand::MOStore, 2, 2);
16593
16594   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16595   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16596                                           DAG.getVTList(MVT::Other),
16597                                           Ops, MVT::i16, MMO);
16598
16599   // Load FP Control Word from stack slot
16600   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16601                             MachinePointerInfo(), false, false, false, 0);
16602
16603   // Transform as necessary
16604   SDValue CWD1 =
16605     DAG.getNode(ISD::SRL, DL, MVT::i16,
16606                 DAG.getNode(ISD::AND, DL, MVT::i16,
16607                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16608                 DAG.getConstant(11, DL, MVT::i8));
16609   SDValue CWD2 =
16610     DAG.getNode(ISD::SRL, DL, MVT::i16,
16611                 DAG.getNode(ISD::AND, DL, MVT::i16,
16612                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16613                 DAG.getConstant(9, DL, MVT::i8));
16614
16615   SDValue RetVal =
16616     DAG.getNode(ISD::AND, DL, MVT::i16,
16617                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16618                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16619                             DAG.getConstant(1, DL, MVT::i16)),
16620                 DAG.getConstant(3, DL, MVT::i16));
16621
16622   return DAG.getNode((VT.getSizeInBits() < 16 ?
16623                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16624 }
16625
16626 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16627   MVT VT = Op.getSimpleValueType();
16628   EVT OpVT = VT;
16629   unsigned NumBits = VT.getSizeInBits();
16630   SDLoc dl(Op);
16631
16632   Op = Op.getOperand(0);
16633   if (VT == MVT::i8) {
16634     // Zero extend to i32 since there is not an i8 bsr.
16635     OpVT = MVT::i32;
16636     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16637   }
16638
16639   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16640   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16641   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16642
16643   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16644   SDValue Ops[] = {
16645     Op,
16646     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16647     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16648     Op.getValue(1)
16649   };
16650   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16651
16652   // Finally xor with NumBits-1.
16653   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16654                    DAG.getConstant(NumBits - 1, dl, OpVT));
16655
16656   if (VT == MVT::i8)
16657     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16658   return Op;
16659 }
16660
16661 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16662   MVT VT = Op.getSimpleValueType();
16663   EVT OpVT = VT;
16664   unsigned NumBits = VT.getSizeInBits();
16665   SDLoc dl(Op);
16666
16667   Op = Op.getOperand(0);
16668   if (VT == MVT::i8) {
16669     // Zero extend to i32 since there is not an i8 bsr.
16670     OpVT = MVT::i32;
16671     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16672   }
16673
16674   // Issue a bsr (scan bits in reverse).
16675   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16676   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16677
16678   // And xor with NumBits-1.
16679   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16680                    DAG.getConstant(NumBits - 1, dl, OpVT));
16681
16682   if (VT == MVT::i8)
16683     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16684   return Op;
16685 }
16686
16687 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16688   MVT VT = Op.getSimpleValueType();
16689   unsigned NumBits = VT.getSizeInBits();
16690   SDLoc dl(Op);
16691   Op = Op.getOperand(0);
16692
16693   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16694   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16695   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16696
16697   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16698   SDValue Ops[] = {
16699     Op,
16700     DAG.getConstant(NumBits, dl, VT),
16701     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16702     Op.getValue(1)
16703   };
16704   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16705 }
16706
16707 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16708 // ones, and then concatenate the result back.
16709 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16710   MVT VT = Op.getSimpleValueType();
16711
16712   assert(VT.is256BitVector() && VT.isInteger() &&
16713          "Unsupported value type for operation");
16714
16715   unsigned NumElems = VT.getVectorNumElements();
16716   SDLoc dl(Op);
16717
16718   // Extract the LHS vectors
16719   SDValue LHS = Op.getOperand(0);
16720   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16721   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16722
16723   // Extract the RHS vectors
16724   SDValue RHS = Op.getOperand(1);
16725   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16726   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16727
16728   MVT EltVT = VT.getVectorElementType();
16729   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16730
16731   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16732                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16733                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16734 }
16735
16736 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16737   if (Op.getValueType() == MVT::i1)
16738     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16739                        Op.getOperand(0), Op.getOperand(1));
16740   assert(Op.getSimpleValueType().is256BitVector() &&
16741          Op.getSimpleValueType().isInteger() &&
16742          "Only handle AVX 256-bit vector integer operation");
16743   return Lower256IntArith(Op, DAG);
16744 }
16745
16746 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16747   if (Op.getValueType() == MVT::i1)
16748     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16749                        Op.getOperand(0), Op.getOperand(1));
16750   assert(Op.getSimpleValueType().is256BitVector() &&
16751          Op.getSimpleValueType().isInteger() &&
16752          "Only handle AVX 256-bit vector integer operation");
16753   return Lower256IntArith(Op, DAG);
16754 }
16755
16756 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16757                         SelectionDAG &DAG) {
16758   SDLoc dl(Op);
16759   MVT VT = Op.getSimpleValueType();
16760
16761   if (VT == MVT::i1)
16762     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16763
16764   // Decompose 256-bit ops into smaller 128-bit ops.
16765   if (VT.is256BitVector() && !Subtarget->hasInt256())
16766     return Lower256IntArith(Op, DAG);
16767
16768   SDValue A = Op.getOperand(0);
16769   SDValue B = Op.getOperand(1);
16770
16771   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16772   // pairs, multiply and truncate.
16773   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16774     if (Subtarget->hasInt256()) {
16775       if (VT == MVT::v32i8) {
16776         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16777         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16778         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16779         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16780         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16781         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16782         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16783         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16784                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16785                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16786       }
16787
16788       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16789       return DAG.getNode(
16790           ISD::TRUNCATE, dl, VT,
16791           DAG.getNode(ISD::MUL, dl, ExVT,
16792                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16793                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16794     }
16795
16796     assert(VT == MVT::v16i8 &&
16797            "Pre-AVX2 support only supports v16i8 multiplication");
16798     MVT ExVT = MVT::v8i16;
16799
16800     // Extract the lo parts and sign extend to i16
16801     SDValue ALo, BLo;
16802     if (Subtarget->hasSSE41()) {
16803       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16804       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16805     } else {
16806       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16807                               -1, 4, -1, 5, -1, 6, -1, 7};
16808       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16809       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16810       ALo = DAG.getBitcast(ExVT, ALo);
16811       BLo = DAG.getBitcast(ExVT, BLo);
16812       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16813       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16814     }
16815
16816     // Extract the hi parts and sign extend to i16
16817     SDValue AHi, BHi;
16818     if (Subtarget->hasSSE41()) {
16819       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16820                               -1, -1, -1, -1, -1, -1, -1, -1};
16821       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16822       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16823       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16824       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16825     } else {
16826       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16827                               -1, 12, -1, 13, -1, 14, -1, 15};
16828       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16829       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16830       AHi = DAG.getBitcast(ExVT, AHi);
16831       BHi = DAG.getBitcast(ExVT, BHi);
16832       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16833       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16834     }
16835
16836     // Multiply, mask the lower 8bits of the lo/hi results and pack
16837     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16838     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16839     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16840     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16841     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16842   }
16843
16844   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16845   if (VT == MVT::v4i32) {
16846     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16847            "Should not custom lower when pmuldq is available!");
16848
16849     // Extract the odd parts.
16850     static const int UnpackMask[] = { 1, -1, 3, -1 };
16851     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16852     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16853
16854     // Multiply the even parts.
16855     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16856     // Now multiply odd parts.
16857     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16858
16859     Evens = DAG.getBitcast(VT, Evens);
16860     Odds = DAG.getBitcast(VT, Odds);
16861
16862     // Merge the two vectors back together with a shuffle. This expands into 2
16863     // shuffles.
16864     static const int ShufMask[] = { 0, 4, 2, 6 };
16865     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16866   }
16867
16868   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16869          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16870
16871   //  Ahi = psrlqi(a, 32);
16872   //  Bhi = psrlqi(b, 32);
16873   //
16874   //  AloBlo = pmuludq(a, b);
16875   //  AloBhi = pmuludq(a, Bhi);
16876   //  AhiBlo = pmuludq(Ahi, b);
16877
16878   //  AloBhi = psllqi(AloBhi, 32);
16879   //  AhiBlo = psllqi(AhiBlo, 32);
16880   //  return AloBlo + AloBhi + AhiBlo;
16881
16882   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16883   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16884
16885   SDValue AhiBlo = Ahi;
16886   SDValue AloBhi = Bhi;
16887   // Bit cast to 32-bit vectors for MULUDQ
16888   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16889                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16890   A = DAG.getBitcast(MulVT, A);
16891   B = DAG.getBitcast(MulVT, B);
16892   Ahi = DAG.getBitcast(MulVT, Ahi);
16893   Bhi = DAG.getBitcast(MulVT, Bhi);
16894
16895   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16896   // After shifting right const values the result may be all-zero.
16897   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16898     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16899     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16900   }
16901   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16902     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16903     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16904   }
16905
16906   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16907   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16908 }
16909
16910 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16911   assert(Subtarget->isTargetWin64() && "Unexpected target");
16912   EVT VT = Op.getValueType();
16913   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16914          "Unexpected return type for lowering");
16915
16916   RTLIB::Libcall LC;
16917   bool isSigned;
16918   switch (Op->getOpcode()) {
16919   default: llvm_unreachable("Unexpected request for libcall!");
16920   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16921   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16922   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16923   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16924   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16925   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16926   }
16927
16928   SDLoc dl(Op);
16929   SDValue InChain = DAG.getEntryNode();
16930
16931   TargetLowering::ArgListTy Args;
16932   TargetLowering::ArgListEntry Entry;
16933   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16934     EVT ArgVT = Op->getOperand(i).getValueType();
16935     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16936            "Unexpected argument type for lowering");
16937     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16938     Entry.Node = StackPtr;
16939     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16940                            false, false, 16);
16941     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16942     Entry.Ty = PointerType::get(ArgTy,0);
16943     Entry.isSExt = false;
16944     Entry.isZExt = false;
16945     Args.push_back(Entry);
16946   }
16947
16948   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16949                                          getPointerTy(DAG.getDataLayout()));
16950
16951   TargetLowering::CallLoweringInfo CLI(DAG);
16952   CLI.setDebugLoc(dl).setChain(InChain)
16953     .setCallee(getLibcallCallingConv(LC),
16954                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16955                Callee, std::move(Args), 0)
16956     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16957
16958   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16959   return DAG.getBitcast(VT, CallInfo.first);
16960 }
16961
16962 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16963                              SelectionDAG &DAG) {
16964   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16965   EVT VT = Op0.getValueType();
16966   SDLoc dl(Op);
16967
16968   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16969          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16970
16971   // PMULxD operations multiply each even value (starting at 0) of LHS with
16972   // the related value of RHS and produce a widen result.
16973   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16974   // => <2 x i64> <ae|cg>
16975   //
16976   // In other word, to have all the results, we need to perform two PMULxD:
16977   // 1. one with the even values.
16978   // 2. one with the odd values.
16979   // To achieve #2, with need to place the odd values at an even position.
16980   //
16981   // Place the odd value at an even position (basically, shift all values 1
16982   // step to the left):
16983   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16984   // <a|b|c|d> => <b|undef|d|undef>
16985   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16986   // <e|f|g|h> => <f|undef|h|undef>
16987   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16988
16989   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16990   // ints.
16991   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16992   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16993   unsigned Opcode =
16994       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16995   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16996   // => <2 x i64> <ae|cg>
16997   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16998   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16999   // => <2 x i64> <bf|dh>
17000   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17001
17002   // Shuffle it back into the right order.
17003   SDValue Highs, Lows;
17004   if (VT == MVT::v8i32) {
17005     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17006     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17007     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17008     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17009   } else {
17010     const int HighMask[] = {1, 5, 3, 7};
17011     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17012     const int LowMask[] = {0, 4, 2, 6};
17013     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17014   }
17015
17016   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17017   // unsigned multiply.
17018   if (IsSigned && !Subtarget->hasSSE41()) {
17019     SDValue ShAmt = DAG.getConstant(
17020         31, dl,
17021         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17022     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17023                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17024     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17025                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17026
17027     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17028     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17029   }
17030
17031   // The first result of MUL_LOHI is actually the low value, followed by the
17032   // high value.
17033   SDValue Ops[] = {Lows, Highs};
17034   return DAG.getMergeValues(Ops, dl);
17035 }
17036
17037 // Return true if the requred (according to Opcode) shift-imm form is natively
17038 // supported by the Subtarget
17039 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17040                                         unsigned Opcode) {
17041   if (VT.getScalarSizeInBits() < 16)
17042     return false;
17043
17044   if (VT.is512BitVector() &&
17045       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17046     return true;
17047
17048   bool LShift = VT.is128BitVector() ||
17049     (VT.is256BitVector() && Subtarget->hasInt256());
17050
17051   bool AShift = LShift && (Subtarget->hasVLX() ||
17052     (VT != MVT::v2i64 && VT != MVT::v4i64));
17053   return (Opcode == ISD::SRA) ? AShift : LShift;
17054 }
17055
17056 // The shift amount is a variable, but it is the same for all vector lanes.
17057 // These instrcutions are defined together with shift-immediate.
17058 static
17059 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17060                                       unsigned Opcode) {
17061   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17062 }
17063
17064 // Return true if the requred (according to Opcode) variable-shift form is
17065 // natively supported by the Subtarget
17066 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17067                                     unsigned Opcode) {
17068
17069   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17070     return false;
17071
17072   // vXi16 supported only on AVX-512, BWI
17073   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17074     return false;
17075
17076   if (VT.is512BitVector() || Subtarget->hasVLX())
17077     return true;
17078
17079   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17080   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17081   return (Opcode == ISD::SRA) ? AShift : LShift;
17082 }
17083
17084 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17085                                          const X86Subtarget *Subtarget) {
17086   MVT VT = Op.getSimpleValueType();
17087   SDLoc dl(Op);
17088   SDValue R = Op.getOperand(0);
17089   SDValue Amt = Op.getOperand(1);
17090
17091   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17092     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17093
17094   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17095     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17096     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17097     SDValue Ex = DAG.getBitcast(ExVT, R);
17098
17099     if (ShiftAmt >= 32) {
17100       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17101       SDValue Upper =
17102           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17103       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17104                                                  ShiftAmt - 32, DAG);
17105       if (VT == MVT::v2i64)
17106         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17107       if (VT == MVT::v4i64)
17108         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17109                                   {9, 1, 11, 3, 13, 5, 15, 7});
17110     } else {
17111       // SRA upper i32, SHL whole i64 and select lower i32.
17112       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17113                                                  ShiftAmt, DAG);
17114       SDValue Lower =
17115           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17116       Lower = DAG.getBitcast(ExVT, Lower);
17117       if (VT == MVT::v2i64)
17118         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17119       if (VT == MVT::v4i64)
17120         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17121                                   {8, 1, 10, 3, 12, 5, 14, 7});
17122     }
17123     return DAG.getBitcast(VT, Ex);
17124   };
17125
17126   // Optimize shl/srl/sra with constant shift amount.
17127   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17128     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17129       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17130
17131       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17132         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17133
17134       // i64 SRA needs to be performed as partial shifts.
17135       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17136           Op.getOpcode() == ISD::SRA)
17137         return ArithmeticShiftRight64(ShiftAmt);
17138
17139       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17140         unsigned NumElts = VT.getVectorNumElements();
17141         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17142
17143         if (Op.getOpcode() == ISD::SHL) {
17144           // Simple i8 add case
17145           if (ShiftAmt == 1)
17146             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17147
17148           // Make a large shift.
17149           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17150                                                    R, ShiftAmt, DAG);
17151           SHL = DAG.getBitcast(VT, SHL);
17152           // Zero out the rightmost bits.
17153           SmallVector<SDValue, 32> V(
17154               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17155           return DAG.getNode(ISD::AND, dl, VT, SHL,
17156                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17157         }
17158         if (Op.getOpcode() == ISD::SRL) {
17159           // Make a large shift.
17160           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17161                                                    R, ShiftAmt, DAG);
17162           SRL = DAG.getBitcast(VT, SRL);
17163           // Zero out the leftmost bits.
17164           SmallVector<SDValue, 32> V(
17165               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17166           return DAG.getNode(ISD::AND, dl, VT, SRL,
17167                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17168         }
17169         if (Op.getOpcode() == ISD::SRA) {
17170           if (ShiftAmt == 7) {
17171             // R s>> 7  ===  R s< 0
17172             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17173             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17174           }
17175
17176           // R s>> a === ((R u>> a) ^ m) - m
17177           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17178           SmallVector<SDValue, 32> V(NumElts,
17179                                      DAG.getConstant(128 >> ShiftAmt, dl,
17180                                                      MVT::i8));
17181           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17182           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17183           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17184           return Res;
17185         }
17186         llvm_unreachable("Unknown shift opcode.");
17187       }
17188     }
17189   }
17190
17191   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17192   if (!Subtarget->is64Bit() &&
17193       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17194       Amt.getOpcode() == ISD::BITCAST &&
17195       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17196     Amt = Amt.getOperand(0);
17197     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17198                      VT.getVectorNumElements();
17199     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17200     uint64_t ShiftAmt = 0;
17201     for (unsigned i = 0; i != Ratio; ++i) {
17202       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17203       if (!C)
17204         return SDValue();
17205       // 6 == Log2(64)
17206       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17207     }
17208     // Check remaining shift amounts.
17209     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17210       uint64_t ShAmt = 0;
17211       for (unsigned j = 0; j != Ratio; ++j) {
17212         ConstantSDNode *C =
17213           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17214         if (!C)
17215           return SDValue();
17216         // 6 == Log2(64)
17217         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17218       }
17219       if (ShAmt != ShiftAmt)
17220         return SDValue();
17221     }
17222
17223     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17224       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17225
17226     if (Op.getOpcode() == ISD::SRA)
17227       return ArithmeticShiftRight64(ShiftAmt);
17228   }
17229
17230   return SDValue();
17231 }
17232
17233 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17234                                         const X86Subtarget* Subtarget) {
17235   MVT VT = Op.getSimpleValueType();
17236   SDLoc dl(Op);
17237   SDValue R = Op.getOperand(0);
17238   SDValue Amt = Op.getOperand(1);
17239
17240   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17241     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17242
17243   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17244     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17245
17246   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17247     SDValue BaseShAmt;
17248     EVT EltVT = VT.getVectorElementType();
17249
17250     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17251       // Check if this build_vector node is doing a splat.
17252       // If so, then set BaseShAmt equal to the splat value.
17253       BaseShAmt = BV->getSplatValue();
17254       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17255         BaseShAmt = SDValue();
17256     } else {
17257       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17258         Amt = Amt.getOperand(0);
17259
17260       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17261       if (SVN && SVN->isSplat()) {
17262         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17263         SDValue InVec = Amt.getOperand(0);
17264         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17265           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17266                  "Unexpected shuffle index found!");
17267           BaseShAmt = InVec.getOperand(SplatIdx);
17268         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17269            if (ConstantSDNode *C =
17270                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17271              if (C->getZExtValue() == SplatIdx)
17272                BaseShAmt = InVec.getOperand(1);
17273            }
17274         }
17275
17276         if (!BaseShAmt)
17277           // Avoid introducing an extract element from a shuffle.
17278           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17279                                   DAG.getIntPtrConstant(SplatIdx, dl));
17280       }
17281     }
17282
17283     if (BaseShAmt.getNode()) {
17284       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17285       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17286         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17287       else if (EltVT.bitsLT(MVT::i32))
17288         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17289
17290       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17291     }
17292   }
17293
17294   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17295   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17296       Amt.getOpcode() == ISD::BITCAST &&
17297       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17298     Amt = Amt.getOperand(0);
17299     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17300                      VT.getVectorNumElements();
17301     std::vector<SDValue> Vals(Ratio);
17302     for (unsigned i = 0; i != Ratio; ++i)
17303       Vals[i] = Amt.getOperand(i);
17304     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17305       for (unsigned j = 0; j != Ratio; ++j)
17306         if (Vals[j] != Amt.getOperand(i + j))
17307           return SDValue();
17308     }
17309
17310     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17311       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17312   }
17313   return SDValue();
17314 }
17315
17316 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17317                           SelectionDAG &DAG) {
17318   MVT VT = Op.getSimpleValueType();
17319   SDLoc dl(Op);
17320   SDValue R = Op.getOperand(0);
17321   SDValue Amt = Op.getOperand(1);
17322
17323   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17324   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17325
17326   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17327     return V;
17328
17329   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17330       return V;
17331
17332   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17333     return Op;
17334
17335   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17336   // shifts per-lane and then shuffle the partial results back together.
17337   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17338     // Splat the shift amounts so the scalar shifts above will catch it.
17339     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17340     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17341     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17342     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17343     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17344   }
17345
17346   // If possible, lower this packed shift into a vector multiply instead of
17347   // expanding it into a sequence of scalar shifts.
17348   // Do this only if the vector shift count is a constant build_vector.
17349   if (Op.getOpcode() == ISD::SHL &&
17350       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17351        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17352       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17353     SmallVector<SDValue, 8> Elts;
17354     EVT SVT = VT.getScalarType();
17355     unsigned SVTBits = SVT.getSizeInBits();
17356     const APInt &One = APInt(SVTBits, 1);
17357     unsigned NumElems = VT.getVectorNumElements();
17358
17359     for (unsigned i=0; i !=NumElems; ++i) {
17360       SDValue Op = Amt->getOperand(i);
17361       if (Op->getOpcode() == ISD::UNDEF) {
17362         Elts.push_back(Op);
17363         continue;
17364       }
17365
17366       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17367       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17368       uint64_t ShAmt = C.getZExtValue();
17369       if (ShAmt >= SVTBits) {
17370         Elts.push_back(DAG.getUNDEF(SVT));
17371         continue;
17372       }
17373       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17374     }
17375     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17376     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17377   }
17378
17379   // Lower SHL with variable shift amount.
17380   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17381     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17382
17383     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17384                      DAG.getConstant(0x3f800000U, dl, VT));
17385     Op = DAG.getBitcast(MVT::v4f32, Op);
17386     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17387     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17388   }
17389
17390   // If possible, lower this shift as a sequence of two shifts by
17391   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17392   // Example:
17393   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17394   //
17395   // Could be rewritten as:
17396   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17397   //
17398   // The advantage is that the two shifts from the example would be
17399   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17400   // the vector shift into four scalar shifts plus four pairs of vector
17401   // insert/extract.
17402   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17403       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17404     unsigned TargetOpcode = X86ISD::MOVSS;
17405     bool CanBeSimplified;
17406     // The splat value for the first packed shift (the 'X' from the example).
17407     SDValue Amt1 = Amt->getOperand(0);
17408     // The splat value for the second packed shift (the 'Y' from the example).
17409     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17410                                         Amt->getOperand(2);
17411
17412     // See if it is possible to replace this node with a sequence of
17413     // two shifts followed by a MOVSS/MOVSD
17414     if (VT == MVT::v4i32) {
17415       // Check if it is legal to use a MOVSS.
17416       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17417                         Amt2 == Amt->getOperand(3);
17418       if (!CanBeSimplified) {
17419         // Otherwise, check if we can still simplify this node using a MOVSD.
17420         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17421                           Amt->getOperand(2) == Amt->getOperand(3);
17422         TargetOpcode = X86ISD::MOVSD;
17423         Amt2 = Amt->getOperand(2);
17424       }
17425     } else {
17426       // Do similar checks for the case where the machine value type
17427       // is MVT::v8i16.
17428       CanBeSimplified = Amt1 == Amt->getOperand(1);
17429       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17430         CanBeSimplified = Amt2 == Amt->getOperand(i);
17431
17432       if (!CanBeSimplified) {
17433         TargetOpcode = X86ISD::MOVSD;
17434         CanBeSimplified = true;
17435         Amt2 = Amt->getOperand(4);
17436         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17437           CanBeSimplified = Amt1 == Amt->getOperand(i);
17438         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17439           CanBeSimplified = Amt2 == Amt->getOperand(j);
17440       }
17441     }
17442
17443     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17444         isa<ConstantSDNode>(Amt2)) {
17445       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17446       EVT CastVT = MVT::v4i32;
17447       SDValue Splat1 =
17448         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17449       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17450       SDValue Splat2 =
17451         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17452       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17453       if (TargetOpcode == X86ISD::MOVSD)
17454         CastVT = MVT::v2i64;
17455       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17456       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17457       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17458                                             BitCast1, DAG);
17459       return DAG.getBitcast(VT, Result);
17460     }
17461   }
17462
17463   // v4i32 Non Uniform Shifts.
17464   // If the shift amount is constant we can shift each lane using the SSE2
17465   // immediate shifts, else we need to zero-extend each lane to the lower i64
17466   // and shift using the SSE2 variable shifts.
17467   // The separate results can then be blended together.
17468   if (VT == MVT::v4i32) {
17469     unsigned Opc = Op.getOpcode();
17470     SDValue Amt0, Amt1, Amt2, Amt3;
17471     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17472       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17473       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17474       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17475       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17476     } else {
17477       // ISD::SHL is handled above but we include it here for completeness.
17478       switch (Opc) {
17479       default:
17480         llvm_unreachable("Unknown target vector shift node");
17481       case ISD::SHL:
17482         Opc = X86ISD::VSHL;
17483         break;
17484       case ISD::SRL:
17485         Opc = X86ISD::VSRL;
17486         break;
17487       case ISD::SRA:
17488         Opc = X86ISD::VSRA;
17489         break;
17490       }
17491       // The SSE2 shifts use the lower i64 as the same shift amount for
17492       // all lanes and the upper i64 is ignored. These shuffle masks
17493       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17494       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17495       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17496       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17497       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17498       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17499     }
17500
17501     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17502     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17503     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17504     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17505     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17506     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17507     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17508   }
17509
17510   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17511     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17512     unsigned ShiftOpcode = Op->getOpcode();
17513
17514     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17515       // On SSE41 targets we make use of the fact that VSELECT lowers
17516       // to PBLENDVB which selects bytes based just on the sign bit.
17517       if (Subtarget->hasSSE41()) {
17518         V0 = DAG.getBitcast(VT, V0);
17519         V1 = DAG.getBitcast(VT, V1);
17520         Sel = DAG.getBitcast(VT, Sel);
17521         return DAG.getBitcast(SelVT,
17522                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17523       }
17524       // On pre-SSE41 targets we test for the sign bit by comparing to
17525       // zero - a negative value will set all bits of the lanes to true
17526       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17527       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17528       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17529       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17530     };
17531
17532     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17533     // We can safely do this using i16 shifts as we're only interested in
17534     // the 3 lower bits of each byte.
17535     Amt = DAG.getBitcast(ExtVT, Amt);
17536     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17537     Amt = DAG.getBitcast(VT, Amt);
17538
17539     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17540       // r = VSELECT(r, shift(r, 4), a);
17541       SDValue M =
17542           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17543       R = SignBitSelect(VT, Amt, M, R);
17544
17545       // a += a
17546       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17547
17548       // r = VSELECT(r, shift(r, 2), a);
17549       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17550       R = SignBitSelect(VT, Amt, M, R);
17551
17552       // a += a
17553       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17554
17555       // return VSELECT(r, shift(r, 1), a);
17556       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17557       R = SignBitSelect(VT, Amt, M, R);
17558       return R;
17559     }
17560
17561     if (Op->getOpcode() == ISD::SRA) {
17562       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17563       // so we can correctly sign extend. We don't care what happens to the
17564       // lower byte.
17565       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17566       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17567       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17568       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17569       ALo = DAG.getBitcast(ExtVT, ALo);
17570       AHi = DAG.getBitcast(ExtVT, AHi);
17571       RLo = DAG.getBitcast(ExtVT, RLo);
17572       RHi = DAG.getBitcast(ExtVT, RHi);
17573
17574       // r = VSELECT(r, shift(r, 4), a);
17575       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17576                                 DAG.getConstant(4, dl, ExtVT));
17577       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17578                                 DAG.getConstant(4, dl, ExtVT));
17579       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17580       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17581
17582       // a += a
17583       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17584       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17585
17586       // r = VSELECT(r, shift(r, 2), a);
17587       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17588                         DAG.getConstant(2, dl, ExtVT));
17589       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17590                         DAG.getConstant(2, dl, ExtVT));
17591       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17592       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17593
17594       // a += a
17595       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17596       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17597
17598       // r = VSELECT(r, shift(r, 1), a);
17599       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17600                         DAG.getConstant(1, dl, ExtVT));
17601       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17602                         DAG.getConstant(1, dl, ExtVT));
17603       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17604       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17605
17606       // Logical shift the result back to the lower byte, leaving a zero upper
17607       // byte
17608       // meaning that we can safely pack with PACKUSWB.
17609       RLo =
17610           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17611       RHi =
17612           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17613       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17614     }
17615   }
17616
17617   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17618   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17619   // solution better.
17620   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17621     MVT ExtVT = MVT::v8i32;
17622     unsigned ExtOpc =
17623         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17624     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17625     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17626     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17627                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17628   }
17629
17630   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17631     MVT ExtVT = MVT::v8i32;
17632     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17633     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17634     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17635     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17636     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17637     ALo = DAG.getBitcast(ExtVT, ALo);
17638     AHi = DAG.getBitcast(ExtVT, AHi);
17639     RLo = DAG.getBitcast(ExtVT, RLo);
17640     RHi = DAG.getBitcast(ExtVT, RHi);
17641     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17642     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17643     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17644     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17645     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17646   }
17647
17648   if (VT == MVT::v8i16) {
17649     unsigned ShiftOpcode = Op->getOpcode();
17650
17651     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17652       // On SSE41 targets we make use of the fact that VSELECT lowers
17653       // to PBLENDVB which selects bytes based just on the sign bit.
17654       if (Subtarget->hasSSE41()) {
17655         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17656         V0 = DAG.getBitcast(ExtVT, V0);
17657         V1 = DAG.getBitcast(ExtVT, V1);
17658         Sel = DAG.getBitcast(ExtVT, Sel);
17659         return DAG.getBitcast(
17660             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17661       }
17662       // On pre-SSE41 targets we splat the sign bit - a negative value will
17663       // set all bits of the lanes to true and VSELECT uses that in
17664       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17665       SDValue C =
17666           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17667       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17668     };
17669
17670     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17671     if (Subtarget->hasSSE41()) {
17672       // On SSE41 targets we need to replicate the shift mask in both
17673       // bytes for PBLENDVB.
17674       Amt = DAG.getNode(
17675           ISD::OR, dl, VT,
17676           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17677           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17678     } else {
17679       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17680     }
17681
17682     // r = VSELECT(r, shift(r, 8), a);
17683     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17684     R = SignBitSelect(Amt, M, R);
17685
17686     // a += a
17687     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17688
17689     // r = VSELECT(r, shift(r, 4), a);
17690     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17691     R = SignBitSelect(Amt, M, R);
17692
17693     // a += a
17694     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17695
17696     // r = VSELECT(r, shift(r, 2), a);
17697     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17698     R = SignBitSelect(Amt, M, R);
17699
17700     // a += a
17701     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17702
17703     // return VSELECT(r, shift(r, 1), a);
17704     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17705     R = SignBitSelect(Amt, M, R);
17706     return R;
17707   }
17708
17709   // Decompose 256-bit shifts into smaller 128-bit shifts.
17710   if (VT.is256BitVector()) {
17711     unsigned NumElems = VT.getVectorNumElements();
17712     MVT EltVT = VT.getVectorElementType();
17713     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17714
17715     // Extract the two vectors
17716     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17717     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17718
17719     // Recreate the shift amount vectors
17720     SDValue Amt1, Amt2;
17721     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17722       // Constant shift amount
17723       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17724       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17725       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17726
17727       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17728       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17729     } else {
17730       // Variable shift amount
17731       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17732       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17733     }
17734
17735     // Issue new vector shifts for the smaller types
17736     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17737     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17738
17739     // Concatenate the result back
17740     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17741   }
17742
17743   return SDValue();
17744 }
17745
17746 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17747   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17748   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17749   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17750   // has only one use.
17751   SDNode *N = Op.getNode();
17752   SDValue LHS = N->getOperand(0);
17753   SDValue RHS = N->getOperand(1);
17754   unsigned BaseOp = 0;
17755   unsigned Cond = 0;
17756   SDLoc DL(Op);
17757   switch (Op.getOpcode()) {
17758   default: llvm_unreachable("Unknown ovf instruction!");
17759   case ISD::SADDO:
17760     // A subtract of one will be selected as a INC. Note that INC doesn't
17761     // set CF, so we can't do this for UADDO.
17762     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17763       if (C->isOne()) {
17764         BaseOp = X86ISD::INC;
17765         Cond = X86::COND_O;
17766         break;
17767       }
17768     BaseOp = X86ISD::ADD;
17769     Cond = X86::COND_O;
17770     break;
17771   case ISD::UADDO:
17772     BaseOp = X86ISD::ADD;
17773     Cond = X86::COND_B;
17774     break;
17775   case ISD::SSUBO:
17776     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17777     // set CF, so we can't do this for USUBO.
17778     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17779       if (C->isOne()) {
17780         BaseOp = X86ISD::DEC;
17781         Cond = X86::COND_O;
17782         break;
17783       }
17784     BaseOp = X86ISD::SUB;
17785     Cond = X86::COND_O;
17786     break;
17787   case ISD::USUBO:
17788     BaseOp = X86ISD::SUB;
17789     Cond = X86::COND_B;
17790     break;
17791   case ISD::SMULO:
17792     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17793     Cond = X86::COND_O;
17794     break;
17795   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17796     if (N->getValueType(0) == MVT::i8) {
17797       BaseOp = X86ISD::UMUL8;
17798       Cond = X86::COND_O;
17799       break;
17800     }
17801     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17802                                  MVT::i32);
17803     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17804
17805     SDValue SetCC =
17806       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17807                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17808                   SDValue(Sum.getNode(), 2));
17809
17810     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17811   }
17812   }
17813
17814   // Also sets EFLAGS.
17815   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17816   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17817
17818   SDValue SetCC =
17819     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17820                 DAG.getConstant(Cond, DL, MVT::i32),
17821                 SDValue(Sum.getNode(), 1));
17822
17823   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17824 }
17825
17826 /// Returns true if the operand type is exactly twice the native width, and
17827 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17828 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17829 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17830 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17831   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17832
17833   if (OpWidth == 64)
17834     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17835   else if (OpWidth == 128)
17836     return Subtarget->hasCmpxchg16b();
17837   else
17838     return false;
17839 }
17840
17841 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17842   return needsCmpXchgNb(SI->getValueOperand()->getType());
17843 }
17844
17845 // Note: this turns large loads into lock cmpxchg8b/16b.
17846 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17847 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17848   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17849   return needsCmpXchgNb(PTy->getElementType());
17850 }
17851
17852 TargetLoweringBase::AtomicRMWExpansionKind
17853 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17854   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17855   const Type *MemType = AI->getType();
17856
17857   // If the operand is too big, we must see if cmpxchg8/16b is available
17858   // and default to library calls otherwise.
17859   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17860     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17861                                    : AtomicRMWExpansionKind::None;
17862   }
17863
17864   AtomicRMWInst::BinOp Op = AI->getOperation();
17865   switch (Op) {
17866   default:
17867     llvm_unreachable("Unknown atomic operation");
17868   case AtomicRMWInst::Xchg:
17869   case AtomicRMWInst::Add:
17870   case AtomicRMWInst::Sub:
17871     // It's better to use xadd, xsub or xchg for these in all cases.
17872     return AtomicRMWExpansionKind::None;
17873   case AtomicRMWInst::Or:
17874   case AtomicRMWInst::And:
17875   case AtomicRMWInst::Xor:
17876     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17877     // prefix to a normal instruction for these operations.
17878     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17879                             : AtomicRMWExpansionKind::None;
17880   case AtomicRMWInst::Nand:
17881   case AtomicRMWInst::Max:
17882   case AtomicRMWInst::Min:
17883   case AtomicRMWInst::UMax:
17884   case AtomicRMWInst::UMin:
17885     // These always require a non-trivial set of data operations on x86. We must
17886     // use a cmpxchg loop.
17887     return AtomicRMWExpansionKind::CmpXChg;
17888   }
17889 }
17890
17891 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17892   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17893   // no-sse2). There isn't any reason to disable it if the target processor
17894   // supports it.
17895   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17896 }
17897
17898 LoadInst *
17899 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17900   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17901   const Type *MemType = AI->getType();
17902   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17903   // there is no benefit in turning such RMWs into loads, and it is actually
17904   // harmful as it introduces a mfence.
17905   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17906     return nullptr;
17907
17908   auto Builder = IRBuilder<>(AI);
17909   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17910   auto SynchScope = AI->getSynchScope();
17911   // We must restrict the ordering to avoid generating loads with Release or
17912   // ReleaseAcquire orderings.
17913   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17914   auto Ptr = AI->getPointerOperand();
17915
17916   // Before the load we need a fence. Here is an example lifted from
17917   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17918   // is required:
17919   // Thread 0:
17920   //   x.store(1, relaxed);
17921   //   r1 = y.fetch_add(0, release);
17922   // Thread 1:
17923   //   y.fetch_add(42, acquire);
17924   //   r2 = x.load(relaxed);
17925   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17926   // lowered to just a load without a fence. A mfence flushes the store buffer,
17927   // making the optimization clearly correct.
17928   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17929   // otherwise, we might be able to be more agressive on relaxed idempotent
17930   // rmw. In practice, they do not look useful, so we don't try to be
17931   // especially clever.
17932   if (SynchScope == SingleThread)
17933     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17934     // the IR level, so we must wrap it in an intrinsic.
17935     return nullptr;
17936
17937   if (!hasMFENCE(*Subtarget))
17938     // FIXME: it might make sense to use a locked operation here but on a
17939     // different cache-line to prevent cache-line bouncing. In practice it
17940     // is probably a small win, and x86 processors without mfence are rare
17941     // enough that we do not bother.
17942     return nullptr;
17943
17944   Function *MFence =
17945       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17946   Builder.CreateCall(MFence, {});
17947
17948   // Finally we can emit the atomic load.
17949   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17950           AI->getType()->getPrimitiveSizeInBits());
17951   Loaded->setAtomic(Order, SynchScope);
17952   AI->replaceAllUsesWith(Loaded);
17953   AI->eraseFromParent();
17954   return Loaded;
17955 }
17956
17957 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17958                                  SelectionDAG &DAG) {
17959   SDLoc dl(Op);
17960   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17961     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17962   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17963     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17964
17965   // The only fence that needs an instruction is a sequentially-consistent
17966   // cross-thread fence.
17967   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17968     if (hasMFENCE(*Subtarget))
17969       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17970
17971     SDValue Chain = Op.getOperand(0);
17972     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17973     SDValue Ops[] = {
17974       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17975       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17976       DAG.getRegister(0, MVT::i32),            // Index
17977       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17978       DAG.getRegister(0, MVT::i32),            // Segment.
17979       Zero,
17980       Chain
17981     };
17982     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17983     return SDValue(Res, 0);
17984   }
17985
17986   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17987   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17988 }
17989
17990 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17991                              SelectionDAG &DAG) {
17992   MVT T = Op.getSimpleValueType();
17993   SDLoc DL(Op);
17994   unsigned Reg = 0;
17995   unsigned size = 0;
17996   switch(T.SimpleTy) {
17997   default: llvm_unreachable("Invalid value type!");
17998   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17999   case MVT::i16: Reg = X86::AX;  size = 2; break;
18000   case MVT::i32: Reg = X86::EAX; size = 4; break;
18001   case MVT::i64:
18002     assert(Subtarget->is64Bit() && "Node not type legal!");
18003     Reg = X86::RAX; size = 8;
18004     break;
18005   }
18006   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18007                                   Op.getOperand(2), SDValue());
18008   SDValue Ops[] = { cpIn.getValue(0),
18009                     Op.getOperand(1),
18010                     Op.getOperand(3),
18011                     DAG.getTargetConstant(size, DL, MVT::i8),
18012                     cpIn.getValue(1) };
18013   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18014   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18015   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18016                                            Ops, T, MMO);
18017
18018   SDValue cpOut =
18019     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18020   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18021                                       MVT::i32, cpOut.getValue(2));
18022   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18023                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18024                                 EFLAGS);
18025
18026   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18027   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18028   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18029   return SDValue();
18030 }
18031
18032 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18033                             SelectionDAG &DAG) {
18034   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18035   MVT DstVT = Op.getSimpleValueType();
18036
18037   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18038     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18039     if (DstVT != MVT::f64)
18040       // This conversion needs to be expanded.
18041       return SDValue();
18042
18043     SDValue InVec = Op->getOperand(0);
18044     SDLoc dl(Op);
18045     unsigned NumElts = SrcVT.getVectorNumElements();
18046     EVT SVT = SrcVT.getVectorElementType();
18047
18048     // Widen the vector in input in the case of MVT::v2i32.
18049     // Example: from MVT::v2i32 to MVT::v4i32.
18050     SmallVector<SDValue, 16> Elts;
18051     for (unsigned i = 0, e = NumElts; i != e; ++i)
18052       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18053                                  DAG.getIntPtrConstant(i, dl)));
18054
18055     // Explicitly mark the extra elements as Undef.
18056     Elts.append(NumElts, DAG.getUNDEF(SVT));
18057
18058     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18059     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18060     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18061     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18062                        DAG.getIntPtrConstant(0, dl));
18063   }
18064
18065   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18066          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18067   assert((DstVT == MVT::i64 ||
18068           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18069          "Unexpected custom BITCAST");
18070   // i64 <=> MMX conversions are Legal.
18071   if (SrcVT==MVT::i64 && DstVT.isVector())
18072     return Op;
18073   if (DstVT==MVT::i64 && SrcVT.isVector())
18074     return Op;
18075   // MMX <=> MMX conversions are Legal.
18076   if (SrcVT.isVector() && DstVT.isVector())
18077     return Op;
18078   // All other conversions need to be expanded.
18079   return SDValue();
18080 }
18081
18082 /// Compute the horizontal sum of bytes in V for the elements of VT.
18083 ///
18084 /// Requires V to be a byte vector and VT to be an integer vector type with
18085 /// wider elements than V's type. The width of the elements of VT determines
18086 /// how many bytes of V are summed horizontally to produce each element of the
18087 /// result.
18088 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18089                                       const X86Subtarget *Subtarget,
18090                                       SelectionDAG &DAG) {
18091   SDLoc DL(V);
18092   MVT ByteVecVT = V.getSimpleValueType();
18093   MVT EltVT = VT.getVectorElementType();
18094   int NumElts = VT.getVectorNumElements();
18095   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18096          "Expected value to have byte element type.");
18097   assert(EltVT != MVT::i8 &&
18098          "Horizontal byte sum only makes sense for wider elements!");
18099   unsigned VecSize = VT.getSizeInBits();
18100   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18101
18102   // PSADBW instruction horizontally add all bytes and leave the result in i64
18103   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18104   if (EltVT == MVT::i64) {
18105     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18106     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18107     return DAG.getBitcast(VT, V);
18108   }
18109
18110   if (EltVT == MVT::i32) {
18111     // We unpack the low half and high half into i32s interleaved with zeros so
18112     // that we can use PSADBW to horizontally sum them. The most useful part of
18113     // this is that it lines up the results of two PSADBW instructions to be
18114     // two v2i64 vectors which concatenated are the 4 population counts. We can
18115     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18116     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18117     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18118     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18119
18120     // Do the horizontal sums into two v2i64s.
18121     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18122     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18123                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18124     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18125                        DAG.getBitcast(ByteVecVT, High), Zeros);
18126
18127     // Merge them together.
18128     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18129     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18130                     DAG.getBitcast(ShortVecVT, Low),
18131                     DAG.getBitcast(ShortVecVT, High));
18132
18133     return DAG.getBitcast(VT, V);
18134   }
18135
18136   // The only element type left is i16.
18137   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18138
18139   // To obtain pop count for each i16 element starting from the pop count for
18140   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18141   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18142   // directly supported.
18143   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18144   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18145   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18146   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18147                   DAG.getBitcast(ByteVecVT, V));
18148   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18149 }
18150
18151 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18152                                         const X86Subtarget *Subtarget,
18153                                         SelectionDAG &DAG) {
18154   MVT VT = Op.getSimpleValueType();
18155   MVT EltVT = VT.getVectorElementType();
18156   unsigned VecSize = VT.getSizeInBits();
18157
18158   // Implement a lookup table in register by using an algorithm based on:
18159   // http://wm.ite.pl/articles/sse-popcount.html
18160   //
18161   // The general idea is that every lower byte nibble in the input vector is an
18162   // index into a in-register pre-computed pop count table. We then split up the
18163   // input vector in two new ones: (1) a vector with only the shifted-right
18164   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18165   // masked out higher ones) for each byte. PSHUB is used separately with both
18166   // to index the in-register table. Next, both are added and the result is a
18167   // i8 vector where each element contains the pop count for input byte.
18168   //
18169   // To obtain the pop count for elements != i8, we follow up with the same
18170   // approach and use additional tricks as described below.
18171   //
18172   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18173                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18174                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18175                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18176
18177   int NumByteElts = VecSize / 8;
18178   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18179   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18180   SmallVector<SDValue, 16> LUTVec;
18181   for (int i = 0; i < NumByteElts; ++i)
18182     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18183   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18184   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18185                                   DAG.getConstant(0x0F, DL, MVT::i8));
18186   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18187
18188   // High nibbles
18189   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18190   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18191   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18192
18193   // Low nibbles
18194   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18195
18196   // The input vector is used as the shuffle mask that index elements into the
18197   // LUT. After counting low and high nibbles, add the vector to obtain the
18198   // final pop count per i8 element.
18199   SDValue HighPopCnt =
18200       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18201   SDValue LowPopCnt =
18202       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18203   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18204
18205   if (EltVT == MVT::i8)
18206     return PopCnt;
18207
18208   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18209 }
18210
18211 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18212                                        const X86Subtarget *Subtarget,
18213                                        SelectionDAG &DAG) {
18214   MVT VT = Op.getSimpleValueType();
18215   assert(VT.is128BitVector() &&
18216          "Only 128-bit vector bitmath lowering supported.");
18217
18218   int VecSize = VT.getSizeInBits();
18219   MVT EltVT = VT.getVectorElementType();
18220   int Len = EltVT.getSizeInBits();
18221
18222   // This is the vectorized version of the "best" algorithm from
18223   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18224   // with a minor tweak to use a series of adds + shifts instead of vector
18225   // multiplications. Implemented for all integer vector types. We only use
18226   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18227   // much faster, even faster than using native popcnt instructions.
18228
18229   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18230     MVT VT = V.getSimpleValueType();
18231     SmallVector<SDValue, 32> Shifters(
18232         VT.getVectorNumElements(),
18233         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18234     return DAG.getNode(OpCode, DL, VT, V,
18235                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18236   };
18237   auto GetMask = [&](SDValue V, APInt Mask) {
18238     MVT VT = V.getSimpleValueType();
18239     SmallVector<SDValue, 32> Masks(
18240         VT.getVectorNumElements(),
18241         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18242     return DAG.getNode(ISD::AND, DL, VT, V,
18243                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18244   };
18245
18246   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18247   // x86, so set the SRL type to have elements at least i16 wide. This is
18248   // correct because all of our SRLs are followed immediately by a mask anyways
18249   // that handles any bits that sneak into the high bits of the byte elements.
18250   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18251
18252   SDValue V = Op;
18253
18254   // v = v - ((v >> 1) & 0x55555555...)
18255   SDValue Srl =
18256       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18257   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18258   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18259
18260   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18261   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18262   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18263   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18264   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18265
18266   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18267   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18268   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18269   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18270
18271   // At this point, V contains the byte-wise population count, and we are
18272   // merely doing a horizontal sum if necessary to get the wider element
18273   // counts.
18274   if (EltVT == MVT::i8)
18275     return V;
18276
18277   return LowerHorizontalByteSum(
18278       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18279       DAG);
18280 }
18281
18282 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18283                                 SelectionDAG &DAG) {
18284   MVT VT = Op.getSimpleValueType();
18285   // FIXME: Need to add AVX-512 support here!
18286   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18287          "Unknown CTPOP type to handle");
18288   SDLoc DL(Op.getNode());
18289   SDValue Op0 = Op.getOperand(0);
18290
18291   if (!Subtarget->hasSSSE3()) {
18292     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18293     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18294     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18295   }
18296
18297   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18298     unsigned NumElems = VT.getVectorNumElements();
18299
18300     // Extract each 128-bit vector, compute pop count and concat the result.
18301     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18302     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18303
18304     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18305                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18306                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18307   }
18308
18309   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18310 }
18311
18312 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18313                           SelectionDAG &DAG) {
18314   assert(Op.getValueType().isVector() &&
18315          "We only do custom lowering for vector population count.");
18316   return LowerVectorCTPOP(Op, Subtarget, DAG);
18317 }
18318
18319 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18320   SDNode *Node = Op.getNode();
18321   SDLoc dl(Node);
18322   EVT T = Node->getValueType(0);
18323   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18324                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18325   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18326                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18327                        Node->getOperand(0),
18328                        Node->getOperand(1), negOp,
18329                        cast<AtomicSDNode>(Node)->getMemOperand(),
18330                        cast<AtomicSDNode>(Node)->getOrdering(),
18331                        cast<AtomicSDNode>(Node)->getSynchScope());
18332 }
18333
18334 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18335   SDNode *Node = Op.getNode();
18336   SDLoc dl(Node);
18337   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18338
18339   // Convert seq_cst store -> xchg
18340   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18341   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18342   //        (The only way to get a 16-byte store is cmpxchg16b)
18343   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18344   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18345       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18346     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18347                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18348                                  Node->getOperand(0),
18349                                  Node->getOperand(1), Node->getOperand(2),
18350                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18351                                  cast<AtomicSDNode>(Node)->getOrdering(),
18352                                  cast<AtomicSDNode>(Node)->getSynchScope());
18353     return Swap.getValue(1);
18354   }
18355   // Other atomic stores have a simple pattern.
18356   return Op;
18357 }
18358
18359 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18360   EVT VT = Op.getNode()->getSimpleValueType(0);
18361
18362   // Let legalize expand this if it isn't a legal type yet.
18363   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18364     return SDValue();
18365
18366   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18367
18368   unsigned Opc;
18369   bool ExtraOp = false;
18370   switch (Op.getOpcode()) {
18371   default: llvm_unreachable("Invalid code");
18372   case ISD::ADDC: Opc = X86ISD::ADD; break;
18373   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18374   case ISD::SUBC: Opc = X86ISD::SUB; break;
18375   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18376   }
18377
18378   if (!ExtraOp)
18379     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18380                        Op.getOperand(1));
18381   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18382                      Op.getOperand(1), Op.getOperand(2));
18383 }
18384
18385 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18386                             SelectionDAG &DAG) {
18387   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18388
18389   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18390   // which returns the values as { float, float } (in XMM0) or
18391   // { double, double } (which is returned in XMM0, XMM1).
18392   SDLoc dl(Op);
18393   SDValue Arg = Op.getOperand(0);
18394   EVT ArgVT = Arg.getValueType();
18395   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18396
18397   TargetLowering::ArgListTy Args;
18398   TargetLowering::ArgListEntry Entry;
18399
18400   Entry.Node = Arg;
18401   Entry.Ty = ArgTy;
18402   Entry.isSExt = false;
18403   Entry.isZExt = false;
18404   Args.push_back(Entry);
18405
18406   bool isF64 = ArgVT == MVT::f64;
18407   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18408   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18409   // the results are returned via SRet in memory.
18410   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18412   SDValue Callee =
18413       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18414
18415   Type *RetTy = isF64
18416     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18417     : (Type*)VectorType::get(ArgTy, 4);
18418
18419   TargetLowering::CallLoweringInfo CLI(DAG);
18420   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18421     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18422
18423   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18424
18425   if (isF64)
18426     // Returned in xmm0 and xmm1.
18427     return CallResult.first;
18428
18429   // Returned in bits 0:31 and 32:64 xmm0.
18430   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18431                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18432   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18433                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18434   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18435   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18436 }
18437
18438 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18439                              SelectionDAG &DAG) {
18440   assert(Subtarget->hasAVX512() &&
18441          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18442
18443   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18444   EVT VT = N->getValue().getValueType();
18445   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18446   SDLoc dl(Op);
18447
18448   // X86 scatter kills mask register, so its type should be added to
18449   // the list of return values
18450   if (N->getNumValues() == 1) {
18451     SDValue Index = N->getIndex();
18452     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18453         !Index.getValueType().is512BitVector())
18454       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18455
18456     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18457     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18458                       N->getOperand(3), Index };
18459
18460     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18461     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18462     return SDValue(NewScatter.getNode(), 0);
18463   }
18464   return Op;
18465 }
18466
18467 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18468                             SelectionDAG &DAG) {
18469   assert(Subtarget->hasAVX512() &&
18470          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18471
18472   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18473   EVT VT = Op.getValueType();
18474   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18475   SDLoc dl(Op);
18476
18477   SDValue Index = N->getIndex();
18478   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18479       !Index.getValueType().is512BitVector()) {
18480     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18481     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18482                       N->getOperand(3), Index };
18483     DAG.UpdateNodeOperands(N, Ops);
18484   }
18485   return Op;
18486 }
18487
18488 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18489                                                     SelectionDAG &DAG) const {
18490   // TODO: Eventually, the lowering of these nodes should be informed by or
18491   // deferred to the GC strategy for the function in which they appear. For
18492   // now, however, they must be lowered to something. Since they are logically
18493   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18494   // require special handling for these nodes), lower them as literal NOOPs for
18495   // the time being.
18496   SmallVector<SDValue, 2> Ops;
18497
18498   Ops.push_back(Op.getOperand(0));
18499   if (Op->getGluedNode())
18500     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18501
18502   SDLoc OpDL(Op);
18503   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18504   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18505
18506   return NOOP;
18507 }
18508
18509 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18510                                                   SelectionDAG &DAG) const {
18511   // TODO: Eventually, the lowering of these nodes should be informed by or
18512   // deferred to the GC strategy for the function in which they appear. For
18513   // now, however, they must be lowered to something. Since they are logically
18514   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18515   // require special handling for these nodes), lower them as literal NOOPs for
18516   // the time being.
18517   SmallVector<SDValue, 2> Ops;
18518
18519   Ops.push_back(Op.getOperand(0));
18520   if (Op->getGluedNode())
18521     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18522
18523   SDLoc OpDL(Op);
18524   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18525   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18526
18527   return NOOP;
18528 }
18529
18530 /// LowerOperation - Provide custom lowering hooks for some operations.
18531 ///
18532 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18533   switch (Op.getOpcode()) {
18534   default: llvm_unreachable("Should not custom lower this!");
18535   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18536   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18537     return LowerCMP_SWAP(Op, Subtarget, DAG);
18538   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18539   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18540   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18541   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18542   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18543   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18544   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18545   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18546   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18547   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18548   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18549   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18550   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18551   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18552   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18553   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18554   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18555   case ISD::SHL_PARTS:
18556   case ISD::SRA_PARTS:
18557   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18558   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18559   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18560   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18561   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18562   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18563   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18564   case ISD::SIGN_EXTEND_VECTOR_INREG:
18565     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18566   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18567   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18568   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18569   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18570   case ISD::FABS:
18571   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18572   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18573   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18574   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18575   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18576   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18577   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18578   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18579   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18580   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18581   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18582   case ISD::INTRINSIC_VOID:
18583   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18584   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18585   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18586   case ISD::FRAME_TO_ARGS_OFFSET:
18587                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18588   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18589   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18590   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18591   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18592   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18593   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18594   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18595   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18596   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18597   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18598   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18599   case ISD::UMUL_LOHI:
18600   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18601   case ISD::SRA:
18602   case ISD::SRL:
18603   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18604   case ISD::SADDO:
18605   case ISD::UADDO:
18606   case ISD::SSUBO:
18607   case ISD::USUBO:
18608   case ISD::SMULO:
18609   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18610   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18611   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18612   case ISD::ADDC:
18613   case ISD::ADDE:
18614   case ISD::SUBC:
18615   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18616   case ISD::ADD:                return LowerADD(Op, DAG);
18617   case ISD::SUB:                return LowerSUB(Op, DAG);
18618   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18619   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18620   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18621   case ISD::GC_TRANSITION_START:
18622                                 return LowerGC_TRANSITION_START(Op, DAG);
18623   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18624   }
18625 }
18626
18627 /// ReplaceNodeResults - Replace a node with an illegal result type
18628 /// with a new node built out of custom code.
18629 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18630                                            SmallVectorImpl<SDValue>&Results,
18631                                            SelectionDAG &DAG) const {
18632   SDLoc dl(N);
18633   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18634   switch (N->getOpcode()) {
18635   default:
18636     llvm_unreachable("Do not know how to custom type legalize this operation!");
18637   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18638   case X86ISD::FMINC:
18639   case X86ISD::FMIN:
18640   case X86ISD::FMAXC:
18641   case X86ISD::FMAX: {
18642     EVT VT = N->getValueType(0);
18643     if (VT != MVT::v2f32)
18644       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18645     SDValue UNDEF = DAG.getUNDEF(VT);
18646     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18647                               N->getOperand(0), UNDEF);
18648     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18649                               N->getOperand(1), UNDEF);
18650     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18651     return;
18652   }
18653   case ISD::SIGN_EXTEND_INREG:
18654   case ISD::ADDC:
18655   case ISD::ADDE:
18656   case ISD::SUBC:
18657   case ISD::SUBE:
18658     // We don't want to expand or promote these.
18659     return;
18660   case ISD::SDIV:
18661   case ISD::UDIV:
18662   case ISD::SREM:
18663   case ISD::UREM:
18664   case ISD::SDIVREM:
18665   case ISD::UDIVREM: {
18666     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18667     Results.push_back(V);
18668     return;
18669   }
18670   case ISD::FP_TO_SINT:
18671     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18672     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18673     if (N->getOperand(0).getValueType() == MVT::f16)
18674       break;
18675     // fallthrough
18676   case ISD::FP_TO_UINT: {
18677     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18678
18679     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18680       return;
18681
18682     std::pair<SDValue,SDValue> Vals =
18683         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18684     SDValue FIST = Vals.first, StackSlot = Vals.second;
18685     if (FIST.getNode()) {
18686       EVT VT = N->getValueType(0);
18687       // Return a load from the stack slot.
18688       if (StackSlot.getNode())
18689         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18690                                       MachinePointerInfo(),
18691                                       false, false, false, 0));
18692       else
18693         Results.push_back(FIST);
18694     }
18695     return;
18696   }
18697   case ISD::UINT_TO_FP: {
18698     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18699     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18700         N->getValueType(0) != MVT::v2f32)
18701       return;
18702     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18703                                  N->getOperand(0));
18704     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18705                                      MVT::f64);
18706     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18707     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18708                              DAG.getBitcast(MVT::v2i64, VBias));
18709     Or = DAG.getBitcast(MVT::v2f64, Or);
18710     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18711     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18712     return;
18713   }
18714   case ISD::FP_ROUND: {
18715     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18716         return;
18717     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18718     Results.push_back(V);
18719     return;
18720   }
18721   case ISD::FP_EXTEND: {
18722     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18723     // No other ValueType for FP_EXTEND should reach this point.
18724     assert(N->getValueType(0) == MVT::v2f32 &&
18725            "Do not know how to legalize this Node");
18726     return;
18727   }
18728   case ISD::INTRINSIC_W_CHAIN: {
18729     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18730     switch (IntNo) {
18731     default : llvm_unreachable("Do not know how to custom type "
18732                                "legalize this intrinsic operation!");
18733     case Intrinsic::x86_rdtsc:
18734       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18735                                      Results);
18736     case Intrinsic::x86_rdtscp:
18737       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18738                                      Results);
18739     case Intrinsic::x86_rdpmc:
18740       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18741     }
18742   }
18743   case ISD::READCYCLECOUNTER: {
18744     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18745                                    Results);
18746   }
18747   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18748     EVT T = N->getValueType(0);
18749     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18750     bool Regs64bit = T == MVT::i128;
18751     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18752     SDValue cpInL, cpInH;
18753     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18754                         DAG.getConstant(0, dl, HalfT));
18755     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18756                         DAG.getConstant(1, dl, HalfT));
18757     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18758                              Regs64bit ? X86::RAX : X86::EAX,
18759                              cpInL, SDValue());
18760     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18761                              Regs64bit ? X86::RDX : X86::EDX,
18762                              cpInH, cpInL.getValue(1));
18763     SDValue swapInL, swapInH;
18764     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18765                           DAG.getConstant(0, dl, HalfT));
18766     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18767                           DAG.getConstant(1, dl, HalfT));
18768     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18769                                Regs64bit ? X86::RBX : X86::EBX,
18770                                swapInL, cpInH.getValue(1));
18771     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18772                                Regs64bit ? X86::RCX : X86::ECX,
18773                                swapInH, swapInL.getValue(1));
18774     SDValue Ops[] = { swapInH.getValue(0),
18775                       N->getOperand(1),
18776                       swapInH.getValue(1) };
18777     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18778     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18779     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18780                                   X86ISD::LCMPXCHG8_DAG;
18781     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18782     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18783                                         Regs64bit ? X86::RAX : X86::EAX,
18784                                         HalfT, Result.getValue(1));
18785     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18786                                         Regs64bit ? X86::RDX : X86::EDX,
18787                                         HalfT, cpOutL.getValue(2));
18788     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18789
18790     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18791                                         MVT::i32, cpOutH.getValue(2));
18792     SDValue Success =
18793         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18794                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18795     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18796
18797     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18798     Results.push_back(Success);
18799     Results.push_back(EFLAGS.getValue(1));
18800     return;
18801   }
18802   case ISD::ATOMIC_SWAP:
18803   case ISD::ATOMIC_LOAD_ADD:
18804   case ISD::ATOMIC_LOAD_SUB:
18805   case ISD::ATOMIC_LOAD_AND:
18806   case ISD::ATOMIC_LOAD_OR:
18807   case ISD::ATOMIC_LOAD_XOR:
18808   case ISD::ATOMIC_LOAD_NAND:
18809   case ISD::ATOMIC_LOAD_MIN:
18810   case ISD::ATOMIC_LOAD_MAX:
18811   case ISD::ATOMIC_LOAD_UMIN:
18812   case ISD::ATOMIC_LOAD_UMAX:
18813   case ISD::ATOMIC_LOAD: {
18814     // Delegate to generic TypeLegalization. Situations we can really handle
18815     // should have already been dealt with by AtomicExpandPass.cpp.
18816     break;
18817   }
18818   case ISD::BITCAST: {
18819     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18820     EVT DstVT = N->getValueType(0);
18821     EVT SrcVT = N->getOperand(0)->getValueType(0);
18822
18823     if (SrcVT != MVT::f64 ||
18824         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18825       return;
18826
18827     unsigned NumElts = DstVT.getVectorNumElements();
18828     EVT SVT = DstVT.getVectorElementType();
18829     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18830     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18831                                    MVT::v2f64, N->getOperand(0));
18832     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18833
18834     if (ExperimentalVectorWideningLegalization) {
18835       // If we are legalizing vectors by widening, we already have the desired
18836       // legal vector type, just return it.
18837       Results.push_back(ToVecInt);
18838       return;
18839     }
18840
18841     SmallVector<SDValue, 8> Elts;
18842     for (unsigned i = 0, e = NumElts; i != e; ++i)
18843       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18844                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18845
18846     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18847   }
18848   }
18849 }
18850
18851 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18852   switch ((X86ISD::NodeType)Opcode) {
18853   case X86ISD::FIRST_NUMBER:       break;
18854   case X86ISD::BSF:                return "X86ISD::BSF";
18855   case X86ISD::BSR:                return "X86ISD::BSR";
18856   case X86ISD::SHLD:               return "X86ISD::SHLD";
18857   case X86ISD::SHRD:               return "X86ISD::SHRD";
18858   case X86ISD::FAND:               return "X86ISD::FAND";
18859   case X86ISD::FANDN:              return "X86ISD::FANDN";
18860   case X86ISD::FOR:                return "X86ISD::FOR";
18861   case X86ISD::FXOR:               return "X86ISD::FXOR";
18862   case X86ISD::FILD:               return "X86ISD::FILD";
18863   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18864   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18865   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18866   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18867   case X86ISD::FLD:                return "X86ISD::FLD";
18868   case X86ISD::FST:                return "X86ISD::FST";
18869   case X86ISD::CALL:               return "X86ISD::CALL";
18870   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18871   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18872   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18873   case X86ISD::BT:                 return "X86ISD::BT";
18874   case X86ISD::CMP:                return "X86ISD::CMP";
18875   case X86ISD::COMI:               return "X86ISD::COMI";
18876   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18877   case X86ISD::CMPM:               return "X86ISD::CMPM";
18878   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18879   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18880   case X86ISD::SETCC:              return "X86ISD::SETCC";
18881   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18882   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18883   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18884   case X86ISD::CMOV:               return "X86ISD::CMOV";
18885   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18886   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18887   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18888   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18889   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18890   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18891   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18892   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18893   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18894   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18895   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18896   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18897   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18898   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18899   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18900   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18901   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18902   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18903   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18904   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18905   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18906   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18907   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18908   case X86ISD::HADD:               return "X86ISD::HADD";
18909   case X86ISD::HSUB:               return "X86ISD::HSUB";
18910   case X86ISD::FHADD:              return "X86ISD::FHADD";
18911   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18912   case X86ISD::ABS:                return "X86ISD::ABS";
18913   case X86ISD::FMAX:               return "X86ISD::FMAX";
18914   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18915   case X86ISD::FMIN:               return "X86ISD::FMIN";
18916   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18917   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18918   case X86ISD::FMINC:              return "X86ISD::FMINC";
18919   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18920   case X86ISD::FRCP:               return "X86ISD::FRCP";
18921   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
18922   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
18923   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18924   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18925   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18926   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18927   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18928   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18929   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18930   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18931   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18932   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18933   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18934   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18935   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18936   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18937   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18938   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18939   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18940   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18941   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18942   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18943   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18944   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18945   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
18946   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18947   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18948   case X86ISD::VSHL:               return "X86ISD::VSHL";
18949   case X86ISD::VSRL:               return "X86ISD::VSRL";
18950   case X86ISD::VSRA:               return "X86ISD::VSRA";
18951   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18952   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18953   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18954   case X86ISD::CMPP:               return "X86ISD::CMPP";
18955   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18956   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18957   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18958   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18959   case X86ISD::ADD:                return "X86ISD::ADD";
18960   case X86ISD::SUB:                return "X86ISD::SUB";
18961   case X86ISD::ADC:                return "X86ISD::ADC";
18962   case X86ISD::SBB:                return "X86ISD::SBB";
18963   case X86ISD::SMUL:               return "X86ISD::SMUL";
18964   case X86ISD::UMUL:               return "X86ISD::UMUL";
18965   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18966   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18967   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18968   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18969   case X86ISD::INC:                return "X86ISD::INC";
18970   case X86ISD::DEC:                return "X86ISD::DEC";
18971   case X86ISD::OR:                 return "X86ISD::OR";
18972   case X86ISD::XOR:                return "X86ISD::XOR";
18973   case X86ISD::AND:                return "X86ISD::AND";
18974   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18975   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18976   case X86ISD::PTEST:              return "X86ISD::PTEST";
18977   case X86ISD::TESTP:              return "X86ISD::TESTP";
18978   case X86ISD::TESTM:              return "X86ISD::TESTM";
18979   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18980   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18981   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18982   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18983   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18984   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18985   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18986   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18987   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18988   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18989   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
18990   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18991   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18992   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18993   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18994   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18995   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18996   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18997   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18998   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18999   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19000   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19001   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19002   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19003   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19004   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19005   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19006   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19007   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19008   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19009   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19010   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19011   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19012   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19013   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19014   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19015   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19016   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19017   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19018   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19019   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19020   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19021   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19022   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19023   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19024   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19025   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19026   case X86ISD::SAHF:               return "X86ISD::SAHF";
19027   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19028   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19029   case X86ISD::FMADD:              return "X86ISD::FMADD";
19030   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19031   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19032   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19033   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19034   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19035   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19036   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19037   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19038   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19039   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19040   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19041   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
19042   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19043   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19044   case X86ISD::XTEST:              return "X86ISD::XTEST";
19045   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19046   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19047   case X86ISD::SELECT:             return "X86ISD::SELECT";
19048   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19049   case X86ISD::RCP28:              return "X86ISD::RCP28";
19050   case X86ISD::EXP2:               return "X86ISD::EXP2";
19051   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19052   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19053   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19054   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19055   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19056   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19057   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19058   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19059   case X86ISD::ADDS:               return "X86ISD::ADDS";
19060   case X86ISD::SUBS:               return "X86ISD::SUBS";
19061   case X86ISD::AVG:                return "X86ISD::AVG";
19062   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19063   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19064   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19065   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19066   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19067   }
19068   return nullptr;
19069 }
19070
19071 // isLegalAddressingMode - Return true if the addressing mode represented
19072 // by AM is legal for this target, for a load/store of the specified type.
19073 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19074                                               const AddrMode &AM, Type *Ty,
19075                                               unsigned AS) const {
19076   // X86 supports extremely general addressing modes.
19077   CodeModel::Model M = getTargetMachine().getCodeModel();
19078   Reloc::Model R = getTargetMachine().getRelocationModel();
19079
19080   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19081   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19082     return false;
19083
19084   if (AM.BaseGV) {
19085     unsigned GVFlags =
19086       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19087
19088     // If a reference to this global requires an extra load, we can't fold it.
19089     if (isGlobalStubReference(GVFlags))
19090       return false;
19091
19092     // If BaseGV requires a register for the PIC base, we cannot also have a
19093     // BaseReg specified.
19094     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19095       return false;
19096
19097     // If lower 4G is not available, then we must use rip-relative addressing.
19098     if ((M != CodeModel::Small || R != Reloc::Static) &&
19099         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19100       return false;
19101   }
19102
19103   switch (AM.Scale) {
19104   case 0:
19105   case 1:
19106   case 2:
19107   case 4:
19108   case 8:
19109     // These scales always work.
19110     break;
19111   case 3:
19112   case 5:
19113   case 9:
19114     // These scales are formed with basereg+scalereg.  Only accept if there is
19115     // no basereg yet.
19116     if (AM.HasBaseReg)
19117       return false;
19118     break;
19119   default:  // Other stuff never works.
19120     return false;
19121   }
19122
19123   return true;
19124 }
19125
19126 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19127   unsigned Bits = Ty->getScalarSizeInBits();
19128
19129   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19130   // particularly cheaper than those without.
19131   if (Bits == 8)
19132     return false;
19133
19134   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19135   // variable shifts just as cheap as scalar ones.
19136   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19137     return false;
19138
19139   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19140   // fully general vector.
19141   return true;
19142 }
19143
19144 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19145   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19146     return false;
19147   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19148   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19149   return NumBits1 > NumBits2;
19150 }
19151
19152 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19153   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19154     return false;
19155
19156   if (!isTypeLegal(EVT::getEVT(Ty1)))
19157     return false;
19158
19159   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19160
19161   // Assuming the caller doesn't have a zeroext or signext return parameter,
19162   // truncation all the way down to i1 is valid.
19163   return true;
19164 }
19165
19166 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19167   return isInt<32>(Imm);
19168 }
19169
19170 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19171   // Can also use sub to handle negated immediates.
19172   return isInt<32>(Imm);
19173 }
19174
19175 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19176   if (!VT1.isInteger() || !VT2.isInteger())
19177     return false;
19178   unsigned NumBits1 = VT1.getSizeInBits();
19179   unsigned NumBits2 = VT2.getSizeInBits();
19180   return NumBits1 > NumBits2;
19181 }
19182
19183 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19184   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19185   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19186 }
19187
19188 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19189   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19190   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19191 }
19192
19193 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19194   EVT VT1 = Val.getValueType();
19195   if (isZExtFree(VT1, VT2))
19196     return true;
19197
19198   if (Val.getOpcode() != ISD::LOAD)
19199     return false;
19200
19201   if (!VT1.isSimple() || !VT1.isInteger() ||
19202       !VT2.isSimple() || !VT2.isInteger())
19203     return false;
19204
19205   switch (VT1.getSimpleVT().SimpleTy) {
19206   default: break;
19207   case MVT::i8:
19208   case MVT::i16:
19209   case MVT::i32:
19210     // X86 has 8, 16, and 32-bit zero-extending loads.
19211     return true;
19212   }
19213
19214   return false;
19215 }
19216
19217 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19218
19219 bool
19220 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19221   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19222     return false;
19223
19224   VT = VT.getScalarType();
19225
19226   if (!VT.isSimple())
19227     return false;
19228
19229   switch (VT.getSimpleVT().SimpleTy) {
19230   case MVT::f32:
19231   case MVT::f64:
19232     return true;
19233   default:
19234     break;
19235   }
19236
19237   return false;
19238 }
19239
19240 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19241   // i16 instructions are longer (0x66 prefix) and potentially slower.
19242   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19243 }
19244
19245 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19246 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19247 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19248 /// are assumed to be legal.
19249 bool
19250 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19251                                       EVT VT) const {
19252   if (!VT.isSimple())
19253     return false;
19254
19255   // Not for i1 vectors
19256   if (VT.getScalarType() == MVT::i1)
19257     return false;
19258
19259   // Very little shuffling can be done for 64-bit vectors right now.
19260   if (VT.getSizeInBits() == 64)
19261     return false;
19262
19263   // We only care that the types being shuffled are legal. The lowering can
19264   // handle any possible shuffle mask that results.
19265   return isTypeLegal(VT.getSimpleVT());
19266 }
19267
19268 bool
19269 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19270                                           EVT VT) const {
19271   // Just delegate to the generic legality, clear masks aren't special.
19272   return isShuffleMaskLegal(Mask, VT);
19273 }
19274
19275 //===----------------------------------------------------------------------===//
19276 //                           X86 Scheduler Hooks
19277 //===----------------------------------------------------------------------===//
19278
19279 /// Utility function to emit xbegin specifying the start of an RTM region.
19280 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19281                                      const TargetInstrInfo *TII) {
19282   DebugLoc DL = MI->getDebugLoc();
19283
19284   const BasicBlock *BB = MBB->getBasicBlock();
19285   MachineFunction::iterator I = MBB;
19286   ++I;
19287
19288   // For the v = xbegin(), we generate
19289   //
19290   // thisMBB:
19291   //  xbegin sinkMBB
19292   //
19293   // mainMBB:
19294   //  eax = -1
19295   //
19296   // sinkMBB:
19297   //  v = eax
19298
19299   MachineBasicBlock *thisMBB = MBB;
19300   MachineFunction *MF = MBB->getParent();
19301   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19302   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19303   MF->insert(I, mainMBB);
19304   MF->insert(I, sinkMBB);
19305
19306   // Transfer the remainder of BB and its successor edges to sinkMBB.
19307   sinkMBB->splice(sinkMBB->begin(), MBB,
19308                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19309   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19310
19311   // thisMBB:
19312   //  xbegin sinkMBB
19313   //  # fallthrough to mainMBB
19314   //  # abortion to sinkMBB
19315   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19316   thisMBB->addSuccessor(mainMBB);
19317   thisMBB->addSuccessor(sinkMBB);
19318
19319   // mainMBB:
19320   //  EAX = -1
19321   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19322   mainMBB->addSuccessor(sinkMBB);
19323
19324   // sinkMBB:
19325   // EAX is live into the sinkMBB
19326   sinkMBB->addLiveIn(X86::EAX);
19327   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19328           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19329     .addReg(X86::EAX);
19330
19331   MI->eraseFromParent();
19332   return sinkMBB;
19333 }
19334
19335 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19336 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19337 // in the .td file.
19338 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19339                                        const TargetInstrInfo *TII) {
19340   unsigned Opc;
19341   switch (MI->getOpcode()) {
19342   default: llvm_unreachable("illegal opcode!");
19343   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19344   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19345   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19346   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19347   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19348   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19349   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19350   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19351   }
19352
19353   DebugLoc dl = MI->getDebugLoc();
19354   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19355
19356   unsigned NumArgs = MI->getNumOperands();
19357   for (unsigned i = 1; i < NumArgs; ++i) {
19358     MachineOperand &Op = MI->getOperand(i);
19359     if (!(Op.isReg() && Op.isImplicit()))
19360       MIB.addOperand(Op);
19361   }
19362   if (MI->hasOneMemOperand())
19363     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19364
19365   BuildMI(*BB, MI, dl,
19366     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19367     .addReg(X86::XMM0);
19368
19369   MI->eraseFromParent();
19370   return BB;
19371 }
19372
19373 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19374 // defs in an instruction pattern
19375 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19376                                        const TargetInstrInfo *TII) {
19377   unsigned Opc;
19378   switch (MI->getOpcode()) {
19379   default: llvm_unreachable("illegal opcode!");
19380   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19381   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19382   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19383   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19384   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19385   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19386   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19387   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19388   }
19389
19390   DebugLoc dl = MI->getDebugLoc();
19391   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19392
19393   unsigned NumArgs = MI->getNumOperands(); // remove the results
19394   for (unsigned i = 1; i < NumArgs; ++i) {
19395     MachineOperand &Op = MI->getOperand(i);
19396     if (!(Op.isReg() && Op.isImplicit()))
19397       MIB.addOperand(Op);
19398   }
19399   if (MI->hasOneMemOperand())
19400     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19401
19402   BuildMI(*BB, MI, dl,
19403     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19404     .addReg(X86::ECX);
19405
19406   MI->eraseFromParent();
19407   return BB;
19408 }
19409
19410 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19411                                       const X86Subtarget *Subtarget) {
19412   DebugLoc dl = MI->getDebugLoc();
19413   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19414   // Address into RAX/EAX, other two args into ECX, EDX.
19415   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19416   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19417   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19418   for (int i = 0; i < X86::AddrNumOperands; ++i)
19419     MIB.addOperand(MI->getOperand(i));
19420
19421   unsigned ValOps = X86::AddrNumOperands;
19422   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19423     .addReg(MI->getOperand(ValOps).getReg());
19424   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19425     .addReg(MI->getOperand(ValOps+1).getReg());
19426
19427   // The instruction doesn't actually take any operands though.
19428   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19429
19430   MI->eraseFromParent(); // The pseudo is gone now.
19431   return BB;
19432 }
19433
19434 MachineBasicBlock *
19435 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19436                                                  MachineBasicBlock *MBB) const {
19437   // Emit va_arg instruction on X86-64.
19438
19439   // Operands to this pseudo-instruction:
19440   // 0  ) Output        : destination address (reg)
19441   // 1-5) Input         : va_list address (addr, i64mem)
19442   // 6  ) ArgSize       : Size (in bytes) of vararg type
19443   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19444   // 8  ) Align         : Alignment of type
19445   // 9  ) EFLAGS (implicit-def)
19446
19447   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19448   static_assert(X86::AddrNumOperands == 5,
19449                 "VAARG_64 assumes 5 address operands");
19450
19451   unsigned DestReg = MI->getOperand(0).getReg();
19452   MachineOperand &Base = MI->getOperand(1);
19453   MachineOperand &Scale = MI->getOperand(2);
19454   MachineOperand &Index = MI->getOperand(3);
19455   MachineOperand &Disp = MI->getOperand(4);
19456   MachineOperand &Segment = MI->getOperand(5);
19457   unsigned ArgSize = MI->getOperand(6).getImm();
19458   unsigned ArgMode = MI->getOperand(7).getImm();
19459   unsigned Align = MI->getOperand(8).getImm();
19460
19461   // Memory Reference
19462   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19463   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19464   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19465
19466   // Machine Information
19467   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19468   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19469   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19470   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19471   DebugLoc DL = MI->getDebugLoc();
19472
19473   // struct va_list {
19474   //   i32   gp_offset
19475   //   i32   fp_offset
19476   //   i64   overflow_area (address)
19477   //   i64   reg_save_area (address)
19478   // }
19479   // sizeof(va_list) = 24
19480   // alignment(va_list) = 8
19481
19482   unsigned TotalNumIntRegs = 6;
19483   unsigned TotalNumXMMRegs = 8;
19484   bool UseGPOffset = (ArgMode == 1);
19485   bool UseFPOffset = (ArgMode == 2);
19486   unsigned MaxOffset = TotalNumIntRegs * 8 +
19487                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19488
19489   /* Align ArgSize to a multiple of 8 */
19490   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19491   bool NeedsAlign = (Align > 8);
19492
19493   MachineBasicBlock *thisMBB = MBB;
19494   MachineBasicBlock *overflowMBB;
19495   MachineBasicBlock *offsetMBB;
19496   MachineBasicBlock *endMBB;
19497
19498   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19499   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19500   unsigned OffsetReg = 0;
19501
19502   if (!UseGPOffset && !UseFPOffset) {
19503     // If we only pull from the overflow region, we don't create a branch.
19504     // We don't need to alter control flow.
19505     OffsetDestReg = 0; // unused
19506     OverflowDestReg = DestReg;
19507
19508     offsetMBB = nullptr;
19509     overflowMBB = thisMBB;
19510     endMBB = thisMBB;
19511   } else {
19512     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19513     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19514     // If not, pull from overflow_area. (branch to overflowMBB)
19515     //
19516     //       thisMBB
19517     //         |     .
19518     //         |        .
19519     //     offsetMBB   overflowMBB
19520     //         |        .
19521     //         |     .
19522     //        endMBB
19523
19524     // Registers for the PHI in endMBB
19525     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19526     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19527
19528     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19529     MachineFunction *MF = MBB->getParent();
19530     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19531     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19532     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19533
19534     MachineFunction::iterator MBBIter = MBB;
19535     ++MBBIter;
19536
19537     // Insert the new basic blocks
19538     MF->insert(MBBIter, offsetMBB);
19539     MF->insert(MBBIter, overflowMBB);
19540     MF->insert(MBBIter, endMBB);
19541
19542     // Transfer the remainder of MBB and its successor edges to endMBB.
19543     endMBB->splice(endMBB->begin(), thisMBB,
19544                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19545     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19546
19547     // Make offsetMBB and overflowMBB successors of thisMBB
19548     thisMBB->addSuccessor(offsetMBB);
19549     thisMBB->addSuccessor(overflowMBB);
19550
19551     // endMBB is a successor of both offsetMBB and overflowMBB
19552     offsetMBB->addSuccessor(endMBB);
19553     overflowMBB->addSuccessor(endMBB);
19554
19555     // Load the offset value into a register
19556     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19557     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19558       .addOperand(Base)
19559       .addOperand(Scale)
19560       .addOperand(Index)
19561       .addDisp(Disp, UseFPOffset ? 4 : 0)
19562       .addOperand(Segment)
19563       .setMemRefs(MMOBegin, MMOEnd);
19564
19565     // Check if there is enough room left to pull this argument.
19566     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19567       .addReg(OffsetReg)
19568       .addImm(MaxOffset + 8 - ArgSizeA8);
19569
19570     // Branch to "overflowMBB" if offset >= max
19571     // Fall through to "offsetMBB" otherwise
19572     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19573       .addMBB(overflowMBB);
19574   }
19575
19576   // In offsetMBB, emit code to use the reg_save_area.
19577   if (offsetMBB) {
19578     assert(OffsetReg != 0);
19579
19580     // Read the reg_save_area address.
19581     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19582     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19583       .addOperand(Base)
19584       .addOperand(Scale)
19585       .addOperand(Index)
19586       .addDisp(Disp, 16)
19587       .addOperand(Segment)
19588       .setMemRefs(MMOBegin, MMOEnd);
19589
19590     // Zero-extend the offset
19591     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19592       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19593         .addImm(0)
19594         .addReg(OffsetReg)
19595         .addImm(X86::sub_32bit);
19596
19597     // Add the offset to the reg_save_area to get the final address.
19598     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19599       .addReg(OffsetReg64)
19600       .addReg(RegSaveReg);
19601
19602     // Compute the offset for the next argument
19603     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19604     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19605       .addReg(OffsetReg)
19606       .addImm(UseFPOffset ? 16 : 8);
19607
19608     // Store it back into the va_list.
19609     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19610       .addOperand(Base)
19611       .addOperand(Scale)
19612       .addOperand(Index)
19613       .addDisp(Disp, UseFPOffset ? 4 : 0)
19614       .addOperand(Segment)
19615       .addReg(NextOffsetReg)
19616       .setMemRefs(MMOBegin, MMOEnd);
19617
19618     // Jump to endMBB
19619     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19620       .addMBB(endMBB);
19621   }
19622
19623   //
19624   // Emit code to use overflow area
19625   //
19626
19627   // Load the overflow_area address into a register.
19628   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19629   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19630     .addOperand(Base)
19631     .addOperand(Scale)
19632     .addOperand(Index)
19633     .addDisp(Disp, 8)
19634     .addOperand(Segment)
19635     .setMemRefs(MMOBegin, MMOEnd);
19636
19637   // If we need to align it, do so. Otherwise, just copy the address
19638   // to OverflowDestReg.
19639   if (NeedsAlign) {
19640     // Align the overflow address
19641     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19642     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19643
19644     // aligned_addr = (addr + (align-1)) & ~(align-1)
19645     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19646       .addReg(OverflowAddrReg)
19647       .addImm(Align-1);
19648
19649     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19650       .addReg(TmpReg)
19651       .addImm(~(uint64_t)(Align-1));
19652   } else {
19653     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19654       .addReg(OverflowAddrReg);
19655   }
19656
19657   // Compute the next overflow address after this argument.
19658   // (the overflow address should be kept 8-byte aligned)
19659   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19660   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19661     .addReg(OverflowDestReg)
19662     .addImm(ArgSizeA8);
19663
19664   // Store the new overflow address.
19665   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19666     .addOperand(Base)
19667     .addOperand(Scale)
19668     .addOperand(Index)
19669     .addDisp(Disp, 8)
19670     .addOperand(Segment)
19671     .addReg(NextAddrReg)
19672     .setMemRefs(MMOBegin, MMOEnd);
19673
19674   // If we branched, emit the PHI to the front of endMBB.
19675   if (offsetMBB) {
19676     BuildMI(*endMBB, endMBB->begin(), DL,
19677             TII->get(X86::PHI), DestReg)
19678       .addReg(OffsetDestReg).addMBB(offsetMBB)
19679       .addReg(OverflowDestReg).addMBB(overflowMBB);
19680   }
19681
19682   // Erase the pseudo instruction
19683   MI->eraseFromParent();
19684
19685   return endMBB;
19686 }
19687
19688 MachineBasicBlock *
19689 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19690                                                  MachineInstr *MI,
19691                                                  MachineBasicBlock *MBB) const {
19692   // Emit code to save XMM registers to the stack. The ABI says that the
19693   // number of registers to save is given in %al, so it's theoretically
19694   // possible to do an indirect jump trick to avoid saving all of them,
19695   // however this code takes a simpler approach and just executes all
19696   // of the stores if %al is non-zero. It's less code, and it's probably
19697   // easier on the hardware branch predictor, and stores aren't all that
19698   // expensive anyway.
19699
19700   // Create the new basic blocks. One block contains all the XMM stores,
19701   // and one block is the final destination regardless of whether any
19702   // stores were performed.
19703   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19704   MachineFunction *F = MBB->getParent();
19705   MachineFunction::iterator MBBIter = MBB;
19706   ++MBBIter;
19707   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19708   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19709   F->insert(MBBIter, XMMSaveMBB);
19710   F->insert(MBBIter, EndMBB);
19711
19712   // Transfer the remainder of MBB and its successor edges to EndMBB.
19713   EndMBB->splice(EndMBB->begin(), MBB,
19714                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19715   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19716
19717   // The original block will now fall through to the XMM save block.
19718   MBB->addSuccessor(XMMSaveMBB);
19719   // The XMMSaveMBB will fall through to the end block.
19720   XMMSaveMBB->addSuccessor(EndMBB);
19721
19722   // Now add the instructions.
19723   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19724   DebugLoc DL = MI->getDebugLoc();
19725
19726   unsigned CountReg = MI->getOperand(0).getReg();
19727   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19728   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19729
19730   if (!Subtarget->isTargetWin64()) {
19731     // If %al is 0, branch around the XMM save block.
19732     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19733     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19734     MBB->addSuccessor(EndMBB);
19735   }
19736
19737   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19738   // that was just emitted, but clearly shouldn't be "saved".
19739   assert((MI->getNumOperands() <= 3 ||
19740           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19741           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19742          && "Expected last argument to be EFLAGS");
19743   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19744   // In the XMM save block, save all the XMM argument registers.
19745   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19746     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19747     MachineMemOperand *MMO =
19748       F->getMachineMemOperand(
19749           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19750         MachineMemOperand::MOStore,
19751         /*Size=*/16, /*Align=*/16);
19752     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19753       .addFrameIndex(RegSaveFrameIndex)
19754       .addImm(/*Scale=*/1)
19755       .addReg(/*IndexReg=*/0)
19756       .addImm(/*Disp=*/Offset)
19757       .addReg(/*Segment=*/0)
19758       .addReg(MI->getOperand(i).getReg())
19759       .addMemOperand(MMO);
19760   }
19761
19762   MI->eraseFromParent();   // The pseudo instruction is gone now.
19763
19764   return EndMBB;
19765 }
19766
19767 // The EFLAGS operand of SelectItr might be missing a kill marker
19768 // because there were multiple uses of EFLAGS, and ISel didn't know
19769 // which to mark. Figure out whether SelectItr should have had a
19770 // kill marker, and set it if it should. Returns the correct kill
19771 // marker value.
19772 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19773                                      MachineBasicBlock* BB,
19774                                      const TargetRegisterInfo* TRI) {
19775   // Scan forward through BB for a use/def of EFLAGS.
19776   MachineBasicBlock::iterator miI(std::next(SelectItr));
19777   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19778     const MachineInstr& mi = *miI;
19779     if (mi.readsRegister(X86::EFLAGS))
19780       return false;
19781     if (mi.definesRegister(X86::EFLAGS))
19782       break; // Should have kill-flag - update below.
19783   }
19784
19785   // If we hit the end of the block, check whether EFLAGS is live into a
19786   // successor.
19787   if (miI == BB->end()) {
19788     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19789                                           sEnd = BB->succ_end();
19790          sItr != sEnd; ++sItr) {
19791       MachineBasicBlock* succ = *sItr;
19792       if (succ->isLiveIn(X86::EFLAGS))
19793         return false;
19794     }
19795   }
19796
19797   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19798   // out. SelectMI should have a kill flag on EFLAGS.
19799   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19800   return true;
19801 }
19802
19803 MachineBasicBlock *
19804 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19805                                      MachineBasicBlock *BB) const {
19806   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19807   DebugLoc DL = MI->getDebugLoc();
19808
19809   // To "insert" a SELECT_CC instruction, we actually have to insert the
19810   // diamond control-flow pattern.  The incoming instruction knows the
19811   // destination vreg to set, the condition code register to branch on, the
19812   // true/false values to select between, and a branch opcode to use.
19813   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19814   MachineFunction::iterator It = BB;
19815   ++It;
19816
19817   //  thisMBB:
19818   //  ...
19819   //   TrueVal = ...
19820   //   cmpTY ccX, r1, r2
19821   //   bCC copy1MBB
19822   //   fallthrough --> copy0MBB
19823   MachineBasicBlock *thisMBB = BB;
19824   MachineFunction *F = BB->getParent();
19825
19826   // We also lower double CMOVs:
19827   //   (CMOV (CMOV F, T, cc1), T, cc2)
19828   // to two successives branches.  For that, we look for another CMOV as the
19829   // following instruction.
19830   //
19831   // Without this, we would add a PHI between the two jumps, which ends up
19832   // creating a few copies all around. For instance, for
19833   //
19834   //    (sitofp (zext (fcmp une)))
19835   //
19836   // we would generate:
19837   //
19838   //         ucomiss %xmm1, %xmm0
19839   //         movss  <1.0f>, %xmm0
19840   //         movaps  %xmm0, %xmm1
19841   //         jne     .LBB5_2
19842   //         xorps   %xmm1, %xmm1
19843   // .LBB5_2:
19844   //         jp      .LBB5_4
19845   //         movaps  %xmm1, %xmm0
19846   // .LBB5_4:
19847   //         retq
19848   //
19849   // because this custom-inserter would have generated:
19850   //
19851   //   A
19852   //   | \
19853   //   |  B
19854   //   | /
19855   //   C
19856   //   | \
19857   //   |  D
19858   //   | /
19859   //   E
19860   //
19861   // A: X = ...; Y = ...
19862   // B: empty
19863   // C: Z = PHI [X, A], [Y, B]
19864   // D: empty
19865   // E: PHI [X, C], [Z, D]
19866   //
19867   // If we lower both CMOVs in a single step, we can instead generate:
19868   //
19869   //   A
19870   //   | \
19871   //   |  C
19872   //   | /|
19873   //   |/ |
19874   //   |  |
19875   //   |  D
19876   //   | /
19877   //   E
19878   //
19879   // A: X = ...; Y = ...
19880   // D: empty
19881   // E: PHI [X, A], [X, C], [Y, D]
19882   //
19883   // Which, in our sitofp/fcmp example, gives us something like:
19884   //
19885   //         ucomiss %xmm1, %xmm0
19886   //         movss  <1.0f>, %xmm0
19887   //         jne     .LBB5_4
19888   //         jp      .LBB5_4
19889   //         xorps   %xmm0, %xmm0
19890   // .LBB5_4:
19891   //         retq
19892   //
19893   MachineInstr *NextCMOV = nullptr;
19894   MachineBasicBlock::iterator NextMIIt =
19895       std::next(MachineBasicBlock::iterator(MI));
19896   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19897       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19898       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19899     NextCMOV = &*NextMIIt;
19900
19901   MachineBasicBlock *jcc1MBB = nullptr;
19902
19903   // If we have a double CMOV, we lower it to two successive branches to
19904   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19905   if (NextCMOV) {
19906     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19907     F->insert(It, jcc1MBB);
19908     jcc1MBB->addLiveIn(X86::EFLAGS);
19909   }
19910
19911   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19912   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19913   F->insert(It, copy0MBB);
19914   F->insert(It, sinkMBB);
19915
19916   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19917   // live into the sink and copy blocks.
19918   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19919
19920   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19921   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19922       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19923     copy0MBB->addLiveIn(X86::EFLAGS);
19924     sinkMBB->addLiveIn(X86::EFLAGS);
19925   }
19926
19927   // Transfer the remainder of BB and its successor edges to sinkMBB.
19928   sinkMBB->splice(sinkMBB->begin(), BB,
19929                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19930   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19931
19932   // Add the true and fallthrough blocks as its successors.
19933   if (NextCMOV) {
19934     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19935     BB->addSuccessor(jcc1MBB);
19936
19937     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19938     // jump to the sinkMBB.
19939     jcc1MBB->addSuccessor(copy0MBB);
19940     jcc1MBB->addSuccessor(sinkMBB);
19941   } else {
19942     BB->addSuccessor(copy0MBB);
19943   }
19944
19945   // The true block target of the first (or only) branch is always sinkMBB.
19946   BB->addSuccessor(sinkMBB);
19947
19948   // Create the conditional branch instruction.
19949   unsigned Opc =
19950     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19951   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19952
19953   if (NextCMOV) {
19954     unsigned Opc2 = X86::GetCondBranchFromCond(
19955         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19956     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19957   }
19958
19959   //  copy0MBB:
19960   //   %FalseValue = ...
19961   //   # fallthrough to sinkMBB
19962   copy0MBB->addSuccessor(sinkMBB);
19963
19964   //  sinkMBB:
19965   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19966   //  ...
19967   MachineInstrBuilder MIB =
19968       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19969               MI->getOperand(0).getReg())
19970           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19971           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19972
19973   // If we have a double CMOV, the second Jcc provides the same incoming
19974   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19975   if (NextCMOV) {
19976     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19977     // Copy the PHI result to the register defined by the second CMOV.
19978     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19979             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19980         .addReg(MI->getOperand(0).getReg());
19981     NextCMOV->eraseFromParent();
19982   }
19983
19984   MI->eraseFromParent();   // The pseudo instruction is gone now.
19985   return sinkMBB;
19986 }
19987
19988 MachineBasicBlock *
19989 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19990                                         MachineBasicBlock *BB) const {
19991   MachineFunction *MF = BB->getParent();
19992   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19993   DebugLoc DL = MI->getDebugLoc();
19994   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19995
19996   assert(MF->shouldSplitStack());
19997
19998   const bool Is64Bit = Subtarget->is64Bit();
19999   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20000
20001   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20002   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20003
20004   // BB:
20005   //  ... [Till the alloca]
20006   // If stacklet is not large enough, jump to mallocMBB
20007   //
20008   // bumpMBB:
20009   //  Allocate by subtracting from RSP
20010   //  Jump to continueMBB
20011   //
20012   // mallocMBB:
20013   //  Allocate by call to runtime
20014   //
20015   // continueMBB:
20016   //  ...
20017   //  [rest of original BB]
20018   //
20019
20020   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20021   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20022   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20023
20024   MachineRegisterInfo &MRI = MF->getRegInfo();
20025   const TargetRegisterClass *AddrRegClass =
20026       getRegClassFor(getPointerTy(MF->getDataLayout()));
20027
20028   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20029     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20030     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20031     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20032     sizeVReg = MI->getOperand(1).getReg(),
20033     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20034
20035   MachineFunction::iterator MBBIter = BB;
20036   ++MBBIter;
20037
20038   MF->insert(MBBIter, bumpMBB);
20039   MF->insert(MBBIter, mallocMBB);
20040   MF->insert(MBBIter, continueMBB);
20041
20042   continueMBB->splice(continueMBB->begin(), BB,
20043                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20044   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20045
20046   // Add code to the main basic block to check if the stack limit has been hit,
20047   // and if so, jump to mallocMBB otherwise to bumpMBB.
20048   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20049   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20050     .addReg(tmpSPVReg).addReg(sizeVReg);
20051   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20052     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20053     .addReg(SPLimitVReg);
20054   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20055
20056   // bumpMBB simply decreases the stack pointer, since we know the current
20057   // stacklet has enough space.
20058   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20059     .addReg(SPLimitVReg);
20060   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20061     .addReg(SPLimitVReg);
20062   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20063
20064   // Calls into a routine in libgcc to allocate more space from the heap.
20065   const uint32_t *RegMask =
20066       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20067   if (IsLP64) {
20068     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20069       .addReg(sizeVReg);
20070     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20071       .addExternalSymbol("__morestack_allocate_stack_space")
20072       .addRegMask(RegMask)
20073       .addReg(X86::RDI, RegState::Implicit)
20074       .addReg(X86::RAX, RegState::ImplicitDefine);
20075   } else if (Is64Bit) {
20076     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20077       .addReg(sizeVReg);
20078     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20079       .addExternalSymbol("__morestack_allocate_stack_space")
20080       .addRegMask(RegMask)
20081       .addReg(X86::EDI, RegState::Implicit)
20082       .addReg(X86::EAX, RegState::ImplicitDefine);
20083   } else {
20084     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20085       .addImm(12);
20086     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20087     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20088       .addExternalSymbol("__morestack_allocate_stack_space")
20089       .addRegMask(RegMask)
20090       .addReg(X86::EAX, RegState::ImplicitDefine);
20091   }
20092
20093   if (!Is64Bit)
20094     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20095       .addImm(16);
20096
20097   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20098     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20099   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20100
20101   // Set up the CFG correctly.
20102   BB->addSuccessor(bumpMBB);
20103   BB->addSuccessor(mallocMBB);
20104   mallocMBB->addSuccessor(continueMBB);
20105   bumpMBB->addSuccessor(continueMBB);
20106
20107   // Take care of the PHI nodes.
20108   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20109           MI->getOperand(0).getReg())
20110     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20111     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20112
20113   // Delete the original pseudo instruction.
20114   MI->eraseFromParent();
20115
20116   // And we're done.
20117   return continueMBB;
20118 }
20119
20120 MachineBasicBlock *
20121 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20122                                         MachineBasicBlock *BB) const {
20123   DebugLoc DL = MI->getDebugLoc();
20124
20125   assert(!Subtarget->isTargetMachO());
20126
20127   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20128                                                     DL);
20129
20130   MI->eraseFromParent();   // The pseudo instruction is gone now.
20131   return BB;
20132 }
20133
20134 MachineBasicBlock *
20135 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20136                                       MachineBasicBlock *BB) const {
20137   // This is pretty easy.  We're taking the value that we received from
20138   // our load from the relocation, sticking it in either RDI (x86-64)
20139   // or EAX and doing an indirect call.  The return value will then
20140   // be in the normal return register.
20141   MachineFunction *F = BB->getParent();
20142   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20143   DebugLoc DL = MI->getDebugLoc();
20144
20145   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20146   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20147
20148   // Get a register mask for the lowered call.
20149   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20150   // proper register mask.
20151   const uint32_t *RegMask =
20152       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20153   if (Subtarget->is64Bit()) {
20154     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20155                                       TII->get(X86::MOV64rm), X86::RDI)
20156     .addReg(X86::RIP)
20157     .addImm(0).addReg(0)
20158     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20159                       MI->getOperand(3).getTargetFlags())
20160     .addReg(0);
20161     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20162     addDirectMem(MIB, X86::RDI);
20163     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20164   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20165     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20166                                       TII->get(X86::MOV32rm), X86::EAX)
20167     .addReg(0)
20168     .addImm(0).addReg(0)
20169     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20170                       MI->getOperand(3).getTargetFlags())
20171     .addReg(0);
20172     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20173     addDirectMem(MIB, X86::EAX);
20174     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20175   } else {
20176     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20177                                       TII->get(X86::MOV32rm), X86::EAX)
20178     .addReg(TII->getGlobalBaseReg(F))
20179     .addImm(0).addReg(0)
20180     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20181                       MI->getOperand(3).getTargetFlags())
20182     .addReg(0);
20183     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20184     addDirectMem(MIB, X86::EAX);
20185     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20186   }
20187
20188   MI->eraseFromParent(); // The pseudo instruction is gone now.
20189   return BB;
20190 }
20191
20192 MachineBasicBlock *
20193 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20194                                     MachineBasicBlock *MBB) const {
20195   DebugLoc DL = MI->getDebugLoc();
20196   MachineFunction *MF = MBB->getParent();
20197   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20198   MachineRegisterInfo &MRI = MF->getRegInfo();
20199
20200   const BasicBlock *BB = MBB->getBasicBlock();
20201   MachineFunction::iterator I = MBB;
20202   ++I;
20203
20204   // Memory Reference
20205   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20206   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20207
20208   unsigned DstReg;
20209   unsigned MemOpndSlot = 0;
20210
20211   unsigned CurOp = 0;
20212
20213   DstReg = MI->getOperand(CurOp++).getReg();
20214   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20215   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20216   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20217   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20218
20219   MemOpndSlot = CurOp;
20220
20221   MVT PVT = getPointerTy(MF->getDataLayout());
20222   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20223          "Invalid Pointer Size!");
20224
20225   // For v = setjmp(buf), we generate
20226   //
20227   // thisMBB:
20228   //  buf[LabelOffset] = restoreMBB
20229   //  SjLjSetup restoreMBB
20230   //
20231   // mainMBB:
20232   //  v_main = 0
20233   //
20234   // sinkMBB:
20235   //  v = phi(main, restore)
20236   //
20237   // restoreMBB:
20238   //  if base pointer being used, load it from frame
20239   //  v_restore = 1
20240
20241   MachineBasicBlock *thisMBB = MBB;
20242   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20243   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20244   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20245   MF->insert(I, mainMBB);
20246   MF->insert(I, sinkMBB);
20247   MF->push_back(restoreMBB);
20248
20249   MachineInstrBuilder MIB;
20250
20251   // Transfer the remainder of BB and its successor edges to sinkMBB.
20252   sinkMBB->splice(sinkMBB->begin(), MBB,
20253                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20254   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20255
20256   // thisMBB:
20257   unsigned PtrStoreOpc = 0;
20258   unsigned LabelReg = 0;
20259   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20260   Reloc::Model RM = MF->getTarget().getRelocationModel();
20261   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20262                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20263
20264   // Prepare IP either in reg or imm.
20265   if (!UseImmLabel) {
20266     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20267     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20268     LabelReg = MRI.createVirtualRegister(PtrRC);
20269     if (Subtarget->is64Bit()) {
20270       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20271               .addReg(X86::RIP)
20272               .addImm(0)
20273               .addReg(0)
20274               .addMBB(restoreMBB)
20275               .addReg(0);
20276     } else {
20277       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20278       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20279               .addReg(XII->getGlobalBaseReg(MF))
20280               .addImm(0)
20281               .addReg(0)
20282               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20283               .addReg(0);
20284     }
20285   } else
20286     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20287   // Store IP
20288   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20289   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20290     if (i == X86::AddrDisp)
20291       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20292     else
20293       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20294   }
20295   if (!UseImmLabel)
20296     MIB.addReg(LabelReg);
20297   else
20298     MIB.addMBB(restoreMBB);
20299   MIB.setMemRefs(MMOBegin, MMOEnd);
20300   // Setup
20301   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20302           .addMBB(restoreMBB);
20303
20304   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20305   MIB.addRegMask(RegInfo->getNoPreservedMask());
20306   thisMBB->addSuccessor(mainMBB);
20307   thisMBB->addSuccessor(restoreMBB);
20308
20309   // mainMBB:
20310   //  EAX = 0
20311   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20312   mainMBB->addSuccessor(sinkMBB);
20313
20314   // sinkMBB:
20315   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20316           TII->get(X86::PHI), DstReg)
20317     .addReg(mainDstReg).addMBB(mainMBB)
20318     .addReg(restoreDstReg).addMBB(restoreMBB);
20319
20320   // restoreMBB:
20321   if (RegInfo->hasBasePointer(*MF)) {
20322     const bool Uses64BitFramePtr =
20323         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20324     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20325     X86FI->setRestoreBasePointer(MF);
20326     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20327     unsigned BasePtr = RegInfo->getBaseRegister();
20328     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20329     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20330                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20331       .setMIFlag(MachineInstr::FrameSetup);
20332   }
20333   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20334   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20335   restoreMBB->addSuccessor(sinkMBB);
20336
20337   MI->eraseFromParent();
20338   return sinkMBB;
20339 }
20340
20341 MachineBasicBlock *
20342 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20343                                      MachineBasicBlock *MBB) const {
20344   DebugLoc DL = MI->getDebugLoc();
20345   MachineFunction *MF = MBB->getParent();
20346   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20347   MachineRegisterInfo &MRI = MF->getRegInfo();
20348
20349   // Memory Reference
20350   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20351   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20352
20353   MVT PVT = getPointerTy(MF->getDataLayout());
20354   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20355          "Invalid Pointer Size!");
20356
20357   const TargetRegisterClass *RC =
20358     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20359   unsigned Tmp = MRI.createVirtualRegister(RC);
20360   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20361   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20362   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20363   unsigned SP = RegInfo->getStackRegister();
20364
20365   MachineInstrBuilder MIB;
20366
20367   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20368   const int64_t SPOffset = 2 * PVT.getStoreSize();
20369
20370   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20371   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20372
20373   // Reload FP
20374   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20375   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20376     MIB.addOperand(MI->getOperand(i));
20377   MIB.setMemRefs(MMOBegin, MMOEnd);
20378   // Reload IP
20379   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20380   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20381     if (i == X86::AddrDisp)
20382       MIB.addDisp(MI->getOperand(i), LabelOffset);
20383     else
20384       MIB.addOperand(MI->getOperand(i));
20385   }
20386   MIB.setMemRefs(MMOBegin, MMOEnd);
20387   // Reload SP
20388   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20389   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20390     if (i == X86::AddrDisp)
20391       MIB.addDisp(MI->getOperand(i), SPOffset);
20392     else
20393       MIB.addOperand(MI->getOperand(i));
20394   }
20395   MIB.setMemRefs(MMOBegin, MMOEnd);
20396   // Jump
20397   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20398
20399   MI->eraseFromParent();
20400   return MBB;
20401 }
20402
20403 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20404 // accumulator loops. Writing back to the accumulator allows the coalescer
20405 // to remove extra copies in the loop.
20406 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20407 MachineBasicBlock *
20408 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20409                                  MachineBasicBlock *MBB) const {
20410   MachineOperand &AddendOp = MI->getOperand(3);
20411
20412   // Bail out early if the addend isn't a register - we can't switch these.
20413   if (!AddendOp.isReg())
20414     return MBB;
20415
20416   MachineFunction &MF = *MBB->getParent();
20417   MachineRegisterInfo &MRI = MF.getRegInfo();
20418
20419   // Check whether the addend is defined by a PHI:
20420   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20421   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20422   if (!AddendDef.isPHI())
20423     return MBB;
20424
20425   // Look for the following pattern:
20426   // loop:
20427   //   %addend = phi [%entry, 0], [%loop, %result]
20428   //   ...
20429   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20430
20431   // Replace with:
20432   //   loop:
20433   //   %addend = phi [%entry, 0], [%loop, %result]
20434   //   ...
20435   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20436
20437   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20438     assert(AddendDef.getOperand(i).isReg());
20439     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20440     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20441     if (&PHISrcInst == MI) {
20442       // Found a matching instruction.
20443       unsigned NewFMAOpc = 0;
20444       switch (MI->getOpcode()) {
20445         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20446         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20447         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20448         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20449         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20450         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20451         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20452         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20453         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20454         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20455         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20456         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20457         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20458         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20459         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20460         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20461         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20462         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20463         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20464         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20465
20466         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20467         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20468         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20469         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20470         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20471         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20472         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20473         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20474         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20475         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20476         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20477         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20478         default: llvm_unreachable("Unrecognized FMA variant.");
20479       }
20480
20481       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20482       MachineInstrBuilder MIB =
20483         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20484         .addOperand(MI->getOperand(0))
20485         .addOperand(MI->getOperand(3))
20486         .addOperand(MI->getOperand(2))
20487         .addOperand(MI->getOperand(1));
20488       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20489       MI->eraseFromParent();
20490     }
20491   }
20492
20493   return MBB;
20494 }
20495
20496 MachineBasicBlock *
20497 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20498                                                MachineBasicBlock *BB) const {
20499   switch (MI->getOpcode()) {
20500   default: llvm_unreachable("Unexpected instr type to insert");
20501   case X86::TAILJMPd64:
20502   case X86::TAILJMPr64:
20503   case X86::TAILJMPm64:
20504   case X86::TAILJMPd64_REX:
20505   case X86::TAILJMPr64_REX:
20506   case X86::TAILJMPm64_REX:
20507     llvm_unreachable("TAILJMP64 would not be touched here.");
20508   case X86::TCRETURNdi64:
20509   case X86::TCRETURNri64:
20510   case X86::TCRETURNmi64:
20511     return BB;
20512   case X86::WIN_ALLOCA:
20513     return EmitLoweredWinAlloca(MI, BB);
20514   case X86::SEG_ALLOCA_32:
20515   case X86::SEG_ALLOCA_64:
20516     return EmitLoweredSegAlloca(MI, BB);
20517   case X86::TLSCall_32:
20518   case X86::TLSCall_64:
20519     return EmitLoweredTLSCall(MI, BB);
20520   case X86::CMOV_GR8:
20521   case X86::CMOV_FR32:
20522   case X86::CMOV_FR64:
20523   case X86::CMOV_V4F32:
20524   case X86::CMOV_V2F64:
20525   case X86::CMOV_V2I64:
20526   case X86::CMOV_V8F32:
20527   case X86::CMOV_V4F64:
20528   case X86::CMOV_V4I64:
20529   case X86::CMOV_V16F32:
20530   case X86::CMOV_V8F64:
20531   case X86::CMOV_V8I64:
20532   case X86::CMOV_GR16:
20533   case X86::CMOV_GR32:
20534   case X86::CMOV_RFP32:
20535   case X86::CMOV_RFP64:
20536   case X86::CMOV_RFP80:
20537   case X86::CMOV_V8I1:
20538   case X86::CMOV_V16I1:
20539   case X86::CMOV_V32I1:
20540   case X86::CMOV_V64I1:
20541     return EmitLoweredSelect(MI, BB);
20542
20543   case X86::FP32_TO_INT16_IN_MEM:
20544   case X86::FP32_TO_INT32_IN_MEM:
20545   case X86::FP32_TO_INT64_IN_MEM:
20546   case X86::FP64_TO_INT16_IN_MEM:
20547   case X86::FP64_TO_INT32_IN_MEM:
20548   case X86::FP64_TO_INT64_IN_MEM:
20549   case X86::FP80_TO_INT16_IN_MEM:
20550   case X86::FP80_TO_INT32_IN_MEM:
20551   case X86::FP80_TO_INT64_IN_MEM: {
20552     MachineFunction *F = BB->getParent();
20553     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20554     DebugLoc DL = MI->getDebugLoc();
20555
20556     // Change the floating point control register to use "round towards zero"
20557     // mode when truncating to an integer value.
20558     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20559     addFrameReference(BuildMI(*BB, MI, DL,
20560                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20561
20562     // Load the old value of the high byte of the control word...
20563     unsigned OldCW =
20564       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20565     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20566                       CWFrameIdx);
20567
20568     // Set the high part to be round to zero...
20569     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20570       .addImm(0xC7F);
20571
20572     // Reload the modified control word now...
20573     addFrameReference(BuildMI(*BB, MI, DL,
20574                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20575
20576     // Restore the memory image of control word to original value
20577     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20578       .addReg(OldCW);
20579
20580     // Get the X86 opcode to use.
20581     unsigned Opc;
20582     switch (MI->getOpcode()) {
20583     default: llvm_unreachable("illegal opcode!");
20584     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20585     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20586     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20587     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20588     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20589     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20590     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20591     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20592     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20593     }
20594
20595     X86AddressMode AM;
20596     MachineOperand &Op = MI->getOperand(0);
20597     if (Op.isReg()) {
20598       AM.BaseType = X86AddressMode::RegBase;
20599       AM.Base.Reg = Op.getReg();
20600     } else {
20601       AM.BaseType = X86AddressMode::FrameIndexBase;
20602       AM.Base.FrameIndex = Op.getIndex();
20603     }
20604     Op = MI->getOperand(1);
20605     if (Op.isImm())
20606       AM.Scale = Op.getImm();
20607     Op = MI->getOperand(2);
20608     if (Op.isImm())
20609       AM.IndexReg = Op.getImm();
20610     Op = MI->getOperand(3);
20611     if (Op.isGlobal()) {
20612       AM.GV = Op.getGlobal();
20613     } else {
20614       AM.Disp = Op.getImm();
20615     }
20616     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20617                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20618
20619     // Reload the original control word now.
20620     addFrameReference(BuildMI(*BB, MI, DL,
20621                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20622
20623     MI->eraseFromParent();   // The pseudo instruction is gone now.
20624     return BB;
20625   }
20626     // String/text processing lowering.
20627   case X86::PCMPISTRM128REG:
20628   case X86::VPCMPISTRM128REG:
20629   case X86::PCMPISTRM128MEM:
20630   case X86::VPCMPISTRM128MEM:
20631   case X86::PCMPESTRM128REG:
20632   case X86::VPCMPESTRM128REG:
20633   case X86::PCMPESTRM128MEM:
20634   case X86::VPCMPESTRM128MEM:
20635     assert(Subtarget->hasSSE42() &&
20636            "Target must have SSE4.2 or AVX features enabled");
20637     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20638
20639   // String/text processing lowering.
20640   case X86::PCMPISTRIREG:
20641   case X86::VPCMPISTRIREG:
20642   case X86::PCMPISTRIMEM:
20643   case X86::VPCMPISTRIMEM:
20644   case X86::PCMPESTRIREG:
20645   case X86::VPCMPESTRIREG:
20646   case X86::PCMPESTRIMEM:
20647   case X86::VPCMPESTRIMEM:
20648     assert(Subtarget->hasSSE42() &&
20649            "Target must have SSE4.2 or AVX features enabled");
20650     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20651
20652   // Thread synchronization.
20653   case X86::MONITOR:
20654     return EmitMonitor(MI, BB, Subtarget);
20655
20656   // xbegin
20657   case X86::XBEGIN:
20658     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20659
20660   case X86::VASTART_SAVE_XMM_REGS:
20661     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20662
20663   case X86::VAARG_64:
20664     return EmitVAARG64WithCustomInserter(MI, BB);
20665
20666   case X86::EH_SjLj_SetJmp32:
20667   case X86::EH_SjLj_SetJmp64:
20668     return emitEHSjLjSetJmp(MI, BB);
20669
20670   case X86::EH_SjLj_LongJmp32:
20671   case X86::EH_SjLj_LongJmp64:
20672     return emitEHSjLjLongJmp(MI, BB);
20673
20674   case TargetOpcode::STATEPOINT:
20675     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20676     // this point in the process.  We diverge later.
20677     return emitPatchPoint(MI, BB);
20678
20679   case TargetOpcode::STACKMAP:
20680   case TargetOpcode::PATCHPOINT:
20681     return emitPatchPoint(MI, BB);
20682
20683   case X86::VFMADDPDr213r:
20684   case X86::VFMADDPSr213r:
20685   case X86::VFMADDSDr213r:
20686   case X86::VFMADDSSr213r:
20687   case X86::VFMSUBPDr213r:
20688   case X86::VFMSUBPSr213r:
20689   case X86::VFMSUBSDr213r:
20690   case X86::VFMSUBSSr213r:
20691   case X86::VFNMADDPDr213r:
20692   case X86::VFNMADDPSr213r:
20693   case X86::VFNMADDSDr213r:
20694   case X86::VFNMADDSSr213r:
20695   case X86::VFNMSUBPDr213r:
20696   case X86::VFNMSUBPSr213r:
20697   case X86::VFNMSUBSDr213r:
20698   case X86::VFNMSUBSSr213r:
20699   case X86::VFMADDSUBPDr213r:
20700   case X86::VFMADDSUBPSr213r:
20701   case X86::VFMSUBADDPDr213r:
20702   case X86::VFMSUBADDPSr213r:
20703   case X86::VFMADDPDr213rY:
20704   case X86::VFMADDPSr213rY:
20705   case X86::VFMSUBPDr213rY:
20706   case X86::VFMSUBPSr213rY:
20707   case X86::VFNMADDPDr213rY:
20708   case X86::VFNMADDPSr213rY:
20709   case X86::VFNMSUBPDr213rY:
20710   case X86::VFNMSUBPSr213rY:
20711   case X86::VFMADDSUBPDr213rY:
20712   case X86::VFMADDSUBPSr213rY:
20713   case X86::VFMSUBADDPDr213rY:
20714   case X86::VFMSUBADDPSr213rY:
20715     return emitFMA3Instr(MI, BB);
20716   }
20717 }
20718
20719 //===----------------------------------------------------------------------===//
20720 //                           X86 Optimization Hooks
20721 //===----------------------------------------------------------------------===//
20722
20723 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20724                                                       APInt &KnownZero,
20725                                                       APInt &KnownOne,
20726                                                       const SelectionDAG &DAG,
20727                                                       unsigned Depth) const {
20728   unsigned BitWidth = KnownZero.getBitWidth();
20729   unsigned Opc = Op.getOpcode();
20730   assert((Opc >= ISD::BUILTIN_OP_END ||
20731           Opc == ISD::INTRINSIC_WO_CHAIN ||
20732           Opc == ISD::INTRINSIC_W_CHAIN ||
20733           Opc == ISD::INTRINSIC_VOID) &&
20734          "Should use MaskedValueIsZero if you don't know whether Op"
20735          " is a target node!");
20736
20737   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20738   switch (Opc) {
20739   default: break;
20740   case X86ISD::ADD:
20741   case X86ISD::SUB:
20742   case X86ISD::ADC:
20743   case X86ISD::SBB:
20744   case X86ISD::SMUL:
20745   case X86ISD::UMUL:
20746   case X86ISD::INC:
20747   case X86ISD::DEC:
20748   case X86ISD::OR:
20749   case X86ISD::XOR:
20750   case X86ISD::AND:
20751     // These nodes' second result is a boolean.
20752     if (Op.getResNo() == 0)
20753       break;
20754     // Fallthrough
20755   case X86ISD::SETCC:
20756     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20757     break;
20758   case ISD::INTRINSIC_WO_CHAIN: {
20759     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20760     unsigned NumLoBits = 0;
20761     switch (IntId) {
20762     default: break;
20763     case Intrinsic::x86_sse_movmsk_ps:
20764     case Intrinsic::x86_avx_movmsk_ps_256:
20765     case Intrinsic::x86_sse2_movmsk_pd:
20766     case Intrinsic::x86_avx_movmsk_pd_256:
20767     case Intrinsic::x86_mmx_pmovmskb:
20768     case Intrinsic::x86_sse2_pmovmskb_128:
20769     case Intrinsic::x86_avx2_pmovmskb: {
20770       // High bits of movmskp{s|d}, pmovmskb are known zero.
20771       switch (IntId) {
20772         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20773         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20774         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20775         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20776         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20777         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20778         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20779         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20780       }
20781       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20782       break;
20783     }
20784     }
20785     break;
20786   }
20787   }
20788 }
20789
20790 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20791   SDValue Op,
20792   const SelectionDAG &,
20793   unsigned Depth) const {
20794   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20795   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20796     return Op.getValueType().getScalarType().getSizeInBits();
20797
20798   // Fallback case.
20799   return 1;
20800 }
20801
20802 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20803 /// node is a GlobalAddress + offset.
20804 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20805                                        const GlobalValue* &GA,
20806                                        int64_t &Offset) const {
20807   if (N->getOpcode() == X86ISD::Wrapper) {
20808     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20809       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20810       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20811       return true;
20812     }
20813   }
20814   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20815 }
20816
20817 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20818 /// same as extracting the high 128-bit part of 256-bit vector and then
20819 /// inserting the result into the low part of a new 256-bit vector
20820 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20821   EVT VT = SVOp->getValueType(0);
20822   unsigned NumElems = VT.getVectorNumElements();
20823
20824   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20825   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20826     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20827         SVOp->getMaskElt(j) >= 0)
20828       return false;
20829
20830   return true;
20831 }
20832
20833 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20834 /// same as extracting the low 128-bit part of 256-bit vector and then
20835 /// inserting the result into the high part of a new 256-bit vector
20836 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20837   EVT VT = SVOp->getValueType(0);
20838   unsigned NumElems = VT.getVectorNumElements();
20839
20840   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20841   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20842     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20843         SVOp->getMaskElt(j) >= 0)
20844       return false;
20845
20846   return true;
20847 }
20848
20849 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20850 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20851                                         TargetLowering::DAGCombinerInfo &DCI,
20852                                         const X86Subtarget* Subtarget) {
20853   SDLoc dl(N);
20854   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20855   SDValue V1 = SVOp->getOperand(0);
20856   SDValue V2 = SVOp->getOperand(1);
20857   EVT VT = SVOp->getValueType(0);
20858   unsigned NumElems = VT.getVectorNumElements();
20859
20860   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20861       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20862     //
20863     //                   0,0,0,...
20864     //                      |
20865     //    V      UNDEF    BUILD_VECTOR    UNDEF
20866     //     \      /           \           /
20867     //  CONCAT_VECTOR         CONCAT_VECTOR
20868     //         \                  /
20869     //          \                /
20870     //          RESULT: V + zero extended
20871     //
20872     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20873         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20874         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20875       return SDValue();
20876
20877     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20878       return SDValue();
20879
20880     // To match the shuffle mask, the first half of the mask should
20881     // be exactly the first vector, and all the rest a splat with the
20882     // first element of the second one.
20883     for (unsigned i = 0; i != NumElems/2; ++i)
20884       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20885           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20886         return SDValue();
20887
20888     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20889     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20890       if (Ld->hasNUsesOfValue(1, 0)) {
20891         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20892         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20893         SDValue ResNode =
20894           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20895                                   Ld->getMemoryVT(),
20896                                   Ld->getPointerInfo(),
20897                                   Ld->getAlignment(),
20898                                   false/*isVolatile*/, true/*ReadMem*/,
20899                                   false/*WriteMem*/);
20900
20901         // Make sure the newly-created LOAD is in the same position as Ld in
20902         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20903         // and update uses of Ld's output chain to use the TokenFactor.
20904         if (Ld->hasAnyUseOfValue(1)) {
20905           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20906                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20907           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20908           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20909                                  SDValue(ResNode.getNode(), 1));
20910         }
20911
20912         return DAG.getBitcast(VT, ResNode);
20913       }
20914     }
20915
20916     // Emit a zeroed vector and insert the desired subvector on its
20917     // first half.
20918     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20919     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20920     return DCI.CombineTo(N, InsV);
20921   }
20922
20923   //===--------------------------------------------------------------------===//
20924   // Combine some shuffles into subvector extracts and inserts:
20925   //
20926
20927   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20928   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20929     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20930     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20931     return DCI.CombineTo(N, InsV);
20932   }
20933
20934   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20935   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20936     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20937     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20938     return DCI.CombineTo(N, InsV);
20939   }
20940
20941   return SDValue();
20942 }
20943
20944 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20945 /// possible.
20946 ///
20947 /// This is the leaf of the recursive combinine below. When we have found some
20948 /// chain of single-use x86 shuffle instructions and accumulated the combined
20949 /// shuffle mask represented by them, this will try to pattern match that mask
20950 /// into either a single instruction if there is a special purpose instruction
20951 /// for this operation, or into a PSHUFB instruction which is a fully general
20952 /// instruction but should only be used to replace chains over a certain depth.
20953 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20954                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20955                                    TargetLowering::DAGCombinerInfo &DCI,
20956                                    const X86Subtarget *Subtarget) {
20957   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20958
20959   // Find the operand that enters the chain. Note that multiple uses are OK
20960   // here, we're not going to remove the operand we find.
20961   SDValue Input = Op.getOperand(0);
20962   while (Input.getOpcode() == ISD::BITCAST)
20963     Input = Input.getOperand(0);
20964
20965   MVT VT = Input.getSimpleValueType();
20966   MVT RootVT = Root.getSimpleValueType();
20967   SDLoc DL(Root);
20968
20969   // Just remove no-op shuffle masks.
20970   if (Mask.size() == 1) {
20971     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20972                   /*AddTo*/ true);
20973     return true;
20974   }
20975
20976   // Use the float domain if the operand type is a floating point type.
20977   bool FloatDomain = VT.isFloatingPoint();
20978
20979   // For floating point shuffles, we don't have free copies in the shuffle
20980   // instructions or the ability to load as part of the instruction, so
20981   // canonicalize their shuffles to UNPCK or MOV variants.
20982   //
20983   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20984   // vectors because it can have a load folded into it that UNPCK cannot. This
20985   // doesn't preclude something switching to the shorter encoding post-RA.
20986   //
20987   // FIXME: Should teach these routines about AVX vector widths.
20988   if (FloatDomain && VT.getSizeInBits() == 128) {
20989     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20990       bool Lo = Mask.equals({0, 0});
20991       unsigned Shuffle;
20992       MVT ShuffleVT;
20993       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20994       // is no slower than UNPCKLPD but has the option to fold the input operand
20995       // into even an unaligned memory load.
20996       if (Lo && Subtarget->hasSSE3()) {
20997         Shuffle = X86ISD::MOVDDUP;
20998         ShuffleVT = MVT::v2f64;
20999       } else {
21000         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21001         // than the UNPCK variants.
21002         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21003         ShuffleVT = MVT::v4f32;
21004       }
21005       if (Depth == 1 && Root->getOpcode() == Shuffle)
21006         return false; // Nothing to do!
21007       Op = DAG.getBitcast(ShuffleVT, Input);
21008       DCI.AddToWorklist(Op.getNode());
21009       if (Shuffle == X86ISD::MOVDDUP)
21010         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21011       else
21012         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21013       DCI.AddToWorklist(Op.getNode());
21014       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21015                     /*AddTo*/ true);
21016       return true;
21017     }
21018     if (Subtarget->hasSSE3() &&
21019         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21020       bool Lo = Mask.equals({0, 0, 2, 2});
21021       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21022       MVT ShuffleVT = MVT::v4f32;
21023       if (Depth == 1 && Root->getOpcode() == Shuffle)
21024         return false; // Nothing to do!
21025       Op = DAG.getBitcast(ShuffleVT, Input);
21026       DCI.AddToWorklist(Op.getNode());
21027       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21028       DCI.AddToWorklist(Op.getNode());
21029       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21030                     /*AddTo*/ true);
21031       return true;
21032     }
21033     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21034       bool Lo = Mask.equals({0, 0, 1, 1});
21035       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21036       MVT ShuffleVT = MVT::v4f32;
21037       if (Depth == 1 && Root->getOpcode() == Shuffle)
21038         return false; // Nothing to do!
21039       Op = DAG.getBitcast(ShuffleVT, Input);
21040       DCI.AddToWorklist(Op.getNode());
21041       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21042       DCI.AddToWorklist(Op.getNode());
21043       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21044                     /*AddTo*/ true);
21045       return true;
21046     }
21047   }
21048
21049   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21050   // variants as none of these have single-instruction variants that are
21051   // superior to the UNPCK formulation.
21052   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21053       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21054        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21055        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21056        Mask.equals(
21057            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21058     bool Lo = Mask[0] == 0;
21059     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21060     if (Depth == 1 && Root->getOpcode() == Shuffle)
21061       return false; // Nothing to do!
21062     MVT ShuffleVT;
21063     switch (Mask.size()) {
21064     case 8:
21065       ShuffleVT = MVT::v8i16;
21066       break;
21067     case 16:
21068       ShuffleVT = MVT::v16i8;
21069       break;
21070     default:
21071       llvm_unreachable("Impossible mask size!");
21072     };
21073     Op = DAG.getBitcast(ShuffleVT, Input);
21074     DCI.AddToWorklist(Op.getNode());
21075     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21076     DCI.AddToWorklist(Op.getNode());
21077     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21078                   /*AddTo*/ true);
21079     return true;
21080   }
21081
21082   // Don't try to re-form single instruction chains under any circumstances now
21083   // that we've done encoding canonicalization for them.
21084   if (Depth < 2)
21085     return false;
21086
21087   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21088   // can replace them with a single PSHUFB instruction profitably. Intel's
21089   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21090   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21091   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21092     SmallVector<SDValue, 16> PSHUFBMask;
21093     int NumBytes = VT.getSizeInBits() / 8;
21094     int Ratio = NumBytes / Mask.size();
21095     for (int i = 0; i < NumBytes; ++i) {
21096       if (Mask[i / Ratio] == SM_SentinelUndef) {
21097         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21098         continue;
21099       }
21100       int M = Mask[i / Ratio] != SM_SentinelZero
21101                   ? Ratio * Mask[i / Ratio] + i % Ratio
21102                   : 255;
21103       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21104     }
21105     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21106     Op = DAG.getBitcast(ByteVT, Input);
21107     DCI.AddToWorklist(Op.getNode());
21108     SDValue PSHUFBMaskOp =
21109         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21110     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21111     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21112     DCI.AddToWorklist(Op.getNode());
21113     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21114                   /*AddTo*/ true);
21115     return true;
21116   }
21117
21118   // Failed to find any combines.
21119   return false;
21120 }
21121
21122 /// \brief Fully generic combining of x86 shuffle instructions.
21123 ///
21124 /// This should be the last combine run over the x86 shuffle instructions. Once
21125 /// they have been fully optimized, this will recursively consider all chains
21126 /// of single-use shuffle instructions, build a generic model of the cumulative
21127 /// shuffle operation, and check for simpler instructions which implement this
21128 /// operation. We use this primarily for two purposes:
21129 ///
21130 /// 1) Collapse generic shuffles to specialized single instructions when
21131 ///    equivalent. In most cases, this is just an encoding size win, but
21132 ///    sometimes we will collapse multiple generic shuffles into a single
21133 ///    special-purpose shuffle.
21134 /// 2) Look for sequences of shuffle instructions with 3 or more total
21135 ///    instructions, and replace them with the slightly more expensive SSSE3
21136 ///    PSHUFB instruction if available. We do this as the last combining step
21137 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21138 ///    a suitable short sequence of other instructions. The PHUFB will either
21139 ///    use a register or have to read from memory and so is slightly (but only
21140 ///    slightly) more expensive than the other shuffle instructions.
21141 ///
21142 /// Because this is inherently a quadratic operation (for each shuffle in
21143 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21144 /// This should never be an issue in practice as the shuffle lowering doesn't
21145 /// produce sequences of more than 8 instructions.
21146 ///
21147 /// FIXME: We will currently miss some cases where the redundant shuffling
21148 /// would simplify under the threshold for PSHUFB formation because of
21149 /// combine-ordering. To fix this, we should do the redundant instruction
21150 /// combining in this recursive walk.
21151 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21152                                           ArrayRef<int> RootMask,
21153                                           int Depth, bool HasPSHUFB,
21154                                           SelectionDAG &DAG,
21155                                           TargetLowering::DAGCombinerInfo &DCI,
21156                                           const X86Subtarget *Subtarget) {
21157   // Bound the depth of our recursive combine because this is ultimately
21158   // quadratic in nature.
21159   if (Depth > 8)
21160     return false;
21161
21162   // Directly rip through bitcasts to find the underlying operand.
21163   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21164     Op = Op.getOperand(0);
21165
21166   MVT VT = Op.getSimpleValueType();
21167   if (!VT.isVector())
21168     return false; // Bail if we hit a non-vector.
21169
21170   assert(Root.getSimpleValueType().isVector() &&
21171          "Shuffles operate on vector types!");
21172   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21173          "Can only combine shuffles of the same vector register size.");
21174
21175   if (!isTargetShuffle(Op.getOpcode()))
21176     return false;
21177   SmallVector<int, 16> OpMask;
21178   bool IsUnary;
21179   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21180   // We only can combine unary shuffles which we can decode the mask for.
21181   if (!HaveMask || !IsUnary)
21182     return false;
21183
21184   assert(VT.getVectorNumElements() == OpMask.size() &&
21185          "Different mask size from vector size!");
21186   assert(((RootMask.size() > OpMask.size() &&
21187            RootMask.size() % OpMask.size() == 0) ||
21188           (OpMask.size() > RootMask.size() &&
21189            OpMask.size() % RootMask.size() == 0) ||
21190           OpMask.size() == RootMask.size()) &&
21191          "The smaller number of elements must divide the larger.");
21192   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21193   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21194   assert(((RootRatio == 1 && OpRatio == 1) ||
21195           (RootRatio == 1) != (OpRatio == 1)) &&
21196          "Must not have a ratio for both incoming and op masks!");
21197
21198   SmallVector<int, 16> Mask;
21199   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21200
21201   // Merge this shuffle operation's mask into our accumulated mask. Note that
21202   // this shuffle's mask will be the first applied to the input, followed by the
21203   // root mask to get us all the way to the root value arrangement. The reason
21204   // for this order is that we are recursing up the operation chain.
21205   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21206     int RootIdx = i / RootRatio;
21207     if (RootMask[RootIdx] < 0) {
21208       // This is a zero or undef lane, we're done.
21209       Mask.push_back(RootMask[RootIdx]);
21210       continue;
21211     }
21212
21213     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21214     int OpIdx = RootMaskedIdx / OpRatio;
21215     if (OpMask[OpIdx] < 0) {
21216       // The incoming lanes are zero or undef, it doesn't matter which ones we
21217       // are using.
21218       Mask.push_back(OpMask[OpIdx]);
21219       continue;
21220     }
21221
21222     // Ok, we have non-zero lanes, map them through.
21223     Mask.push_back(OpMask[OpIdx] * OpRatio +
21224                    RootMaskedIdx % OpRatio);
21225   }
21226
21227   // See if we can recurse into the operand to combine more things.
21228   switch (Op.getOpcode()) {
21229     case X86ISD::PSHUFB:
21230       HasPSHUFB = true;
21231     case X86ISD::PSHUFD:
21232     case X86ISD::PSHUFHW:
21233     case X86ISD::PSHUFLW:
21234       if (Op.getOperand(0).hasOneUse() &&
21235           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21236                                         HasPSHUFB, DAG, DCI, Subtarget))
21237         return true;
21238       break;
21239
21240     case X86ISD::UNPCKL:
21241     case X86ISD::UNPCKH:
21242       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21243       // We can't check for single use, we have to check that this shuffle is the only user.
21244       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21245           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21246                                         HasPSHUFB, DAG, DCI, Subtarget))
21247           return true;
21248       break;
21249   }
21250
21251   // Minor canonicalization of the accumulated shuffle mask to make it easier
21252   // to match below. All this does is detect masks with squential pairs of
21253   // elements, and shrink them to the half-width mask. It does this in a loop
21254   // so it will reduce the size of the mask to the minimal width mask which
21255   // performs an equivalent shuffle.
21256   SmallVector<int, 16> WidenedMask;
21257   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21258     Mask = std::move(WidenedMask);
21259     WidenedMask.clear();
21260   }
21261
21262   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21263                                 Subtarget);
21264 }
21265
21266 /// \brief Get the PSHUF-style mask from PSHUF node.
21267 ///
21268 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21269 /// PSHUF-style masks that can be reused with such instructions.
21270 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21271   MVT VT = N.getSimpleValueType();
21272   SmallVector<int, 4> Mask;
21273   bool IsUnary;
21274   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21275   (void)HaveMask;
21276   assert(HaveMask);
21277
21278   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21279   // matter. Check that the upper masks are repeats and remove them.
21280   if (VT.getSizeInBits() > 128) {
21281     int LaneElts = 128 / VT.getScalarSizeInBits();
21282 #ifndef NDEBUG
21283     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21284       for (int j = 0; j < LaneElts; ++j)
21285         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21286                "Mask doesn't repeat in high 128-bit lanes!");
21287 #endif
21288     Mask.resize(LaneElts);
21289   }
21290
21291   switch (N.getOpcode()) {
21292   case X86ISD::PSHUFD:
21293     return Mask;
21294   case X86ISD::PSHUFLW:
21295     Mask.resize(4);
21296     return Mask;
21297   case X86ISD::PSHUFHW:
21298     Mask.erase(Mask.begin(), Mask.begin() + 4);
21299     for (int &M : Mask)
21300       M -= 4;
21301     return Mask;
21302   default:
21303     llvm_unreachable("No valid shuffle instruction found!");
21304   }
21305 }
21306
21307 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21308 ///
21309 /// We walk up the chain and look for a combinable shuffle, skipping over
21310 /// shuffles that we could hoist this shuffle's transformation past without
21311 /// altering anything.
21312 static SDValue
21313 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21314                              SelectionDAG &DAG,
21315                              TargetLowering::DAGCombinerInfo &DCI) {
21316   assert(N.getOpcode() == X86ISD::PSHUFD &&
21317          "Called with something other than an x86 128-bit half shuffle!");
21318   SDLoc DL(N);
21319
21320   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21321   // of the shuffles in the chain so that we can form a fresh chain to replace
21322   // this one.
21323   SmallVector<SDValue, 8> Chain;
21324   SDValue V = N.getOperand(0);
21325   for (; V.hasOneUse(); V = V.getOperand(0)) {
21326     switch (V.getOpcode()) {
21327     default:
21328       return SDValue(); // Nothing combined!
21329
21330     case ISD::BITCAST:
21331       // Skip bitcasts as we always know the type for the target specific
21332       // instructions.
21333       continue;
21334
21335     case X86ISD::PSHUFD:
21336       // Found another dword shuffle.
21337       break;
21338
21339     case X86ISD::PSHUFLW:
21340       // Check that the low words (being shuffled) are the identity in the
21341       // dword shuffle, and the high words are self-contained.
21342       if (Mask[0] != 0 || Mask[1] != 1 ||
21343           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21344         return SDValue();
21345
21346       Chain.push_back(V);
21347       continue;
21348
21349     case X86ISD::PSHUFHW:
21350       // Check that the high words (being shuffled) are the identity in the
21351       // dword shuffle, and the low words are self-contained.
21352       if (Mask[2] != 2 || Mask[3] != 3 ||
21353           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21354         return SDValue();
21355
21356       Chain.push_back(V);
21357       continue;
21358
21359     case X86ISD::UNPCKL:
21360     case X86ISD::UNPCKH:
21361       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21362       // shuffle into a preceding word shuffle.
21363       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21364           V.getSimpleValueType().getScalarType() != MVT::i16)
21365         return SDValue();
21366
21367       // Search for a half-shuffle which we can combine with.
21368       unsigned CombineOp =
21369           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21370       if (V.getOperand(0) != V.getOperand(1) ||
21371           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21372         return SDValue();
21373       Chain.push_back(V);
21374       V = V.getOperand(0);
21375       do {
21376         switch (V.getOpcode()) {
21377         default:
21378           return SDValue(); // Nothing to combine.
21379
21380         case X86ISD::PSHUFLW:
21381         case X86ISD::PSHUFHW:
21382           if (V.getOpcode() == CombineOp)
21383             break;
21384
21385           Chain.push_back(V);
21386
21387           // Fallthrough!
21388         case ISD::BITCAST:
21389           V = V.getOperand(0);
21390           continue;
21391         }
21392         break;
21393       } while (V.hasOneUse());
21394       break;
21395     }
21396     // Break out of the loop if we break out of the switch.
21397     break;
21398   }
21399
21400   if (!V.hasOneUse())
21401     // We fell out of the loop without finding a viable combining instruction.
21402     return SDValue();
21403
21404   // Merge this node's mask and our incoming mask.
21405   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21406   for (int &M : Mask)
21407     M = VMask[M];
21408   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21409                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21410
21411   // Rebuild the chain around this new shuffle.
21412   while (!Chain.empty()) {
21413     SDValue W = Chain.pop_back_val();
21414
21415     if (V.getValueType() != W.getOperand(0).getValueType())
21416       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21417
21418     switch (W.getOpcode()) {
21419     default:
21420       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21421
21422     case X86ISD::UNPCKL:
21423     case X86ISD::UNPCKH:
21424       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21425       break;
21426
21427     case X86ISD::PSHUFD:
21428     case X86ISD::PSHUFLW:
21429     case X86ISD::PSHUFHW:
21430       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21431       break;
21432     }
21433   }
21434   if (V.getValueType() != N.getValueType())
21435     V = DAG.getBitcast(N.getValueType(), V);
21436
21437   // Return the new chain to replace N.
21438   return V;
21439 }
21440
21441 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21442 ///
21443 /// We walk up the chain, skipping shuffles of the other half and looking
21444 /// through shuffles which switch halves trying to find a shuffle of the same
21445 /// pair of dwords.
21446 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21447                                         SelectionDAG &DAG,
21448                                         TargetLowering::DAGCombinerInfo &DCI) {
21449   assert(
21450       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21451       "Called with something other than an x86 128-bit half shuffle!");
21452   SDLoc DL(N);
21453   unsigned CombineOpcode = N.getOpcode();
21454
21455   // Walk up a single-use chain looking for a combinable shuffle.
21456   SDValue V = N.getOperand(0);
21457   for (; V.hasOneUse(); V = V.getOperand(0)) {
21458     switch (V.getOpcode()) {
21459     default:
21460       return false; // Nothing combined!
21461
21462     case ISD::BITCAST:
21463       // Skip bitcasts as we always know the type for the target specific
21464       // instructions.
21465       continue;
21466
21467     case X86ISD::PSHUFLW:
21468     case X86ISD::PSHUFHW:
21469       if (V.getOpcode() == CombineOpcode)
21470         break;
21471
21472       // Other-half shuffles are no-ops.
21473       continue;
21474     }
21475     // Break out of the loop if we break out of the switch.
21476     break;
21477   }
21478
21479   if (!V.hasOneUse())
21480     // We fell out of the loop without finding a viable combining instruction.
21481     return false;
21482
21483   // Combine away the bottom node as its shuffle will be accumulated into
21484   // a preceding shuffle.
21485   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21486
21487   // Record the old value.
21488   SDValue Old = V;
21489
21490   // Merge this node's mask and our incoming mask (adjusted to account for all
21491   // the pshufd instructions encountered).
21492   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21493   for (int &M : Mask)
21494     M = VMask[M];
21495   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21496                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21497
21498   // Check that the shuffles didn't cancel each other out. If not, we need to
21499   // combine to the new one.
21500   if (Old != V)
21501     // Replace the combinable shuffle with the combined one, updating all users
21502     // so that we re-evaluate the chain here.
21503     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21504
21505   return true;
21506 }
21507
21508 /// \brief Try to combine x86 target specific shuffles.
21509 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21510                                            TargetLowering::DAGCombinerInfo &DCI,
21511                                            const X86Subtarget *Subtarget) {
21512   SDLoc DL(N);
21513   MVT VT = N.getSimpleValueType();
21514   SmallVector<int, 4> Mask;
21515
21516   switch (N.getOpcode()) {
21517   case X86ISD::PSHUFD:
21518   case X86ISD::PSHUFLW:
21519   case X86ISD::PSHUFHW:
21520     Mask = getPSHUFShuffleMask(N);
21521     assert(Mask.size() == 4);
21522     break;
21523   default:
21524     return SDValue();
21525   }
21526
21527   // Nuke no-op shuffles that show up after combining.
21528   if (isNoopShuffleMask(Mask))
21529     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21530
21531   // Look for simplifications involving one or two shuffle instructions.
21532   SDValue V = N.getOperand(0);
21533   switch (N.getOpcode()) {
21534   default:
21535     break;
21536   case X86ISD::PSHUFLW:
21537   case X86ISD::PSHUFHW:
21538     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21539
21540     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21541       return SDValue(); // We combined away this shuffle, so we're done.
21542
21543     // See if this reduces to a PSHUFD which is no more expensive and can
21544     // combine with more operations. Note that it has to at least flip the
21545     // dwords as otherwise it would have been removed as a no-op.
21546     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21547       int DMask[] = {0, 1, 2, 3};
21548       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21549       DMask[DOffset + 0] = DOffset + 1;
21550       DMask[DOffset + 1] = DOffset + 0;
21551       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21552       V = DAG.getBitcast(DVT, V);
21553       DCI.AddToWorklist(V.getNode());
21554       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21555                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21556       DCI.AddToWorklist(V.getNode());
21557       return DAG.getBitcast(VT, V);
21558     }
21559
21560     // Look for shuffle patterns which can be implemented as a single unpack.
21561     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21562     // only works when we have a PSHUFD followed by two half-shuffles.
21563     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21564         (V.getOpcode() == X86ISD::PSHUFLW ||
21565          V.getOpcode() == X86ISD::PSHUFHW) &&
21566         V.getOpcode() != N.getOpcode() &&
21567         V.hasOneUse()) {
21568       SDValue D = V.getOperand(0);
21569       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21570         D = D.getOperand(0);
21571       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21572         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21573         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21574         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21575         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21576         int WordMask[8];
21577         for (int i = 0; i < 4; ++i) {
21578           WordMask[i + NOffset] = Mask[i] + NOffset;
21579           WordMask[i + VOffset] = VMask[i] + VOffset;
21580         }
21581         // Map the word mask through the DWord mask.
21582         int MappedMask[8];
21583         for (int i = 0; i < 8; ++i)
21584           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21585         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21586             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21587           // We can replace all three shuffles with an unpack.
21588           V = DAG.getBitcast(VT, D.getOperand(0));
21589           DCI.AddToWorklist(V.getNode());
21590           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21591                                                 : X86ISD::UNPCKH,
21592                              DL, VT, V, V);
21593         }
21594       }
21595     }
21596
21597     break;
21598
21599   case X86ISD::PSHUFD:
21600     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21601       return NewN;
21602
21603     break;
21604   }
21605
21606   return SDValue();
21607 }
21608
21609 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21610 ///
21611 /// We combine this directly on the abstract vector shuffle nodes so it is
21612 /// easier to generically match. We also insert dummy vector shuffle nodes for
21613 /// the operands which explicitly discard the lanes which are unused by this
21614 /// operation to try to flow through the rest of the combiner the fact that
21615 /// they're unused.
21616 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21617   SDLoc DL(N);
21618   EVT VT = N->getValueType(0);
21619
21620   // We only handle target-independent shuffles.
21621   // FIXME: It would be easy and harmless to use the target shuffle mask
21622   // extraction tool to support more.
21623   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21624     return SDValue();
21625
21626   auto *SVN = cast<ShuffleVectorSDNode>(N);
21627   ArrayRef<int> Mask = SVN->getMask();
21628   SDValue V1 = N->getOperand(0);
21629   SDValue V2 = N->getOperand(1);
21630
21631   // We require the first shuffle operand to be the SUB node, and the second to
21632   // be the ADD node.
21633   // FIXME: We should support the commuted patterns.
21634   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21635     return SDValue();
21636
21637   // If there are other uses of these operations we can't fold them.
21638   if (!V1->hasOneUse() || !V2->hasOneUse())
21639     return SDValue();
21640
21641   // Ensure that both operations have the same operands. Note that we can
21642   // commute the FADD operands.
21643   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21644   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21645       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21646     return SDValue();
21647
21648   // We're looking for blends between FADD and FSUB nodes. We insist on these
21649   // nodes being lined up in a specific expected pattern.
21650   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21651         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21652         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21653     return SDValue();
21654
21655   // Only specific types are legal at this point, assert so we notice if and
21656   // when these change.
21657   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21658           VT == MVT::v4f64) &&
21659          "Unknown vector type encountered!");
21660
21661   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21662 }
21663
21664 /// PerformShuffleCombine - Performs several different shuffle combines.
21665 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21666                                      TargetLowering::DAGCombinerInfo &DCI,
21667                                      const X86Subtarget *Subtarget) {
21668   SDLoc dl(N);
21669   SDValue N0 = N->getOperand(0);
21670   SDValue N1 = N->getOperand(1);
21671   EVT VT = N->getValueType(0);
21672
21673   // Don't create instructions with illegal types after legalize types has run.
21674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21675   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21676     return SDValue();
21677
21678   // If we have legalized the vector types, look for blends of FADD and FSUB
21679   // nodes that we can fuse into an ADDSUB node.
21680   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21681     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21682       return AddSub;
21683
21684   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21685   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21686       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21687     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21688
21689   // During Type Legalization, when promoting illegal vector types,
21690   // the backend might introduce new shuffle dag nodes and bitcasts.
21691   //
21692   // This code performs the following transformation:
21693   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21694   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21695   //
21696   // We do this only if both the bitcast and the BINOP dag nodes have
21697   // one use. Also, perform this transformation only if the new binary
21698   // operation is legal. This is to avoid introducing dag nodes that
21699   // potentially need to be further expanded (or custom lowered) into a
21700   // less optimal sequence of dag nodes.
21701   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21702       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21703       N0.getOpcode() == ISD::BITCAST) {
21704     SDValue BC0 = N0.getOperand(0);
21705     EVT SVT = BC0.getValueType();
21706     unsigned Opcode = BC0.getOpcode();
21707     unsigned NumElts = VT.getVectorNumElements();
21708
21709     if (BC0.hasOneUse() && SVT.isVector() &&
21710         SVT.getVectorNumElements() * 2 == NumElts &&
21711         TLI.isOperationLegal(Opcode, VT)) {
21712       bool CanFold = false;
21713       switch (Opcode) {
21714       default : break;
21715       case ISD::ADD :
21716       case ISD::FADD :
21717       case ISD::SUB :
21718       case ISD::FSUB :
21719       case ISD::MUL :
21720       case ISD::FMUL :
21721         CanFold = true;
21722       }
21723
21724       unsigned SVTNumElts = SVT.getVectorNumElements();
21725       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21726       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21727         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21728       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21729         CanFold = SVOp->getMaskElt(i) < 0;
21730
21731       if (CanFold) {
21732         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21733         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21734         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21735         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21736       }
21737     }
21738   }
21739
21740   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21741   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21742   // consecutive, non-overlapping, and in the right order.
21743   SmallVector<SDValue, 16> Elts;
21744   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21745     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21746
21747   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21748     return LD;
21749
21750   if (isTargetShuffle(N->getOpcode())) {
21751     SDValue Shuffle =
21752         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21753     if (Shuffle.getNode())
21754       return Shuffle;
21755
21756     // Try recursively combining arbitrary sequences of x86 shuffle
21757     // instructions into higher-order shuffles. We do this after combining
21758     // specific PSHUF instruction sequences into their minimal form so that we
21759     // can evaluate how many specialized shuffle instructions are involved in
21760     // a particular chain.
21761     SmallVector<int, 1> NonceMask; // Just a placeholder.
21762     NonceMask.push_back(0);
21763     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21764                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21765                                       DCI, Subtarget))
21766       return SDValue(); // This routine will use CombineTo to replace N.
21767   }
21768
21769   return SDValue();
21770 }
21771
21772 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21773 /// specific shuffle of a load can be folded into a single element load.
21774 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21775 /// shuffles have been custom lowered so we need to handle those here.
21776 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21777                                          TargetLowering::DAGCombinerInfo &DCI) {
21778   if (DCI.isBeforeLegalizeOps())
21779     return SDValue();
21780
21781   SDValue InVec = N->getOperand(0);
21782   SDValue EltNo = N->getOperand(1);
21783
21784   if (!isa<ConstantSDNode>(EltNo))
21785     return SDValue();
21786
21787   EVT OriginalVT = InVec.getValueType();
21788
21789   if (InVec.getOpcode() == ISD::BITCAST) {
21790     // Don't duplicate a load with other uses.
21791     if (!InVec.hasOneUse())
21792       return SDValue();
21793     EVT BCVT = InVec.getOperand(0).getValueType();
21794     if (!BCVT.isVector() ||
21795         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21796       return SDValue();
21797     InVec = InVec.getOperand(0);
21798   }
21799
21800   EVT CurrentVT = InVec.getValueType();
21801
21802   if (!isTargetShuffle(InVec.getOpcode()))
21803     return SDValue();
21804
21805   // Don't duplicate a load with other uses.
21806   if (!InVec.hasOneUse())
21807     return SDValue();
21808
21809   SmallVector<int, 16> ShuffleMask;
21810   bool UnaryShuffle;
21811   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21812                             ShuffleMask, UnaryShuffle))
21813     return SDValue();
21814
21815   // Select the input vector, guarding against out of range extract vector.
21816   unsigned NumElems = CurrentVT.getVectorNumElements();
21817   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21818   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21819   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21820                                          : InVec.getOperand(1);
21821
21822   // If inputs to shuffle are the same for both ops, then allow 2 uses
21823   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21824                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21825
21826   if (LdNode.getOpcode() == ISD::BITCAST) {
21827     // Don't duplicate a load with other uses.
21828     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21829       return SDValue();
21830
21831     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21832     LdNode = LdNode.getOperand(0);
21833   }
21834
21835   if (!ISD::isNormalLoad(LdNode.getNode()))
21836     return SDValue();
21837
21838   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21839
21840   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21841     return SDValue();
21842
21843   EVT EltVT = N->getValueType(0);
21844   // If there's a bitcast before the shuffle, check if the load type and
21845   // alignment is valid.
21846   unsigned Align = LN0->getAlignment();
21847   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21848   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21849       EltVT.getTypeForEVT(*DAG.getContext()));
21850
21851   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21852     return SDValue();
21853
21854   // All checks match so transform back to vector_shuffle so that DAG combiner
21855   // can finish the job
21856   SDLoc dl(N);
21857
21858   // Create shuffle node taking into account the case that its a unary shuffle
21859   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21860                                    : InVec.getOperand(1);
21861   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21862                                  InVec.getOperand(0), Shuffle,
21863                                  &ShuffleMask[0]);
21864   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21865   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21866                      EltNo);
21867 }
21868
21869 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21870 /// special and don't usually play with other vector types, it's better to
21871 /// handle them early to be sure we emit efficient code by avoiding
21872 /// store-load conversions.
21873 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21874   if (N->getValueType(0) != MVT::x86mmx ||
21875       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21876       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21877     return SDValue();
21878
21879   SDValue V = N->getOperand(0);
21880   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21881   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21882     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21883                        N->getValueType(0), V.getOperand(0));
21884
21885   return SDValue();
21886 }
21887
21888 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21889 /// generation and convert it from being a bunch of shuffles and extracts
21890 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21891 /// storing the value and loading scalars back, while for x64 we should
21892 /// use 64-bit extracts and shifts.
21893 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21894                                          TargetLowering::DAGCombinerInfo &DCI) {
21895   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21896     return NewOp;
21897
21898   SDValue InputVector = N->getOperand(0);
21899   SDLoc dl(InputVector);
21900   // Detect mmx to i32 conversion through a v2i32 elt extract.
21901   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21902       N->getValueType(0) == MVT::i32 &&
21903       InputVector.getValueType() == MVT::v2i32) {
21904
21905     // The bitcast source is a direct mmx result.
21906     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21907     if (MMXSrc.getValueType() == MVT::x86mmx)
21908       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21909                          N->getValueType(0),
21910                          InputVector.getNode()->getOperand(0));
21911
21912     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21913     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21914     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21915         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21916         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21917         MMXSrcOp.getValueType() == MVT::v1i64 &&
21918         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21919       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21920                          N->getValueType(0),
21921                          MMXSrcOp.getOperand(0));
21922   }
21923
21924   EVT VT = N->getValueType(0);
21925
21926   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21927       InputVector.getOpcode() == ISD::BITCAST &&
21928       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21929     uint64_t ExtractedElt =
21930           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21931     uint64_t InputValue =
21932           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21933     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21934     return DAG.getConstant(Res, dl, MVT::i1);
21935   }
21936   // Only operate on vectors of 4 elements, where the alternative shuffling
21937   // gets to be more expensive.
21938   if (InputVector.getValueType() != MVT::v4i32)
21939     return SDValue();
21940
21941   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21942   // single use which is a sign-extend or zero-extend, and all elements are
21943   // used.
21944   SmallVector<SDNode *, 4> Uses;
21945   unsigned ExtractedElements = 0;
21946   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21947        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21948     if (UI.getUse().getResNo() != InputVector.getResNo())
21949       return SDValue();
21950
21951     SDNode *Extract = *UI;
21952     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21953       return SDValue();
21954
21955     if (Extract->getValueType(0) != MVT::i32)
21956       return SDValue();
21957     if (!Extract->hasOneUse())
21958       return SDValue();
21959     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21960         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21961       return SDValue();
21962     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21963       return SDValue();
21964
21965     // Record which element was extracted.
21966     ExtractedElements |=
21967       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21968
21969     Uses.push_back(Extract);
21970   }
21971
21972   // If not all the elements were used, this may not be worthwhile.
21973   if (ExtractedElements != 15)
21974     return SDValue();
21975
21976   // Ok, we've now decided to do the transformation.
21977   // If 64-bit shifts are legal, use the extract-shift sequence,
21978   // otherwise bounce the vector off the cache.
21979   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21980   SDValue Vals[4];
21981
21982   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21983     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21984     auto &DL = DAG.getDataLayout();
21985     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
21986     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21987       DAG.getConstant(0, dl, VecIdxTy));
21988     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21989       DAG.getConstant(1, dl, VecIdxTy));
21990
21991     SDValue ShAmt = DAG.getConstant(
21992         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
21993     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21994     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21995       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21996     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21997     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21998       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21999   } else {
22000     // Store the value to a temporary stack slot.
22001     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22002     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22003       MachinePointerInfo(), false, false, 0);
22004
22005     EVT ElementType = InputVector.getValueType().getVectorElementType();
22006     unsigned EltSize = ElementType.getSizeInBits() / 8;
22007
22008     // Replace each use (extract) with a load of the appropriate element.
22009     for (unsigned i = 0; i < 4; ++i) {
22010       uint64_t Offset = EltSize * i;
22011       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22012       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22013
22014       SDValue ScalarAddr =
22015           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22016
22017       // Load the scalar.
22018       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22019                             ScalarAddr, MachinePointerInfo(),
22020                             false, false, false, 0);
22021
22022     }
22023   }
22024
22025   // Replace the extracts
22026   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22027     UE = Uses.end(); UI != UE; ++UI) {
22028     SDNode *Extract = *UI;
22029
22030     SDValue Idx = Extract->getOperand(1);
22031     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22032     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22033   }
22034
22035   // The replacement was made in place; don't return anything.
22036   return SDValue();
22037 }
22038
22039 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22040 static std::pair<unsigned, bool>
22041 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22042                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22043   if (!VT.isVector())
22044     return std::make_pair(0, false);
22045
22046   bool NeedSplit = false;
22047   switch (VT.getSimpleVT().SimpleTy) {
22048   default: return std::make_pair(0, false);
22049   case MVT::v4i64:
22050   case MVT::v2i64:
22051     if (!Subtarget->hasVLX())
22052       return std::make_pair(0, false);
22053     break;
22054   case MVT::v64i8:
22055   case MVT::v32i16:
22056     if (!Subtarget->hasBWI())
22057       return std::make_pair(0, false);
22058     break;
22059   case MVT::v16i32:
22060   case MVT::v8i64:
22061     if (!Subtarget->hasAVX512())
22062       return std::make_pair(0, false);
22063     break;
22064   case MVT::v32i8:
22065   case MVT::v16i16:
22066   case MVT::v8i32:
22067     if (!Subtarget->hasAVX2())
22068       NeedSplit = true;
22069     if (!Subtarget->hasAVX())
22070       return std::make_pair(0, false);
22071     break;
22072   case MVT::v16i8:
22073   case MVT::v8i16:
22074   case MVT::v4i32:
22075     if (!Subtarget->hasSSE2())
22076       return std::make_pair(0, false);
22077   }
22078
22079   // SSE2 has only a small subset of the operations.
22080   bool hasUnsigned = Subtarget->hasSSE41() ||
22081                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22082   bool hasSigned = Subtarget->hasSSE41() ||
22083                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22084
22085   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22086
22087   unsigned Opc = 0;
22088   // Check for x CC y ? x : y.
22089   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22090       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22091     switch (CC) {
22092     default: break;
22093     case ISD::SETULT:
22094     case ISD::SETULE:
22095       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22096     case ISD::SETUGT:
22097     case ISD::SETUGE:
22098       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22099     case ISD::SETLT:
22100     case ISD::SETLE:
22101       Opc = hasSigned ? ISD::SMIN : 0; break;
22102     case ISD::SETGT:
22103     case ISD::SETGE:
22104       Opc = hasSigned ? ISD::SMAX : 0; break;
22105     }
22106   // Check for x CC y ? y : x -- a min/max with reversed arms.
22107   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22108              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22109     switch (CC) {
22110     default: break;
22111     case ISD::SETULT:
22112     case ISD::SETULE:
22113       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22114     case ISD::SETUGT:
22115     case ISD::SETUGE:
22116       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22117     case ISD::SETLT:
22118     case ISD::SETLE:
22119       Opc = hasSigned ? ISD::SMAX : 0; break;
22120     case ISD::SETGT:
22121     case ISD::SETGE:
22122       Opc = hasSigned ? ISD::SMIN : 0; break;
22123     }
22124   }
22125
22126   return std::make_pair(Opc, NeedSplit);
22127 }
22128
22129 static SDValue
22130 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22131                                       const X86Subtarget *Subtarget) {
22132   SDLoc dl(N);
22133   SDValue Cond = N->getOperand(0);
22134   SDValue LHS = N->getOperand(1);
22135   SDValue RHS = N->getOperand(2);
22136
22137   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22138     SDValue CondSrc = Cond->getOperand(0);
22139     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22140       Cond = CondSrc->getOperand(0);
22141   }
22142
22143   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22144     return SDValue();
22145
22146   // A vselect where all conditions and data are constants can be optimized into
22147   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22148   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22149       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22150     return SDValue();
22151
22152   unsigned MaskValue = 0;
22153   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22154     return SDValue();
22155
22156   MVT VT = N->getSimpleValueType(0);
22157   unsigned NumElems = VT.getVectorNumElements();
22158   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22159   for (unsigned i = 0; i < NumElems; ++i) {
22160     // Be sure we emit undef where we can.
22161     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22162       ShuffleMask[i] = -1;
22163     else
22164       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22165   }
22166
22167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22168   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22169     return SDValue();
22170   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22171 }
22172
22173 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22174 /// nodes.
22175 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22176                                     TargetLowering::DAGCombinerInfo &DCI,
22177                                     const X86Subtarget *Subtarget) {
22178   SDLoc DL(N);
22179   SDValue Cond = N->getOperand(0);
22180   // Get the LHS/RHS of the select.
22181   SDValue LHS = N->getOperand(1);
22182   SDValue RHS = N->getOperand(2);
22183   EVT VT = LHS.getValueType();
22184   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22185
22186   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22187   // instructions match the semantics of the common C idiom x<y?x:y but not
22188   // x<=y?x:y, because of how they handle negative zero (which can be
22189   // ignored in unsafe-math mode).
22190   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22191   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22192       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22193       (Subtarget->hasSSE2() ||
22194        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22195     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22196
22197     unsigned Opcode = 0;
22198     // Check for x CC y ? x : y.
22199     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22200         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22201       switch (CC) {
22202       default: break;
22203       case ISD::SETULT:
22204         // Converting this to a min would handle NaNs incorrectly, and swapping
22205         // the operands would cause it to handle comparisons between positive
22206         // and negative zero incorrectly.
22207         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22208           if (!DAG.getTarget().Options.UnsafeFPMath &&
22209               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22210             break;
22211           std::swap(LHS, RHS);
22212         }
22213         Opcode = X86ISD::FMIN;
22214         break;
22215       case ISD::SETOLE:
22216         // Converting this to a min would handle comparisons between positive
22217         // and negative zero incorrectly.
22218         if (!DAG.getTarget().Options.UnsafeFPMath &&
22219             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22220           break;
22221         Opcode = X86ISD::FMIN;
22222         break;
22223       case ISD::SETULE:
22224         // Converting this to a min would handle both negative zeros and NaNs
22225         // incorrectly, but we can swap the operands to fix both.
22226         std::swap(LHS, RHS);
22227       case ISD::SETOLT:
22228       case ISD::SETLT:
22229       case ISD::SETLE:
22230         Opcode = X86ISD::FMIN;
22231         break;
22232
22233       case ISD::SETOGE:
22234         // Converting this to a max would handle comparisons between positive
22235         // and negative zero incorrectly.
22236         if (!DAG.getTarget().Options.UnsafeFPMath &&
22237             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22238           break;
22239         Opcode = X86ISD::FMAX;
22240         break;
22241       case ISD::SETUGT:
22242         // Converting this to a max would handle NaNs incorrectly, and swapping
22243         // the operands would cause it to handle comparisons between positive
22244         // and negative zero incorrectly.
22245         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22246           if (!DAG.getTarget().Options.UnsafeFPMath &&
22247               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22248             break;
22249           std::swap(LHS, RHS);
22250         }
22251         Opcode = X86ISD::FMAX;
22252         break;
22253       case ISD::SETUGE:
22254         // Converting this to a max would handle both negative zeros and NaNs
22255         // incorrectly, but we can swap the operands to fix both.
22256         std::swap(LHS, RHS);
22257       case ISD::SETOGT:
22258       case ISD::SETGT:
22259       case ISD::SETGE:
22260         Opcode = X86ISD::FMAX;
22261         break;
22262       }
22263     // Check for x CC y ? y : x -- a min/max with reversed arms.
22264     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22265                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22266       switch (CC) {
22267       default: break;
22268       case ISD::SETOGE:
22269         // Converting this to a min would handle comparisons between positive
22270         // and negative zero incorrectly, and swapping the operands would
22271         // cause it to handle NaNs incorrectly.
22272         if (!DAG.getTarget().Options.UnsafeFPMath &&
22273             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22274           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22275             break;
22276           std::swap(LHS, RHS);
22277         }
22278         Opcode = X86ISD::FMIN;
22279         break;
22280       case ISD::SETUGT:
22281         // Converting this to a min would handle NaNs incorrectly.
22282         if (!DAG.getTarget().Options.UnsafeFPMath &&
22283             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22284           break;
22285         Opcode = X86ISD::FMIN;
22286         break;
22287       case ISD::SETUGE:
22288         // Converting this to a min would handle both negative zeros and NaNs
22289         // incorrectly, but we can swap the operands to fix both.
22290         std::swap(LHS, RHS);
22291       case ISD::SETOGT:
22292       case ISD::SETGT:
22293       case ISD::SETGE:
22294         Opcode = X86ISD::FMIN;
22295         break;
22296
22297       case ISD::SETULT:
22298         // Converting this to a max would handle NaNs incorrectly.
22299         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22300           break;
22301         Opcode = X86ISD::FMAX;
22302         break;
22303       case ISD::SETOLE:
22304         // Converting this to a max would handle comparisons between positive
22305         // and negative zero incorrectly, and swapping the operands would
22306         // cause it to handle NaNs incorrectly.
22307         if (!DAG.getTarget().Options.UnsafeFPMath &&
22308             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22309           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22310             break;
22311           std::swap(LHS, RHS);
22312         }
22313         Opcode = X86ISD::FMAX;
22314         break;
22315       case ISD::SETULE:
22316         // Converting this to a max would handle both negative zeros and NaNs
22317         // incorrectly, but we can swap the operands to fix both.
22318         std::swap(LHS, RHS);
22319       case ISD::SETOLT:
22320       case ISD::SETLT:
22321       case ISD::SETLE:
22322         Opcode = X86ISD::FMAX;
22323         break;
22324       }
22325     }
22326
22327     if (Opcode)
22328       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22329   }
22330
22331   EVT CondVT = Cond.getValueType();
22332   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22333       CondVT.getVectorElementType() == MVT::i1) {
22334     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22335     // lowering on KNL. In this case we convert it to
22336     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22337     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22338     // Since SKX these selects have a proper lowering.
22339     EVT OpVT = LHS.getValueType();
22340     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22341         (OpVT.getVectorElementType() == MVT::i8 ||
22342          OpVT.getVectorElementType() == MVT::i16) &&
22343         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22344       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22345       DCI.AddToWorklist(Cond.getNode());
22346       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22347     }
22348   }
22349   // If this is a select between two integer constants, try to do some
22350   // optimizations.
22351   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22352     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22353       // Don't do this for crazy integer types.
22354       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22355         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22356         // so that TrueC (the true value) is larger than FalseC.
22357         bool NeedsCondInvert = false;
22358
22359         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22360             // Efficiently invertible.
22361             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22362              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22363               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22364           NeedsCondInvert = true;
22365           std::swap(TrueC, FalseC);
22366         }
22367
22368         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22369         if (FalseC->getAPIntValue() == 0 &&
22370             TrueC->getAPIntValue().isPowerOf2()) {
22371           if (NeedsCondInvert) // Invert the condition if needed.
22372             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22373                                DAG.getConstant(1, DL, Cond.getValueType()));
22374
22375           // Zero extend the condition if needed.
22376           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22377
22378           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22379           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22380                              DAG.getConstant(ShAmt, DL, MVT::i8));
22381         }
22382
22383         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22384         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22385           if (NeedsCondInvert) // Invert the condition if needed.
22386             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22387                                DAG.getConstant(1, DL, Cond.getValueType()));
22388
22389           // Zero extend the condition if needed.
22390           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22391                              FalseC->getValueType(0), Cond);
22392           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22393                              SDValue(FalseC, 0));
22394         }
22395
22396         // Optimize cases that will turn into an LEA instruction.  This requires
22397         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22398         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22399           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22400           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22401
22402           bool isFastMultiplier = false;
22403           if (Diff < 10) {
22404             switch ((unsigned char)Diff) {
22405               default: break;
22406               case 1:  // result = add base, cond
22407               case 2:  // result = lea base(    , cond*2)
22408               case 3:  // result = lea base(cond, cond*2)
22409               case 4:  // result = lea base(    , cond*4)
22410               case 5:  // result = lea base(cond, cond*4)
22411               case 8:  // result = lea base(    , cond*8)
22412               case 9:  // result = lea base(cond, cond*8)
22413                 isFastMultiplier = true;
22414                 break;
22415             }
22416           }
22417
22418           if (isFastMultiplier) {
22419             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22420             if (NeedsCondInvert) // Invert the condition if needed.
22421               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22422                                  DAG.getConstant(1, DL, Cond.getValueType()));
22423
22424             // Zero extend the condition if needed.
22425             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22426                                Cond);
22427             // Scale the condition by the difference.
22428             if (Diff != 1)
22429               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22430                                  DAG.getConstant(Diff, DL,
22431                                                  Cond.getValueType()));
22432
22433             // Add the base if non-zero.
22434             if (FalseC->getAPIntValue() != 0)
22435               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22436                                  SDValue(FalseC, 0));
22437             return Cond;
22438           }
22439         }
22440       }
22441   }
22442
22443   // Canonicalize max and min:
22444   // (x > y) ? x : y -> (x >= y) ? x : y
22445   // (x < y) ? x : y -> (x <= y) ? x : y
22446   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22447   // the need for an extra compare
22448   // against zero. e.g.
22449   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22450   // subl   %esi, %edi
22451   // testl  %edi, %edi
22452   // movl   $0, %eax
22453   // cmovgl %edi, %eax
22454   // =>
22455   // xorl   %eax, %eax
22456   // subl   %esi, $edi
22457   // cmovsl %eax, %edi
22458   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22459       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22460       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22461     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22462     switch (CC) {
22463     default: break;
22464     case ISD::SETLT:
22465     case ISD::SETGT: {
22466       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22467       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22468                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22469       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22470     }
22471     }
22472   }
22473
22474   // Early exit check
22475   if (!TLI.isTypeLegal(VT))
22476     return SDValue();
22477
22478   // Match VSELECTs into subs with unsigned saturation.
22479   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22480       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22481       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22482        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22483     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22484
22485     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22486     // left side invert the predicate to simplify logic below.
22487     SDValue Other;
22488     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22489       Other = RHS;
22490       CC = ISD::getSetCCInverse(CC, true);
22491     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22492       Other = LHS;
22493     }
22494
22495     if (Other.getNode() && Other->getNumOperands() == 2 &&
22496         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22497       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22498       SDValue CondRHS = Cond->getOperand(1);
22499
22500       // Look for a general sub with unsigned saturation first.
22501       // x >= y ? x-y : 0 --> subus x, y
22502       // x >  y ? x-y : 0 --> subus x, y
22503       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22504           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22505         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22506
22507       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22508         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22509           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22510             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22511               // If the RHS is a constant we have to reverse the const
22512               // canonicalization.
22513               // x > C-1 ? x+-C : 0 --> subus x, C
22514               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22515                   CondRHSConst->getAPIntValue() ==
22516                       (-OpRHSConst->getAPIntValue() - 1))
22517                 return DAG.getNode(
22518                     X86ISD::SUBUS, DL, VT, OpLHS,
22519                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22520
22521           // Another special case: If C was a sign bit, the sub has been
22522           // canonicalized into a xor.
22523           // FIXME: Would it be better to use computeKnownBits to determine
22524           //        whether it's safe to decanonicalize the xor?
22525           // x s< 0 ? x^C : 0 --> subus x, C
22526           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22527               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22528               OpRHSConst->getAPIntValue().isSignBit())
22529             // Note that we have to rebuild the RHS constant here to ensure we
22530             // don't rely on particular values of undef lanes.
22531             return DAG.getNode(
22532                 X86ISD::SUBUS, DL, VT, OpLHS,
22533                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22534         }
22535     }
22536   }
22537
22538   // Try to match a min/max vector operation.
22539   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22540     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22541     unsigned Opc = ret.first;
22542     bool NeedSplit = ret.second;
22543
22544     if (Opc && NeedSplit) {
22545       unsigned NumElems = VT.getVectorNumElements();
22546       // Extract the LHS vectors
22547       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22548       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22549
22550       // Extract the RHS vectors
22551       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22552       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22553
22554       // Create min/max for each subvector
22555       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22556       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22557
22558       // Merge the result
22559       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22560     } else if (Opc)
22561       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22562   }
22563
22564   // Simplify vector selection if condition value type matches vselect
22565   // operand type
22566   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22567     assert(Cond.getValueType().isVector() &&
22568            "vector select expects a vector selector!");
22569
22570     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22571     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22572
22573     // Try invert the condition if true value is not all 1s and false value
22574     // is not all 0s.
22575     if (!TValIsAllOnes && !FValIsAllZeros &&
22576         // Check if the selector will be produced by CMPP*/PCMP*
22577         Cond.getOpcode() == ISD::SETCC &&
22578         // Check if SETCC has already been promoted
22579         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22580             CondVT) {
22581       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22582       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22583
22584       if (TValIsAllZeros || FValIsAllOnes) {
22585         SDValue CC = Cond.getOperand(2);
22586         ISD::CondCode NewCC =
22587           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22588                                Cond.getOperand(0).getValueType().isInteger());
22589         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22590         std::swap(LHS, RHS);
22591         TValIsAllOnes = FValIsAllOnes;
22592         FValIsAllZeros = TValIsAllZeros;
22593       }
22594     }
22595
22596     if (TValIsAllOnes || FValIsAllZeros) {
22597       SDValue Ret;
22598
22599       if (TValIsAllOnes && FValIsAllZeros)
22600         Ret = Cond;
22601       else if (TValIsAllOnes)
22602         Ret =
22603             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22604       else if (FValIsAllZeros)
22605         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22606                           DAG.getBitcast(CondVT, LHS));
22607
22608       return DAG.getBitcast(VT, Ret);
22609     }
22610   }
22611
22612   // We should generate an X86ISD::BLENDI from a vselect if its argument
22613   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22614   // constants. This specific pattern gets generated when we split a
22615   // selector for a 512 bit vector in a machine without AVX512 (but with
22616   // 256-bit vectors), during legalization:
22617   //
22618   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22619   //
22620   // Iff we find this pattern and the build_vectors are built from
22621   // constants, we translate the vselect into a shuffle_vector that we
22622   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22623   if ((N->getOpcode() == ISD::VSELECT ||
22624        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22625       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22626     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22627     if (Shuffle.getNode())
22628       return Shuffle;
22629   }
22630
22631   // If this is a *dynamic* select (non-constant condition) and we can match
22632   // this node with one of the variable blend instructions, restructure the
22633   // condition so that the blends can use the high bit of each element and use
22634   // SimplifyDemandedBits to simplify the condition operand.
22635   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22636       !DCI.isBeforeLegalize() &&
22637       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22638     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22639
22640     // Don't optimize vector selects that map to mask-registers.
22641     if (BitWidth == 1)
22642       return SDValue();
22643
22644     // We can only handle the cases where VSELECT is directly legal on the
22645     // subtarget. We custom lower VSELECT nodes with constant conditions and
22646     // this makes it hard to see whether a dynamic VSELECT will correctly
22647     // lower, so we both check the operation's status and explicitly handle the
22648     // cases where a *dynamic* blend will fail even though a constant-condition
22649     // blend could be custom lowered.
22650     // FIXME: We should find a better way to handle this class of problems.
22651     // Potentially, we should combine constant-condition vselect nodes
22652     // pre-legalization into shuffles and not mark as many types as custom
22653     // lowered.
22654     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22655       return SDValue();
22656     // FIXME: We don't support i16-element blends currently. We could and
22657     // should support them by making *all* the bits in the condition be set
22658     // rather than just the high bit and using an i8-element blend.
22659     if (VT.getScalarType() == MVT::i16)
22660       return SDValue();
22661     // Dynamic blending was only available from SSE4.1 onward.
22662     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22663       return SDValue();
22664     // Byte blends are only available in AVX2
22665     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22666         !Subtarget->hasAVX2())
22667       return SDValue();
22668
22669     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22670     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22671
22672     APInt KnownZero, KnownOne;
22673     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22674                                           DCI.isBeforeLegalizeOps());
22675     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22676         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22677                                  TLO)) {
22678       // If we changed the computation somewhere in the DAG, this change
22679       // will affect all users of Cond.
22680       // Make sure it is fine and update all the nodes so that we do not
22681       // use the generic VSELECT anymore. Otherwise, we may perform
22682       // wrong optimizations as we messed up with the actual expectation
22683       // for the vector boolean values.
22684       if (Cond != TLO.Old) {
22685         // Check all uses of that condition operand to check whether it will be
22686         // consumed by non-BLEND instructions, which may depend on all bits are
22687         // set properly.
22688         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22689              I != E; ++I)
22690           if (I->getOpcode() != ISD::VSELECT)
22691             // TODO: Add other opcodes eventually lowered into BLEND.
22692             return SDValue();
22693
22694         // Update all the users of the condition, before committing the change,
22695         // so that the VSELECT optimizations that expect the correct vector
22696         // boolean value will not be triggered.
22697         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22698              I != E; ++I)
22699           DAG.ReplaceAllUsesOfValueWith(
22700               SDValue(*I, 0),
22701               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22702                           Cond, I->getOperand(1), I->getOperand(2)));
22703         DCI.CommitTargetLoweringOpt(TLO);
22704         return SDValue();
22705       }
22706       // At this point, only Cond is changed. Change the condition
22707       // just for N to keep the opportunity to optimize all other
22708       // users their own way.
22709       DAG.ReplaceAllUsesOfValueWith(
22710           SDValue(N, 0),
22711           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22712                       TLO.New, N->getOperand(1), N->getOperand(2)));
22713       return SDValue();
22714     }
22715   }
22716
22717   return SDValue();
22718 }
22719
22720 // Check whether a boolean test is testing a boolean value generated by
22721 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22722 // code.
22723 //
22724 // Simplify the following patterns:
22725 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22726 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22727 // to (Op EFLAGS Cond)
22728 //
22729 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22730 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22731 // to (Op EFLAGS !Cond)
22732 //
22733 // where Op could be BRCOND or CMOV.
22734 //
22735 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22736   // Quit if not CMP and SUB with its value result used.
22737   if (Cmp.getOpcode() != X86ISD::CMP &&
22738       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22739       return SDValue();
22740
22741   // Quit if not used as a boolean value.
22742   if (CC != X86::COND_E && CC != X86::COND_NE)
22743     return SDValue();
22744
22745   // Check CMP operands. One of them should be 0 or 1 and the other should be
22746   // an SetCC or extended from it.
22747   SDValue Op1 = Cmp.getOperand(0);
22748   SDValue Op2 = Cmp.getOperand(1);
22749
22750   SDValue SetCC;
22751   const ConstantSDNode* C = nullptr;
22752   bool needOppositeCond = (CC == X86::COND_E);
22753   bool checkAgainstTrue = false; // Is it a comparison against 1?
22754
22755   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22756     SetCC = Op2;
22757   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22758     SetCC = Op1;
22759   else // Quit if all operands are not constants.
22760     return SDValue();
22761
22762   if (C->getZExtValue() == 1) {
22763     needOppositeCond = !needOppositeCond;
22764     checkAgainstTrue = true;
22765   } else if (C->getZExtValue() != 0)
22766     // Quit if the constant is neither 0 or 1.
22767     return SDValue();
22768
22769   bool truncatedToBoolWithAnd = false;
22770   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22771   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22772          SetCC.getOpcode() == ISD::TRUNCATE ||
22773          SetCC.getOpcode() == ISD::AND) {
22774     if (SetCC.getOpcode() == ISD::AND) {
22775       int OpIdx = -1;
22776       ConstantSDNode *CS;
22777       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22778           CS->getZExtValue() == 1)
22779         OpIdx = 1;
22780       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22781           CS->getZExtValue() == 1)
22782         OpIdx = 0;
22783       if (OpIdx == -1)
22784         break;
22785       SetCC = SetCC.getOperand(OpIdx);
22786       truncatedToBoolWithAnd = true;
22787     } else
22788       SetCC = SetCC.getOperand(0);
22789   }
22790
22791   switch (SetCC.getOpcode()) {
22792   case X86ISD::SETCC_CARRY:
22793     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22794     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22795     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22796     // truncated to i1 using 'and'.
22797     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22798       break;
22799     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22800            "Invalid use of SETCC_CARRY!");
22801     // FALL THROUGH
22802   case X86ISD::SETCC:
22803     // Set the condition code or opposite one if necessary.
22804     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22805     if (needOppositeCond)
22806       CC = X86::GetOppositeBranchCondition(CC);
22807     return SetCC.getOperand(1);
22808   case X86ISD::CMOV: {
22809     // Check whether false/true value has canonical one, i.e. 0 or 1.
22810     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22811     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22812     // Quit if true value is not a constant.
22813     if (!TVal)
22814       return SDValue();
22815     // Quit if false value is not a constant.
22816     if (!FVal) {
22817       SDValue Op = SetCC.getOperand(0);
22818       // Skip 'zext' or 'trunc' node.
22819       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22820           Op.getOpcode() == ISD::TRUNCATE)
22821         Op = Op.getOperand(0);
22822       // A special case for rdrand/rdseed, where 0 is set if false cond is
22823       // found.
22824       if ((Op.getOpcode() != X86ISD::RDRAND &&
22825            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22826         return SDValue();
22827     }
22828     // Quit if false value is not the constant 0 or 1.
22829     bool FValIsFalse = true;
22830     if (FVal && FVal->getZExtValue() != 0) {
22831       if (FVal->getZExtValue() != 1)
22832         return SDValue();
22833       // If FVal is 1, opposite cond is needed.
22834       needOppositeCond = !needOppositeCond;
22835       FValIsFalse = false;
22836     }
22837     // Quit if TVal is not the constant opposite of FVal.
22838     if (FValIsFalse && TVal->getZExtValue() != 1)
22839       return SDValue();
22840     if (!FValIsFalse && TVal->getZExtValue() != 0)
22841       return SDValue();
22842     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22843     if (needOppositeCond)
22844       CC = X86::GetOppositeBranchCondition(CC);
22845     return SetCC.getOperand(3);
22846   }
22847   }
22848
22849   return SDValue();
22850 }
22851
22852 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22853 /// Match:
22854 ///   (X86or (X86setcc) (X86setcc))
22855 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22856 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22857                                            X86::CondCode &CC1, SDValue &Flags,
22858                                            bool &isAnd) {
22859   if (Cond->getOpcode() == X86ISD::CMP) {
22860     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22861     if (!CondOp1C || !CondOp1C->isNullValue())
22862       return false;
22863
22864     Cond = Cond->getOperand(0);
22865   }
22866
22867   isAnd = false;
22868
22869   SDValue SetCC0, SetCC1;
22870   switch (Cond->getOpcode()) {
22871   default: return false;
22872   case ISD::AND:
22873   case X86ISD::AND:
22874     isAnd = true;
22875     // fallthru
22876   case ISD::OR:
22877   case X86ISD::OR:
22878     SetCC0 = Cond->getOperand(0);
22879     SetCC1 = Cond->getOperand(1);
22880     break;
22881   };
22882
22883   // Make sure we have SETCC nodes, using the same flags value.
22884   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22885       SetCC1.getOpcode() != X86ISD::SETCC ||
22886       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22887     return false;
22888
22889   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22890   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22891   Flags = SetCC0->getOperand(1);
22892   return true;
22893 }
22894
22895 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22896 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22897                                   TargetLowering::DAGCombinerInfo &DCI,
22898                                   const X86Subtarget *Subtarget) {
22899   SDLoc DL(N);
22900
22901   // If the flag operand isn't dead, don't touch this CMOV.
22902   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22903     return SDValue();
22904
22905   SDValue FalseOp = N->getOperand(0);
22906   SDValue TrueOp = N->getOperand(1);
22907   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22908   SDValue Cond = N->getOperand(3);
22909
22910   if (CC == X86::COND_E || CC == X86::COND_NE) {
22911     switch (Cond.getOpcode()) {
22912     default: break;
22913     case X86ISD::BSR:
22914     case X86ISD::BSF:
22915       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22916       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22917         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22918     }
22919   }
22920
22921   SDValue Flags;
22922
22923   Flags = checkBoolTestSetCCCombine(Cond, CC);
22924   if (Flags.getNode() &&
22925       // Extra check as FCMOV only supports a subset of X86 cond.
22926       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22927     SDValue Ops[] = { FalseOp, TrueOp,
22928                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22929     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22930   }
22931
22932   // If this is a select between two integer constants, try to do some
22933   // optimizations.  Note that the operands are ordered the opposite of SELECT
22934   // operands.
22935   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22936     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22937       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22938       // larger than FalseC (the false value).
22939       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22940         CC = X86::GetOppositeBranchCondition(CC);
22941         std::swap(TrueC, FalseC);
22942         std::swap(TrueOp, FalseOp);
22943       }
22944
22945       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22946       // This is efficient for any integer data type (including i8/i16) and
22947       // shift amount.
22948       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22949         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22950                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22951
22952         // Zero extend the condition if needed.
22953         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22954
22955         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22956         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22957                            DAG.getConstant(ShAmt, DL, MVT::i8));
22958         if (N->getNumValues() == 2)  // Dead flag value?
22959           return DCI.CombineTo(N, Cond, SDValue());
22960         return Cond;
22961       }
22962
22963       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22964       // for any integer data type, including i8/i16.
22965       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22966         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22967                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22968
22969         // Zero extend the condition if needed.
22970         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22971                            FalseC->getValueType(0), Cond);
22972         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22973                            SDValue(FalseC, 0));
22974
22975         if (N->getNumValues() == 2)  // Dead flag value?
22976           return DCI.CombineTo(N, Cond, SDValue());
22977         return Cond;
22978       }
22979
22980       // Optimize cases that will turn into an LEA instruction.  This requires
22981       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22982       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22983         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22984         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22985
22986         bool isFastMultiplier = false;
22987         if (Diff < 10) {
22988           switch ((unsigned char)Diff) {
22989           default: break;
22990           case 1:  // result = add base, cond
22991           case 2:  // result = lea base(    , cond*2)
22992           case 3:  // result = lea base(cond, cond*2)
22993           case 4:  // result = lea base(    , cond*4)
22994           case 5:  // result = lea base(cond, cond*4)
22995           case 8:  // result = lea base(    , cond*8)
22996           case 9:  // result = lea base(cond, cond*8)
22997             isFastMultiplier = true;
22998             break;
22999           }
23000         }
23001
23002         if (isFastMultiplier) {
23003           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23004           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23005                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23006           // Zero extend the condition if needed.
23007           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23008                              Cond);
23009           // Scale the condition by the difference.
23010           if (Diff != 1)
23011             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23012                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23013
23014           // Add the base if non-zero.
23015           if (FalseC->getAPIntValue() != 0)
23016             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23017                                SDValue(FalseC, 0));
23018           if (N->getNumValues() == 2)  // Dead flag value?
23019             return DCI.CombineTo(N, Cond, SDValue());
23020           return Cond;
23021         }
23022       }
23023     }
23024   }
23025
23026   // Handle these cases:
23027   //   (select (x != c), e, c) -> select (x != c), e, x),
23028   //   (select (x == c), c, e) -> select (x == c), x, e)
23029   // where the c is an integer constant, and the "select" is the combination
23030   // of CMOV and CMP.
23031   //
23032   // The rationale for this change is that the conditional-move from a constant
23033   // needs two instructions, however, conditional-move from a register needs
23034   // only one instruction.
23035   //
23036   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23037   //  some instruction-combining opportunities. This opt needs to be
23038   //  postponed as late as possible.
23039   //
23040   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23041     // the DCI.xxxx conditions are provided to postpone the optimization as
23042     // late as possible.
23043
23044     ConstantSDNode *CmpAgainst = nullptr;
23045     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23046         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23047         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23048
23049       if (CC == X86::COND_NE &&
23050           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23051         CC = X86::GetOppositeBranchCondition(CC);
23052         std::swap(TrueOp, FalseOp);
23053       }
23054
23055       if (CC == X86::COND_E &&
23056           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23057         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23058                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23059         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23060       }
23061     }
23062   }
23063
23064   // Fold and/or of setcc's to double CMOV:
23065   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23066   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23067   //
23068   // This combine lets us generate:
23069   //   cmovcc1 (jcc1 if we don't have CMOV)
23070   //   cmovcc2 (same)
23071   // instead of:
23072   //   setcc1
23073   //   setcc2
23074   //   and/or
23075   //   cmovne (jne if we don't have CMOV)
23076   // When we can't use the CMOV instruction, it might increase branch
23077   // mispredicts.
23078   // When we can use CMOV, or when there is no mispredict, this improves
23079   // throughput and reduces register pressure.
23080   //
23081   if (CC == X86::COND_NE) {
23082     SDValue Flags;
23083     X86::CondCode CC0, CC1;
23084     bool isAndSetCC;
23085     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23086       if (isAndSetCC) {
23087         std::swap(FalseOp, TrueOp);
23088         CC0 = X86::GetOppositeBranchCondition(CC0);
23089         CC1 = X86::GetOppositeBranchCondition(CC1);
23090       }
23091
23092       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23093         Flags};
23094       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23095       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23096       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23097       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23098       return CMOV;
23099     }
23100   }
23101
23102   return SDValue();
23103 }
23104
23105 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23106                                                 const X86Subtarget *Subtarget) {
23107   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23108   switch (IntNo) {
23109   default: return SDValue();
23110   // SSE/AVX/AVX2 blend intrinsics.
23111   case Intrinsic::x86_avx2_pblendvb:
23112     // Don't try to simplify this intrinsic if we don't have AVX2.
23113     if (!Subtarget->hasAVX2())
23114       return SDValue();
23115     // FALL-THROUGH
23116   case Intrinsic::x86_avx_blendv_pd_256:
23117   case Intrinsic::x86_avx_blendv_ps_256:
23118     // Don't try to simplify this intrinsic if we don't have AVX.
23119     if (!Subtarget->hasAVX())
23120       return SDValue();
23121     // FALL-THROUGH
23122   case Intrinsic::x86_sse41_blendvps:
23123   case Intrinsic::x86_sse41_blendvpd:
23124   case Intrinsic::x86_sse41_pblendvb: {
23125     SDValue Op0 = N->getOperand(1);
23126     SDValue Op1 = N->getOperand(2);
23127     SDValue Mask = N->getOperand(3);
23128
23129     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23130     if (!Subtarget->hasSSE41())
23131       return SDValue();
23132
23133     // fold (blend A, A, Mask) -> A
23134     if (Op0 == Op1)
23135       return Op0;
23136     // fold (blend A, B, allZeros) -> A
23137     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23138       return Op0;
23139     // fold (blend A, B, allOnes) -> B
23140     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23141       return Op1;
23142
23143     // Simplify the case where the mask is a constant i32 value.
23144     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23145       if (C->isNullValue())
23146         return Op0;
23147       if (C->isAllOnesValue())
23148         return Op1;
23149     }
23150
23151     return SDValue();
23152   }
23153
23154   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23155   case Intrinsic::x86_sse2_psrai_w:
23156   case Intrinsic::x86_sse2_psrai_d:
23157   case Intrinsic::x86_avx2_psrai_w:
23158   case Intrinsic::x86_avx2_psrai_d:
23159   case Intrinsic::x86_sse2_psra_w:
23160   case Intrinsic::x86_sse2_psra_d:
23161   case Intrinsic::x86_avx2_psra_w:
23162   case Intrinsic::x86_avx2_psra_d: {
23163     SDValue Op0 = N->getOperand(1);
23164     SDValue Op1 = N->getOperand(2);
23165     EVT VT = Op0.getValueType();
23166     assert(VT.isVector() && "Expected a vector type!");
23167
23168     if (isa<BuildVectorSDNode>(Op1))
23169       Op1 = Op1.getOperand(0);
23170
23171     if (!isa<ConstantSDNode>(Op1))
23172       return SDValue();
23173
23174     EVT SVT = VT.getVectorElementType();
23175     unsigned SVTBits = SVT.getSizeInBits();
23176
23177     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23178     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23179     uint64_t ShAmt = C.getZExtValue();
23180
23181     // Don't try to convert this shift into a ISD::SRA if the shift
23182     // count is bigger than or equal to the element size.
23183     if (ShAmt >= SVTBits)
23184       return SDValue();
23185
23186     // Trivial case: if the shift count is zero, then fold this
23187     // into the first operand.
23188     if (ShAmt == 0)
23189       return Op0;
23190
23191     // Replace this packed shift intrinsic with a target independent
23192     // shift dag node.
23193     SDLoc DL(N);
23194     SDValue Splat = DAG.getConstant(C, DL, VT);
23195     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23196   }
23197   }
23198 }
23199
23200 /// PerformMulCombine - Optimize a single multiply with constant into two
23201 /// in order to implement it with two cheaper instructions, e.g.
23202 /// LEA + SHL, LEA + LEA.
23203 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23204                                  TargetLowering::DAGCombinerInfo &DCI) {
23205   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23206     return SDValue();
23207
23208   EVT VT = N->getValueType(0);
23209   if (VT != MVT::i64 && VT != MVT::i32)
23210     return SDValue();
23211
23212   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23213   if (!C)
23214     return SDValue();
23215   uint64_t MulAmt = C->getZExtValue();
23216   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23217     return SDValue();
23218
23219   uint64_t MulAmt1 = 0;
23220   uint64_t MulAmt2 = 0;
23221   if ((MulAmt % 9) == 0) {
23222     MulAmt1 = 9;
23223     MulAmt2 = MulAmt / 9;
23224   } else if ((MulAmt % 5) == 0) {
23225     MulAmt1 = 5;
23226     MulAmt2 = MulAmt / 5;
23227   } else if ((MulAmt % 3) == 0) {
23228     MulAmt1 = 3;
23229     MulAmt2 = MulAmt / 3;
23230   }
23231   if (MulAmt2 &&
23232       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23233     SDLoc DL(N);
23234
23235     if (isPowerOf2_64(MulAmt2) &&
23236         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23237       // If second multiplifer is pow2, issue it first. We want the multiply by
23238       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23239       // is an add.
23240       std::swap(MulAmt1, MulAmt2);
23241
23242     SDValue NewMul;
23243     if (isPowerOf2_64(MulAmt1))
23244       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23245                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23246     else
23247       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23248                            DAG.getConstant(MulAmt1, DL, VT));
23249
23250     if (isPowerOf2_64(MulAmt2))
23251       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23252                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23253     else
23254       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23255                            DAG.getConstant(MulAmt2, DL, VT));
23256
23257     // Do not add new nodes to DAG combiner worklist.
23258     DCI.CombineTo(N, NewMul, false);
23259   }
23260   return SDValue();
23261 }
23262
23263 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23264   SDValue N0 = N->getOperand(0);
23265   SDValue N1 = N->getOperand(1);
23266   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23267   EVT VT = N0.getValueType();
23268
23269   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23270   // since the result of setcc_c is all zero's or all ones.
23271   if (VT.isInteger() && !VT.isVector() &&
23272       N1C && N0.getOpcode() == ISD::AND &&
23273       N0.getOperand(1).getOpcode() == ISD::Constant) {
23274     SDValue N00 = N0.getOperand(0);
23275     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23276         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23277           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23278          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23279       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23280       APInt ShAmt = N1C->getAPIntValue();
23281       Mask = Mask.shl(ShAmt);
23282       if (Mask != 0) {
23283         SDLoc DL(N);
23284         return DAG.getNode(ISD::AND, DL, VT,
23285                            N00, DAG.getConstant(Mask, DL, VT));
23286       }
23287     }
23288   }
23289
23290   // Hardware support for vector shifts is sparse which makes us scalarize the
23291   // vector operations in many cases. Also, on sandybridge ADD is faster than
23292   // shl.
23293   // (shl V, 1) -> add V,V
23294   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23295     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23296       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23297       // We shift all of the values by one. In many cases we do not have
23298       // hardware support for this operation. This is better expressed as an ADD
23299       // of two values.
23300       if (N1SplatC->getAPIntValue() == 1)
23301         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23302     }
23303
23304   return SDValue();
23305 }
23306
23307 /// \brief Returns a vector of 0s if the node in input is a vector logical
23308 /// shift by a constant amount which is known to be bigger than or equal
23309 /// to the vector element size in bits.
23310 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23311                                       const X86Subtarget *Subtarget) {
23312   EVT VT = N->getValueType(0);
23313
23314   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23315       (!Subtarget->hasInt256() ||
23316        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23317     return SDValue();
23318
23319   SDValue Amt = N->getOperand(1);
23320   SDLoc DL(N);
23321   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23322     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23323       APInt ShiftAmt = AmtSplat->getAPIntValue();
23324       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23325
23326       // SSE2/AVX2 logical shifts always return a vector of 0s
23327       // if the shift amount is bigger than or equal to
23328       // the element size. The constant shift amount will be
23329       // encoded as a 8-bit immediate.
23330       if (ShiftAmt.trunc(8).uge(MaxAmount))
23331         return getZeroVector(VT, Subtarget, DAG, DL);
23332     }
23333
23334   return SDValue();
23335 }
23336
23337 /// PerformShiftCombine - Combine shifts.
23338 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23339                                    TargetLowering::DAGCombinerInfo &DCI,
23340                                    const X86Subtarget *Subtarget) {
23341   if (N->getOpcode() == ISD::SHL)
23342     if (SDValue V = PerformSHLCombine(N, DAG))
23343       return V;
23344
23345   // Try to fold this logical shift into a zero vector.
23346   if (N->getOpcode() != ISD::SRA)
23347     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23348       return V;
23349
23350   return SDValue();
23351 }
23352
23353 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23354 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23355 // and friends.  Likewise for OR -> CMPNEQSS.
23356 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23357                             TargetLowering::DAGCombinerInfo &DCI,
23358                             const X86Subtarget *Subtarget) {
23359   unsigned opcode;
23360
23361   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23362   // we're requiring SSE2 for both.
23363   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23364     SDValue N0 = N->getOperand(0);
23365     SDValue N1 = N->getOperand(1);
23366     SDValue CMP0 = N0->getOperand(1);
23367     SDValue CMP1 = N1->getOperand(1);
23368     SDLoc DL(N);
23369
23370     // The SETCCs should both refer to the same CMP.
23371     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23372       return SDValue();
23373
23374     SDValue CMP00 = CMP0->getOperand(0);
23375     SDValue CMP01 = CMP0->getOperand(1);
23376     EVT     VT    = CMP00.getValueType();
23377
23378     if (VT == MVT::f32 || VT == MVT::f64) {
23379       bool ExpectingFlags = false;
23380       // Check for any users that want flags:
23381       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23382            !ExpectingFlags && UI != UE; ++UI)
23383         switch (UI->getOpcode()) {
23384         default:
23385         case ISD::BR_CC:
23386         case ISD::BRCOND:
23387         case ISD::SELECT:
23388           ExpectingFlags = true;
23389           break;
23390         case ISD::CopyToReg:
23391         case ISD::SIGN_EXTEND:
23392         case ISD::ZERO_EXTEND:
23393         case ISD::ANY_EXTEND:
23394           break;
23395         }
23396
23397       if (!ExpectingFlags) {
23398         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23399         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23400
23401         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23402           X86::CondCode tmp = cc0;
23403           cc0 = cc1;
23404           cc1 = tmp;
23405         }
23406
23407         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23408             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23409           // FIXME: need symbolic constants for these magic numbers.
23410           // See X86ATTInstPrinter.cpp:printSSECC().
23411           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23412           if (Subtarget->hasAVX512()) {
23413             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23414                                          CMP01,
23415                                          DAG.getConstant(x86cc, DL, MVT::i8));
23416             if (N->getValueType(0) != MVT::i1)
23417               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23418                                  FSetCC);
23419             return FSetCC;
23420           }
23421           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23422                                               CMP00.getValueType(), CMP00, CMP01,
23423                                               DAG.getConstant(x86cc, DL,
23424                                                               MVT::i8));
23425
23426           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23427           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23428
23429           if (is64BitFP && !Subtarget->is64Bit()) {
23430             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23431             // 64-bit integer, since that's not a legal type. Since
23432             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23433             // bits, but can do this little dance to extract the lowest 32 bits
23434             // and work with those going forward.
23435             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23436                                            OnesOrZeroesF);
23437             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23438             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23439                                         Vector32, DAG.getIntPtrConstant(0, DL));
23440             IntVT = MVT::i32;
23441           }
23442
23443           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23444           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23445                                       DAG.getConstant(1, DL, IntVT));
23446           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23447                                               ANDed);
23448           return OneBitOfTruth;
23449         }
23450       }
23451     }
23452   }
23453   return SDValue();
23454 }
23455
23456 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23457 /// so it can be folded inside ANDNP.
23458 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23459   EVT VT = N->getValueType(0);
23460
23461   // Match direct AllOnes for 128 and 256-bit vectors
23462   if (ISD::isBuildVectorAllOnes(N))
23463     return true;
23464
23465   // Look through a bit convert.
23466   if (N->getOpcode() == ISD::BITCAST)
23467     N = N->getOperand(0).getNode();
23468
23469   // Sometimes the operand may come from a insert_subvector building a 256-bit
23470   // allones vector
23471   if (VT.is256BitVector() &&
23472       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23473     SDValue V1 = N->getOperand(0);
23474     SDValue V2 = N->getOperand(1);
23475
23476     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23477         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23478         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23479         ISD::isBuildVectorAllOnes(V2.getNode()))
23480       return true;
23481   }
23482
23483   return false;
23484 }
23485
23486 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23487 // register. In most cases we actually compare or select YMM-sized registers
23488 // and mixing the two types creates horrible code. This method optimizes
23489 // some of the transition sequences.
23490 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23491                                  TargetLowering::DAGCombinerInfo &DCI,
23492                                  const X86Subtarget *Subtarget) {
23493   EVT VT = N->getValueType(0);
23494   if (!VT.is256BitVector())
23495     return SDValue();
23496
23497   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23498           N->getOpcode() == ISD::ZERO_EXTEND ||
23499           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23500
23501   SDValue Narrow = N->getOperand(0);
23502   EVT NarrowVT = Narrow->getValueType(0);
23503   if (!NarrowVT.is128BitVector())
23504     return SDValue();
23505
23506   if (Narrow->getOpcode() != ISD::XOR &&
23507       Narrow->getOpcode() != ISD::AND &&
23508       Narrow->getOpcode() != ISD::OR)
23509     return SDValue();
23510
23511   SDValue N0  = Narrow->getOperand(0);
23512   SDValue N1  = Narrow->getOperand(1);
23513   SDLoc DL(Narrow);
23514
23515   // The Left side has to be a trunc.
23516   if (N0.getOpcode() != ISD::TRUNCATE)
23517     return SDValue();
23518
23519   // The type of the truncated inputs.
23520   EVT WideVT = N0->getOperand(0)->getValueType(0);
23521   if (WideVT != VT)
23522     return SDValue();
23523
23524   // The right side has to be a 'trunc' or a constant vector.
23525   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23526   ConstantSDNode *RHSConstSplat = nullptr;
23527   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23528     RHSConstSplat = RHSBV->getConstantSplatNode();
23529   if (!RHSTrunc && !RHSConstSplat)
23530     return SDValue();
23531
23532   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23533
23534   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23535     return SDValue();
23536
23537   // Set N0 and N1 to hold the inputs to the new wide operation.
23538   N0 = N0->getOperand(0);
23539   if (RHSConstSplat) {
23540     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23541                      SDValue(RHSConstSplat, 0));
23542     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23543     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23544   } else if (RHSTrunc) {
23545     N1 = N1->getOperand(0);
23546   }
23547
23548   // Generate the wide operation.
23549   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23550   unsigned Opcode = N->getOpcode();
23551   switch (Opcode) {
23552   case ISD::ANY_EXTEND:
23553     return Op;
23554   case ISD::ZERO_EXTEND: {
23555     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23556     APInt Mask = APInt::getAllOnesValue(InBits);
23557     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23558     return DAG.getNode(ISD::AND, DL, VT,
23559                        Op, DAG.getConstant(Mask, DL, VT));
23560   }
23561   case ISD::SIGN_EXTEND:
23562     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23563                        Op, DAG.getValueType(NarrowVT));
23564   default:
23565     llvm_unreachable("Unexpected opcode");
23566   }
23567 }
23568
23569 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23570                                  TargetLowering::DAGCombinerInfo &DCI,
23571                                  const X86Subtarget *Subtarget) {
23572   SDValue N0 = N->getOperand(0);
23573   SDValue N1 = N->getOperand(1);
23574   SDLoc DL(N);
23575
23576   // A vector zext_in_reg may be represented as a shuffle,
23577   // feeding into a bitcast (this represents anyext) feeding into
23578   // an and with a mask.
23579   // We'd like to try to combine that into a shuffle with zero
23580   // plus a bitcast, removing the and.
23581   if (N0.getOpcode() != ISD::BITCAST ||
23582       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23583     return SDValue();
23584
23585   // The other side of the AND should be a splat of 2^C, where C
23586   // is the number of bits in the source type.
23587   if (N1.getOpcode() == ISD::BITCAST)
23588     N1 = N1.getOperand(0);
23589   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23590     return SDValue();
23591   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23592
23593   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23594   EVT SrcType = Shuffle->getValueType(0);
23595
23596   // We expect a single-source shuffle
23597   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23598     return SDValue();
23599
23600   unsigned SrcSize = SrcType.getScalarSizeInBits();
23601
23602   APInt SplatValue, SplatUndef;
23603   unsigned SplatBitSize;
23604   bool HasAnyUndefs;
23605   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23606                                 SplatBitSize, HasAnyUndefs))
23607     return SDValue();
23608
23609   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23610   // Make sure the splat matches the mask we expect
23611   if (SplatBitSize > ResSize ||
23612       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23613     return SDValue();
23614
23615   // Make sure the input and output size make sense
23616   if (SrcSize >= ResSize || ResSize % SrcSize)
23617     return SDValue();
23618
23619   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23620   // The number of u's between each two values depends on the ratio between
23621   // the source and dest type.
23622   unsigned ZextRatio = ResSize / SrcSize;
23623   bool IsZext = true;
23624   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23625     if (i % ZextRatio) {
23626       if (Shuffle->getMaskElt(i) > 0) {
23627         // Expected undef
23628         IsZext = false;
23629         break;
23630       }
23631     } else {
23632       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23633         // Expected element number
23634         IsZext = false;
23635         break;
23636       }
23637     }
23638   }
23639
23640   if (!IsZext)
23641     return SDValue();
23642
23643   // Ok, perform the transformation - replace the shuffle with
23644   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23645   // (instead of undef) where the k elements come from the zero vector.
23646   SmallVector<int, 8> Mask;
23647   unsigned NumElems = SrcType.getVectorNumElements();
23648   for (unsigned i = 0; i < NumElems; ++i)
23649     if (i % ZextRatio)
23650       Mask.push_back(NumElems);
23651     else
23652       Mask.push_back(i / ZextRatio);
23653
23654   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23655     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23656   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23657 }
23658
23659 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23660                                  TargetLowering::DAGCombinerInfo &DCI,
23661                                  const X86Subtarget *Subtarget) {
23662   if (DCI.isBeforeLegalizeOps())
23663     return SDValue();
23664
23665   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23666     return Zext;
23667
23668   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23669     return R;
23670
23671   EVT VT = N->getValueType(0);
23672   SDValue N0 = N->getOperand(0);
23673   SDValue N1 = N->getOperand(1);
23674   SDLoc DL(N);
23675
23676   // Create BEXTR instructions
23677   // BEXTR is ((X >> imm) & (2**size-1))
23678   if (VT == MVT::i32 || VT == MVT::i64) {
23679     // Check for BEXTR.
23680     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23681         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23682       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23683       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23684       if (MaskNode && ShiftNode) {
23685         uint64_t Mask = MaskNode->getZExtValue();
23686         uint64_t Shift = ShiftNode->getZExtValue();
23687         if (isMask_64(Mask)) {
23688           uint64_t MaskSize = countPopulation(Mask);
23689           if (Shift + MaskSize <= VT.getSizeInBits())
23690             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23691                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23692                                                VT));
23693         }
23694       }
23695     } // BEXTR
23696
23697     return SDValue();
23698   }
23699
23700   // Want to form ANDNP nodes:
23701   // 1) In the hopes of then easily combining them with OR and AND nodes
23702   //    to form PBLEND/PSIGN.
23703   // 2) To match ANDN packed intrinsics
23704   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23705     return SDValue();
23706
23707   // Check LHS for vnot
23708   if (N0.getOpcode() == ISD::XOR &&
23709       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23710       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23711     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23712
23713   // Check RHS for vnot
23714   if (N1.getOpcode() == ISD::XOR &&
23715       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23716       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23717     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23718
23719   return SDValue();
23720 }
23721
23722 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23723                                 TargetLowering::DAGCombinerInfo &DCI,
23724                                 const X86Subtarget *Subtarget) {
23725   if (DCI.isBeforeLegalizeOps())
23726     return SDValue();
23727
23728   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23729     return R;
23730
23731   SDValue N0 = N->getOperand(0);
23732   SDValue N1 = N->getOperand(1);
23733   EVT VT = N->getValueType(0);
23734
23735   // look for psign/blend
23736   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23737     if (!Subtarget->hasSSSE3() ||
23738         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23739       return SDValue();
23740
23741     // Canonicalize pandn to RHS
23742     if (N0.getOpcode() == X86ISD::ANDNP)
23743       std::swap(N0, N1);
23744     // or (and (m, y), (pandn m, x))
23745     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23746       SDValue Mask = N1.getOperand(0);
23747       SDValue X    = N1.getOperand(1);
23748       SDValue Y;
23749       if (N0.getOperand(0) == Mask)
23750         Y = N0.getOperand(1);
23751       if (N0.getOperand(1) == Mask)
23752         Y = N0.getOperand(0);
23753
23754       // Check to see if the mask appeared in both the AND and ANDNP and
23755       if (!Y.getNode())
23756         return SDValue();
23757
23758       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23759       // Look through mask bitcast.
23760       if (Mask.getOpcode() == ISD::BITCAST)
23761         Mask = Mask.getOperand(0);
23762       if (X.getOpcode() == ISD::BITCAST)
23763         X = X.getOperand(0);
23764       if (Y.getOpcode() == ISD::BITCAST)
23765         Y = Y.getOperand(0);
23766
23767       EVT MaskVT = Mask.getValueType();
23768
23769       // Validate that the Mask operand is a vector sra node.
23770       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23771       // there is no psrai.b
23772       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23773       unsigned SraAmt = ~0;
23774       if (Mask.getOpcode() == ISD::SRA) {
23775         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23776           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23777             SraAmt = AmtConst->getZExtValue();
23778       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23779         SDValue SraC = Mask.getOperand(1);
23780         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23781       }
23782       if ((SraAmt + 1) != EltBits)
23783         return SDValue();
23784
23785       SDLoc DL(N);
23786
23787       // Now we know we at least have a plendvb with the mask val.  See if
23788       // we can form a psignb/w/d.
23789       // psign = x.type == y.type == mask.type && y = sub(0, x);
23790       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23791           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23792           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23793         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23794                "Unsupported VT for PSIGN");
23795         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23796         return DAG.getBitcast(VT, Mask);
23797       }
23798       // PBLENDVB only available on SSE 4.1
23799       if (!Subtarget->hasSSE41())
23800         return SDValue();
23801
23802       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23803
23804       X = DAG.getBitcast(BlendVT, X);
23805       Y = DAG.getBitcast(BlendVT, Y);
23806       Mask = DAG.getBitcast(BlendVT, Mask);
23807       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23808       return DAG.getBitcast(VT, Mask);
23809     }
23810   }
23811
23812   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23813     return SDValue();
23814
23815   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23816   MachineFunction &MF = DAG.getMachineFunction();
23817   bool OptForSize =
23818       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23819
23820   // SHLD/SHRD instructions have lower register pressure, but on some
23821   // platforms they have higher latency than the equivalent
23822   // series of shifts/or that would otherwise be generated.
23823   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23824   // have higher latencies and we are not optimizing for size.
23825   if (!OptForSize && Subtarget->isSHLDSlow())
23826     return SDValue();
23827
23828   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23829     std::swap(N0, N1);
23830   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23831     return SDValue();
23832   if (!N0.hasOneUse() || !N1.hasOneUse())
23833     return SDValue();
23834
23835   SDValue ShAmt0 = N0.getOperand(1);
23836   if (ShAmt0.getValueType() != MVT::i8)
23837     return SDValue();
23838   SDValue ShAmt1 = N1.getOperand(1);
23839   if (ShAmt1.getValueType() != MVT::i8)
23840     return SDValue();
23841   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23842     ShAmt0 = ShAmt0.getOperand(0);
23843   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23844     ShAmt1 = ShAmt1.getOperand(0);
23845
23846   SDLoc DL(N);
23847   unsigned Opc = X86ISD::SHLD;
23848   SDValue Op0 = N0.getOperand(0);
23849   SDValue Op1 = N1.getOperand(0);
23850   if (ShAmt0.getOpcode() == ISD::SUB) {
23851     Opc = X86ISD::SHRD;
23852     std::swap(Op0, Op1);
23853     std::swap(ShAmt0, ShAmt1);
23854   }
23855
23856   unsigned Bits = VT.getSizeInBits();
23857   if (ShAmt1.getOpcode() == ISD::SUB) {
23858     SDValue Sum = ShAmt1.getOperand(0);
23859     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23860       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23861       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23862         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23863       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23864         return DAG.getNode(Opc, DL, VT,
23865                            Op0, Op1,
23866                            DAG.getNode(ISD::TRUNCATE, DL,
23867                                        MVT::i8, ShAmt0));
23868     }
23869   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23870     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23871     if (ShAmt0C &&
23872         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23873       return DAG.getNode(Opc, DL, VT,
23874                          N0.getOperand(0), N1.getOperand(0),
23875                          DAG.getNode(ISD::TRUNCATE, DL,
23876                                        MVT::i8, ShAmt0));
23877   }
23878
23879   return SDValue();
23880 }
23881
23882 // Generate NEG and CMOV for integer abs.
23883 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23884   EVT VT = N->getValueType(0);
23885
23886   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23887   // 8-bit integer abs to NEG and CMOV.
23888   if (VT.isInteger() && VT.getSizeInBits() == 8)
23889     return SDValue();
23890
23891   SDValue N0 = N->getOperand(0);
23892   SDValue N1 = N->getOperand(1);
23893   SDLoc DL(N);
23894
23895   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23896   // and change it to SUB and CMOV.
23897   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23898       N0.getOpcode() == ISD::ADD &&
23899       N0.getOperand(1) == N1 &&
23900       N1.getOpcode() == ISD::SRA &&
23901       N1.getOperand(0) == N0.getOperand(0))
23902     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23903       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23904         // Generate SUB & CMOV.
23905         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23906                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23907
23908         SDValue Ops[] = { N0.getOperand(0), Neg,
23909                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23910                           SDValue(Neg.getNode(), 1) };
23911         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23912       }
23913   return SDValue();
23914 }
23915
23916 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23917 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23918                                  TargetLowering::DAGCombinerInfo &DCI,
23919                                  const X86Subtarget *Subtarget) {
23920   if (DCI.isBeforeLegalizeOps())
23921     return SDValue();
23922
23923   if (Subtarget->hasCMov())
23924     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23925       return RV;
23926
23927   return SDValue();
23928 }
23929
23930 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23931 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23932                                   TargetLowering::DAGCombinerInfo &DCI,
23933                                   const X86Subtarget *Subtarget) {
23934   LoadSDNode *Ld = cast<LoadSDNode>(N);
23935   EVT RegVT = Ld->getValueType(0);
23936   EVT MemVT = Ld->getMemoryVT();
23937   SDLoc dl(Ld);
23938   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23939
23940   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23941   // into two 16-byte operations.
23942   ISD::LoadExtType Ext = Ld->getExtensionType();
23943   unsigned Alignment = Ld->getAlignment();
23944   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23945   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23946       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23947     unsigned NumElems = RegVT.getVectorNumElements();
23948     if (NumElems < 2)
23949       return SDValue();
23950
23951     SDValue Ptr = Ld->getBasePtr();
23952     SDValue Increment =
23953         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
23954
23955     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23956                                   NumElems/2);
23957     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23958                                 Ld->getPointerInfo(), Ld->isVolatile(),
23959                                 Ld->isNonTemporal(), Ld->isInvariant(),
23960                                 Alignment);
23961     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23962     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23963                                 Ld->getPointerInfo(), Ld->isVolatile(),
23964                                 Ld->isNonTemporal(), Ld->isInvariant(),
23965                                 std::min(16U, Alignment));
23966     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23967                              Load1.getValue(1),
23968                              Load2.getValue(1));
23969
23970     SDValue NewVec = DAG.getUNDEF(RegVT);
23971     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23972     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23973     return DCI.CombineTo(N, NewVec, TF, true);
23974   }
23975
23976   return SDValue();
23977 }
23978
23979 /// PerformMLOADCombine - Resolve extending loads
23980 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23981                                    TargetLowering::DAGCombinerInfo &DCI,
23982                                    const X86Subtarget *Subtarget) {
23983   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23984   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23985     return SDValue();
23986
23987   EVT VT = Mld->getValueType(0);
23988   unsigned NumElems = VT.getVectorNumElements();
23989   EVT LdVT = Mld->getMemoryVT();
23990   SDLoc dl(Mld);
23991
23992   assert(LdVT != VT && "Cannot extend to the same type");
23993   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23994   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23995   // From, To sizes and ElemCount must be pow of two
23996   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23997     "Unexpected size for extending masked load");
23998
23999   unsigned SizeRatio  = ToSz / FromSz;
24000   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24001
24002   // Create a type on which we perform the shuffle
24003   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24004           LdVT.getScalarType(), NumElems*SizeRatio);
24005   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24006
24007   // Convert Src0 value
24008   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24009   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24010     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24011     for (unsigned i = 0; i != NumElems; ++i)
24012       ShuffleVec[i] = i * SizeRatio;
24013
24014     // Can't shuffle using an illegal type.
24015     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24016             && "WideVecVT should be legal");
24017     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24018                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24019   }
24020   // Prepare the new mask
24021   SDValue NewMask;
24022   SDValue Mask = Mld->getMask();
24023   if (Mask.getValueType() == VT) {
24024     // Mask and original value have the same type
24025     NewMask = DAG.getBitcast(WideVecVT, Mask);
24026     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24027     for (unsigned i = 0; i != NumElems; ++i)
24028       ShuffleVec[i] = i * SizeRatio;
24029     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24030       ShuffleVec[i] = NumElems*SizeRatio;
24031     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24032                                    DAG.getConstant(0, dl, WideVecVT),
24033                                    &ShuffleVec[0]);
24034   }
24035   else {
24036     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24037     unsigned WidenNumElts = NumElems*SizeRatio;
24038     unsigned MaskNumElts = VT.getVectorNumElements();
24039     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24040                                      WidenNumElts);
24041
24042     unsigned NumConcat = WidenNumElts / MaskNumElts;
24043     SmallVector<SDValue, 16> Ops(NumConcat);
24044     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24045     Ops[0] = Mask;
24046     for (unsigned i = 1; i != NumConcat; ++i)
24047       Ops[i] = ZeroVal;
24048
24049     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24050   }
24051
24052   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24053                                      Mld->getBasePtr(), NewMask, WideSrc0,
24054                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24055                                      ISD::NON_EXTLOAD);
24056   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24057   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24058
24059 }
24060 /// PerformMSTORECombine - Resolve truncating stores
24061 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24062                                     const X86Subtarget *Subtarget) {
24063   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24064   if (!Mst->isTruncatingStore())
24065     return SDValue();
24066
24067   EVT VT = Mst->getValue().getValueType();
24068   unsigned NumElems = VT.getVectorNumElements();
24069   EVT StVT = Mst->getMemoryVT();
24070   SDLoc dl(Mst);
24071
24072   assert(StVT != VT && "Cannot truncate to the same type");
24073   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24074   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24075
24076   // From, To sizes and ElemCount must be pow of two
24077   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24078     "Unexpected size for truncating masked store");
24079   // We are going to use the original vector elt for storing.
24080   // Accumulated smaller vector elements must be a multiple of the store size.
24081   assert (((NumElems * FromSz) % ToSz) == 0 &&
24082           "Unexpected ratio for truncating masked store");
24083
24084   unsigned SizeRatio  = FromSz / ToSz;
24085   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24086
24087   // Create a type on which we perform the shuffle
24088   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24089           StVT.getScalarType(), NumElems*SizeRatio);
24090
24091   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24092
24093   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24094   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24095   for (unsigned i = 0; i != NumElems; ++i)
24096     ShuffleVec[i] = i * SizeRatio;
24097
24098   // Can't shuffle using an illegal type.
24099   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24100           && "WideVecVT should be legal");
24101
24102   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24103                                         DAG.getUNDEF(WideVecVT),
24104                                         &ShuffleVec[0]);
24105
24106   SDValue NewMask;
24107   SDValue Mask = Mst->getMask();
24108   if (Mask.getValueType() == VT) {
24109     // Mask and original value have the same type
24110     NewMask = DAG.getBitcast(WideVecVT, Mask);
24111     for (unsigned i = 0; i != NumElems; ++i)
24112       ShuffleVec[i] = i * SizeRatio;
24113     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24114       ShuffleVec[i] = NumElems*SizeRatio;
24115     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24116                                    DAG.getConstant(0, dl, WideVecVT),
24117                                    &ShuffleVec[0]);
24118   }
24119   else {
24120     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24121     unsigned WidenNumElts = NumElems*SizeRatio;
24122     unsigned MaskNumElts = VT.getVectorNumElements();
24123     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24124                                      WidenNumElts);
24125
24126     unsigned NumConcat = WidenNumElts / MaskNumElts;
24127     SmallVector<SDValue, 16> Ops(NumConcat);
24128     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24129     Ops[0] = Mask;
24130     for (unsigned i = 1; i != NumConcat; ++i)
24131       Ops[i] = ZeroVal;
24132
24133     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24134   }
24135
24136   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24137                             NewMask, StVT, Mst->getMemOperand(), false);
24138 }
24139 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24140 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24141                                    const X86Subtarget *Subtarget) {
24142   StoreSDNode *St = cast<StoreSDNode>(N);
24143   EVT VT = St->getValue().getValueType();
24144   EVT StVT = St->getMemoryVT();
24145   SDLoc dl(St);
24146   SDValue StoredVal = St->getOperand(1);
24147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24148
24149   // If we are saving a concatenation of two XMM registers and 32-byte stores
24150   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24151   unsigned Alignment = St->getAlignment();
24152   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24153   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24154       StVT == VT && !IsAligned) {
24155     unsigned NumElems = VT.getVectorNumElements();
24156     if (NumElems < 2)
24157       return SDValue();
24158
24159     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24160     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24161
24162     SDValue Stride =
24163         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24164     SDValue Ptr0 = St->getBasePtr();
24165     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24166
24167     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24168                                 St->getPointerInfo(), St->isVolatile(),
24169                                 St->isNonTemporal(), Alignment);
24170     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24171                                 St->getPointerInfo(), St->isVolatile(),
24172                                 St->isNonTemporal(),
24173                                 std::min(16U, Alignment));
24174     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24175   }
24176
24177   // Optimize trunc store (of multiple scalars) to shuffle and store.
24178   // First, pack all of the elements in one place. Next, store to memory
24179   // in fewer chunks.
24180   if (St->isTruncatingStore() && VT.isVector()) {
24181     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24182     unsigned NumElems = VT.getVectorNumElements();
24183     assert(StVT != VT && "Cannot truncate to the same type");
24184     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24185     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24186
24187     // From, To sizes and ElemCount must be pow of two
24188     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24189     // We are going to use the original vector elt for storing.
24190     // Accumulated smaller vector elements must be a multiple of the store size.
24191     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24192
24193     unsigned SizeRatio  = FromSz / ToSz;
24194
24195     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24196
24197     // Create a type on which we perform the shuffle
24198     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24199             StVT.getScalarType(), NumElems*SizeRatio);
24200
24201     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24202
24203     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24204     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24205     for (unsigned i = 0; i != NumElems; ++i)
24206       ShuffleVec[i] = i * SizeRatio;
24207
24208     // Can't shuffle using an illegal type.
24209     if (!TLI.isTypeLegal(WideVecVT))
24210       return SDValue();
24211
24212     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24213                                          DAG.getUNDEF(WideVecVT),
24214                                          &ShuffleVec[0]);
24215     // At this point all of the data is stored at the bottom of the
24216     // register. We now need to save it to mem.
24217
24218     // Find the largest store unit
24219     MVT StoreType = MVT::i8;
24220     for (MVT Tp : MVT::integer_valuetypes()) {
24221       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24222         StoreType = Tp;
24223     }
24224
24225     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24226     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24227         (64 <= NumElems * ToSz))
24228       StoreType = MVT::f64;
24229
24230     // Bitcast the original vector into a vector of store-size units
24231     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24232             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24233     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24234     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24235     SmallVector<SDValue, 8> Chains;
24236     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24237                                         TLI.getPointerTy(DAG.getDataLayout()));
24238     SDValue Ptr = St->getBasePtr();
24239
24240     // Perform one or more big stores into memory.
24241     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24242       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24243                                    StoreType, ShuffWide,
24244                                    DAG.getIntPtrConstant(i, dl));
24245       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24246                                 St->getPointerInfo(), St->isVolatile(),
24247                                 St->isNonTemporal(), St->getAlignment());
24248       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24249       Chains.push_back(Ch);
24250     }
24251
24252     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24253   }
24254
24255   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24256   // the FP state in cases where an emms may be missing.
24257   // A preferable solution to the general problem is to figure out the right
24258   // places to insert EMMS.  This qualifies as a quick hack.
24259
24260   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24261   if (VT.getSizeInBits() != 64)
24262     return SDValue();
24263
24264   const Function *F = DAG.getMachineFunction().getFunction();
24265   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24266   bool F64IsLegal =
24267       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24268   if ((VT.isVector() ||
24269        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24270       isa<LoadSDNode>(St->getValue()) &&
24271       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24272       St->getChain().hasOneUse() && !St->isVolatile()) {
24273     SDNode* LdVal = St->getValue().getNode();
24274     LoadSDNode *Ld = nullptr;
24275     int TokenFactorIndex = -1;
24276     SmallVector<SDValue, 8> Ops;
24277     SDNode* ChainVal = St->getChain().getNode();
24278     // Must be a store of a load.  We currently handle two cases:  the load
24279     // is a direct child, and it's under an intervening TokenFactor.  It is
24280     // possible to dig deeper under nested TokenFactors.
24281     if (ChainVal == LdVal)
24282       Ld = cast<LoadSDNode>(St->getChain());
24283     else if (St->getValue().hasOneUse() &&
24284              ChainVal->getOpcode() == ISD::TokenFactor) {
24285       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24286         if (ChainVal->getOperand(i).getNode() == LdVal) {
24287           TokenFactorIndex = i;
24288           Ld = cast<LoadSDNode>(St->getValue());
24289         } else
24290           Ops.push_back(ChainVal->getOperand(i));
24291       }
24292     }
24293
24294     if (!Ld || !ISD::isNormalLoad(Ld))
24295       return SDValue();
24296
24297     // If this is not the MMX case, i.e. we are just turning i64 load/store
24298     // into f64 load/store, avoid the transformation if there are multiple
24299     // uses of the loaded value.
24300     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24301       return SDValue();
24302
24303     SDLoc LdDL(Ld);
24304     SDLoc StDL(N);
24305     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24306     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24307     // pair instead.
24308     if (Subtarget->is64Bit() || F64IsLegal) {
24309       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24310       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24311                                   Ld->getPointerInfo(), Ld->isVolatile(),
24312                                   Ld->isNonTemporal(), Ld->isInvariant(),
24313                                   Ld->getAlignment());
24314       SDValue NewChain = NewLd.getValue(1);
24315       if (TokenFactorIndex != -1) {
24316         Ops.push_back(NewChain);
24317         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24318       }
24319       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24320                           St->getPointerInfo(),
24321                           St->isVolatile(), St->isNonTemporal(),
24322                           St->getAlignment());
24323     }
24324
24325     // Otherwise, lower to two pairs of 32-bit loads / stores.
24326     SDValue LoAddr = Ld->getBasePtr();
24327     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24328                                  DAG.getConstant(4, LdDL, MVT::i32));
24329
24330     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24331                                Ld->getPointerInfo(),
24332                                Ld->isVolatile(), Ld->isNonTemporal(),
24333                                Ld->isInvariant(), Ld->getAlignment());
24334     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24335                                Ld->getPointerInfo().getWithOffset(4),
24336                                Ld->isVolatile(), Ld->isNonTemporal(),
24337                                Ld->isInvariant(),
24338                                MinAlign(Ld->getAlignment(), 4));
24339
24340     SDValue NewChain = LoLd.getValue(1);
24341     if (TokenFactorIndex != -1) {
24342       Ops.push_back(LoLd);
24343       Ops.push_back(HiLd);
24344       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24345     }
24346
24347     LoAddr = St->getBasePtr();
24348     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24349                          DAG.getConstant(4, StDL, MVT::i32));
24350
24351     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24352                                 St->getPointerInfo(),
24353                                 St->isVolatile(), St->isNonTemporal(),
24354                                 St->getAlignment());
24355     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24356                                 St->getPointerInfo().getWithOffset(4),
24357                                 St->isVolatile(),
24358                                 St->isNonTemporal(),
24359                                 MinAlign(St->getAlignment(), 4));
24360     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24361   }
24362
24363   // This is similar to the above case, but here we handle a scalar 64-bit
24364   // integer store that is extracted from a vector on a 32-bit target.
24365   // If we have SSE2, then we can treat it like a floating-point double
24366   // to get past legalization. The execution dependencies fixup pass will
24367   // choose the optimal machine instruction for the store if this really is
24368   // an integer or v2f32 rather than an f64.
24369   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24370       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24371     SDValue OldExtract = St->getOperand(1);
24372     SDValue ExtOp0 = OldExtract.getOperand(0);
24373     unsigned VecSize = ExtOp0.getValueSizeInBits();
24374     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24375     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24376     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24377                                      BitCast, OldExtract.getOperand(1));
24378     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24379                         St->getPointerInfo(), St->isVolatile(),
24380                         St->isNonTemporal(), St->getAlignment());
24381   }
24382
24383   return SDValue();
24384 }
24385
24386 /// Return 'true' if this vector operation is "horizontal"
24387 /// and return the operands for the horizontal operation in LHS and RHS.  A
24388 /// horizontal operation performs the binary operation on successive elements
24389 /// of its first operand, then on successive elements of its second operand,
24390 /// returning the resulting values in a vector.  For example, if
24391 ///   A = < float a0, float a1, float a2, float a3 >
24392 /// and
24393 ///   B = < float b0, float b1, float b2, float b3 >
24394 /// then the result of doing a horizontal operation on A and B is
24395 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24396 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24397 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24398 /// set to A, RHS to B, and the routine returns 'true'.
24399 /// Note that the binary operation should have the property that if one of the
24400 /// operands is UNDEF then the result is UNDEF.
24401 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24402   // Look for the following pattern: if
24403   //   A = < float a0, float a1, float a2, float a3 >
24404   //   B = < float b0, float b1, float b2, float b3 >
24405   // and
24406   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24407   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24408   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24409   // which is A horizontal-op B.
24410
24411   // At least one of the operands should be a vector shuffle.
24412   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24413       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24414     return false;
24415
24416   MVT VT = LHS.getSimpleValueType();
24417
24418   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24419          "Unsupported vector type for horizontal add/sub");
24420
24421   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24422   // operate independently on 128-bit lanes.
24423   unsigned NumElts = VT.getVectorNumElements();
24424   unsigned NumLanes = VT.getSizeInBits()/128;
24425   unsigned NumLaneElts = NumElts / NumLanes;
24426   assert((NumLaneElts % 2 == 0) &&
24427          "Vector type should have an even number of elements in each lane");
24428   unsigned HalfLaneElts = NumLaneElts/2;
24429
24430   // View LHS in the form
24431   //   LHS = VECTOR_SHUFFLE A, B, LMask
24432   // If LHS is not a shuffle then pretend it is the shuffle
24433   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24434   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24435   // type VT.
24436   SDValue A, B;
24437   SmallVector<int, 16> LMask(NumElts);
24438   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24439     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24440       A = LHS.getOperand(0);
24441     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24442       B = LHS.getOperand(1);
24443     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24444     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24445   } else {
24446     if (LHS.getOpcode() != ISD::UNDEF)
24447       A = LHS;
24448     for (unsigned i = 0; i != NumElts; ++i)
24449       LMask[i] = i;
24450   }
24451
24452   // Likewise, view RHS in the form
24453   //   RHS = VECTOR_SHUFFLE C, D, RMask
24454   SDValue C, D;
24455   SmallVector<int, 16> RMask(NumElts);
24456   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24457     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24458       C = RHS.getOperand(0);
24459     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24460       D = RHS.getOperand(1);
24461     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24462     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24463   } else {
24464     if (RHS.getOpcode() != ISD::UNDEF)
24465       C = RHS;
24466     for (unsigned i = 0; i != NumElts; ++i)
24467       RMask[i] = i;
24468   }
24469
24470   // Check that the shuffles are both shuffling the same vectors.
24471   if (!(A == C && B == D) && !(A == D && B == C))
24472     return false;
24473
24474   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24475   if (!A.getNode() && !B.getNode())
24476     return false;
24477
24478   // If A and B occur in reverse order in RHS, then "swap" them (which means
24479   // rewriting the mask).
24480   if (A != C)
24481     ShuffleVectorSDNode::commuteMask(RMask);
24482
24483   // At this point LHS and RHS are equivalent to
24484   //   LHS = VECTOR_SHUFFLE A, B, LMask
24485   //   RHS = VECTOR_SHUFFLE A, B, RMask
24486   // Check that the masks correspond to performing a horizontal operation.
24487   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24488     for (unsigned i = 0; i != NumLaneElts; ++i) {
24489       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24490
24491       // Ignore any UNDEF components.
24492       if (LIdx < 0 || RIdx < 0 ||
24493           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24494           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24495         continue;
24496
24497       // Check that successive elements are being operated on.  If not, this is
24498       // not a horizontal operation.
24499       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24500       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24501       if (!(LIdx == Index && RIdx == Index + 1) &&
24502           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24503         return false;
24504     }
24505   }
24506
24507   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24508   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24509   return true;
24510 }
24511
24512 /// Do target-specific dag combines on floating point adds.
24513 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24514                                   const X86Subtarget *Subtarget) {
24515   EVT VT = N->getValueType(0);
24516   SDValue LHS = N->getOperand(0);
24517   SDValue RHS = N->getOperand(1);
24518
24519   // Try to synthesize horizontal adds from adds of shuffles.
24520   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24521        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24522       isHorizontalBinOp(LHS, RHS, true))
24523     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24524   return SDValue();
24525 }
24526
24527 /// Do target-specific dag combines on floating point subs.
24528 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24529                                   const X86Subtarget *Subtarget) {
24530   EVT VT = N->getValueType(0);
24531   SDValue LHS = N->getOperand(0);
24532   SDValue RHS = N->getOperand(1);
24533
24534   // Try to synthesize horizontal subs from subs of shuffles.
24535   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24536        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24537       isHorizontalBinOp(LHS, RHS, false))
24538     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24539   return SDValue();
24540 }
24541
24542 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24543 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24544   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24545
24546   // F[X]OR(0.0, x) -> x
24547   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24548     if (C->getValueAPF().isPosZero())
24549       return N->getOperand(1);
24550
24551   // F[X]OR(x, 0.0) -> x
24552   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24553     if (C->getValueAPF().isPosZero())
24554       return N->getOperand(0);
24555   return SDValue();
24556 }
24557
24558 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24559 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24560   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24561
24562   // Only perform optimizations if UnsafeMath is used.
24563   if (!DAG.getTarget().Options.UnsafeFPMath)
24564     return SDValue();
24565
24566   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24567   // into FMINC and FMAXC, which are Commutative operations.
24568   unsigned NewOp = 0;
24569   switch (N->getOpcode()) {
24570     default: llvm_unreachable("unknown opcode");
24571     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24572     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24573   }
24574
24575   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24576                      N->getOperand(0), N->getOperand(1));
24577 }
24578
24579 /// Do target-specific dag combines on X86ISD::FAND nodes.
24580 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24581   // FAND(0.0, x) -> 0.0
24582   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24583     if (C->getValueAPF().isPosZero())
24584       return N->getOperand(0);
24585
24586   // FAND(x, 0.0) -> 0.0
24587   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24588     if (C->getValueAPF().isPosZero())
24589       return N->getOperand(1);
24590
24591   return SDValue();
24592 }
24593
24594 /// Do target-specific dag combines on X86ISD::FANDN nodes
24595 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24596   // FANDN(0.0, x) -> x
24597   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24598     if (C->getValueAPF().isPosZero())
24599       return N->getOperand(1);
24600
24601   // FANDN(x, 0.0) -> 0.0
24602   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24603     if (C->getValueAPF().isPosZero())
24604       return N->getOperand(1);
24605
24606   return SDValue();
24607 }
24608
24609 static SDValue PerformBTCombine(SDNode *N,
24610                                 SelectionDAG &DAG,
24611                                 TargetLowering::DAGCombinerInfo &DCI) {
24612   // BT ignores high bits in the bit index operand.
24613   SDValue Op1 = N->getOperand(1);
24614   if (Op1.hasOneUse()) {
24615     unsigned BitWidth = Op1.getValueSizeInBits();
24616     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24617     APInt KnownZero, KnownOne;
24618     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24619                                           !DCI.isBeforeLegalizeOps());
24620     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24621     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24622         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24623       DCI.CommitTargetLoweringOpt(TLO);
24624   }
24625   return SDValue();
24626 }
24627
24628 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24629   SDValue Op = N->getOperand(0);
24630   if (Op.getOpcode() == ISD::BITCAST)
24631     Op = Op.getOperand(0);
24632   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24633   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24634       VT.getVectorElementType().getSizeInBits() ==
24635       OpVT.getVectorElementType().getSizeInBits()) {
24636     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24637   }
24638   return SDValue();
24639 }
24640
24641 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24642                                                const X86Subtarget *Subtarget) {
24643   EVT VT = N->getValueType(0);
24644   if (!VT.isVector())
24645     return SDValue();
24646
24647   SDValue N0 = N->getOperand(0);
24648   SDValue N1 = N->getOperand(1);
24649   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24650   SDLoc dl(N);
24651
24652   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24653   // both SSE and AVX2 since there is no sign-extended shift right
24654   // operation on a vector with 64-bit elements.
24655   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24656   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24657   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24658       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24659     SDValue N00 = N0.getOperand(0);
24660
24661     // EXTLOAD has a better solution on AVX2,
24662     // it may be replaced with X86ISD::VSEXT node.
24663     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24664       if (!ISD::isNormalLoad(N00.getNode()))
24665         return SDValue();
24666
24667     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24668         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24669                                   N00, N1);
24670       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24671     }
24672   }
24673   return SDValue();
24674 }
24675
24676 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24677                                   TargetLowering::DAGCombinerInfo &DCI,
24678                                   const X86Subtarget *Subtarget) {
24679   SDValue N0 = N->getOperand(0);
24680   EVT VT = N->getValueType(0);
24681   EVT SVT = VT.getScalarType();
24682   EVT InVT = N0.getValueType();
24683   EVT InSVT = InVT.getScalarType();
24684   SDLoc DL(N);
24685
24686   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24687   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24688   // This exposes the sext to the sdivrem lowering, so that it directly extends
24689   // from AH (which we otherwise need to do contortions to access).
24690   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24691       InVT == MVT::i8 && VT == MVT::i32) {
24692     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24693     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24694                             N0.getOperand(0), N0.getOperand(1));
24695     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24696     return R.getValue(1);
24697   }
24698
24699   if (!DCI.isBeforeLegalizeOps()) {
24700     if (InVT == MVT::i1) {
24701       SDValue Zero = DAG.getConstant(0, DL, VT);
24702       SDValue AllOnes =
24703         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24704       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24705     }
24706     return SDValue();
24707   }
24708
24709   if (VT.isVector() && Subtarget->hasSSE2()) {
24710     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24711       EVT InVT = N.getValueType();
24712       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24713                                    Size / InVT.getScalarSizeInBits());
24714       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24715                                     DAG.getUNDEF(InVT));
24716       Opnds[0] = N;
24717       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24718     };
24719
24720     // If target-size is less than 128-bits, extend to a type that would extend
24721     // to 128 bits, extend that and extract the original target vector.
24722     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24723         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24724         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24725       unsigned Scale = 128 / VT.getSizeInBits();
24726       EVT ExVT =
24727           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24728       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24729       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24730       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24731                          DAG.getIntPtrConstant(0, DL));
24732     }
24733
24734     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24735     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24736     if (VT.getSizeInBits() == 128 &&
24737         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24738         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24739       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24740       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24741     }
24742
24743     // On pre-AVX2 targets, split into 128-bit nodes of
24744     // ISD::SIGN_EXTEND_VECTOR_INREG.
24745     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24746         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24747         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24748       unsigned NumVecs = VT.getSizeInBits() / 128;
24749       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24750       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24751       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24752
24753       SmallVector<SDValue, 8> Opnds;
24754       for (unsigned i = 0, Offset = 0; i != NumVecs;
24755            ++i, Offset += NumSubElts) {
24756         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24757                                      DAG.getIntPtrConstant(Offset, DL));
24758         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24759         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24760         Opnds.push_back(SrcVec);
24761       }
24762       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24763     }
24764   }
24765
24766   if (!Subtarget->hasFp256())
24767     return SDValue();
24768
24769   if (VT.isVector() && VT.getSizeInBits() == 256)
24770     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24771       return R;
24772
24773   return SDValue();
24774 }
24775
24776 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24777                                  const X86Subtarget* Subtarget) {
24778   SDLoc dl(N);
24779   EVT VT = N->getValueType(0);
24780
24781   // Let legalize expand this if it isn't a legal type yet.
24782   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24783     return SDValue();
24784
24785   EVT ScalarVT = VT.getScalarType();
24786   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24787       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24788        !Subtarget->hasAVX512()))
24789     return SDValue();
24790
24791   SDValue A = N->getOperand(0);
24792   SDValue B = N->getOperand(1);
24793   SDValue C = N->getOperand(2);
24794
24795   bool NegA = (A.getOpcode() == ISD::FNEG);
24796   bool NegB = (B.getOpcode() == ISD::FNEG);
24797   bool NegC = (C.getOpcode() == ISD::FNEG);
24798
24799   // Negative multiplication when NegA xor NegB
24800   bool NegMul = (NegA != NegB);
24801   if (NegA)
24802     A = A.getOperand(0);
24803   if (NegB)
24804     B = B.getOperand(0);
24805   if (NegC)
24806     C = C.getOperand(0);
24807
24808   unsigned Opcode;
24809   if (!NegMul)
24810     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24811   else
24812     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24813
24814   return DAG.getNode(Opcode, dl, VT, A, B, C);
24815 }
24816
24817 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24818                                   TargetLowering::DAGCombinerInfo &DCI,
24819                                   const X86Subtarget *Subtarget) {
24820   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24821   //           (and (i32 x86isd::setcc_carry), 1)
24822   // This eliminates the zext. This transformation is necessary because
24823   // ISD::SETCC is always legalized to i8.
24824   SDLoc dl(N);
24825   SDValue N0 = N->getOperand(0);
24826   EVT VT = N->getValueType(0);
24827
24828   if (N0.getOpcode() == ISD::AND &&
24829       N0.hasOneUse() &&
24830       N0.getOperand(0).hasOneUse()) {
24831     SDValue N00 = N0.getOperand(0);
24832     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24833       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24834       if (!C || C->getZExtValue() != 1)
24835         return SDValue();
24836       return DAG.getNode(ISD::AND, dl, VT,
24837                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24838                                      N00.getOperand(0), N00.getOperand(1)),
24839                          DAG.getConstant(1, dl, VT));
24840     }
24841   }
24842
24843   if (N0.getOpcode() == ISD::TRUNCATE &&
24844       N0.hasOneUse() &&
24845       N0.getOperand(0).hasOneUse()) {
24846     SDValue N00 = N0.getOperand(0);
24847     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24848       return DAG.getNode(ISD::AND, dl, VT,
24849                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24850                                      N00.getOperand(0), N00.getOperand(1)),
24851                          DAG.getConstant(1, dl, VT));
24852     }
24853   }
24854
24855   if (VT.is256BitVector())
24856     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24857       return R;
24858
24859   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24860   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24861   // This exposes the zext to the udivrem lowering, so that it directly extends
24862   // from AH (which we otherwise need to do contortions to access).
24863   if (N0.getOpcode() == ISD::UDIVREM &&
24864       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24865       (VT == MVT::i32 || VT == MVT::i64)) {
24866     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24867     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24868                             N0.getOperand(0), N0.getOperand(1));
24869     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24870     return R.getValue(1);
24871   }
24872
24873   return SDValue();
24874 }
24875
24876 // Optimize x == -y --> x+y == 0
24877 //          x != -y --> x+y != 0
24878 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24879                                       const X86Subtarget* Subtarget) {
24880   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24881   SDValue LHS = N->getOperand(0);
24882   SDValue RHS = N->getOperand(1);
24883   EVT VT = N->getValueType(0);
24884   SDLoc DL(N);
24885
24886   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24887     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24888       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24889         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24890                                    LHS.getOperand(1));
24891         return DAG.getSetCC(DL, N->getValueType(0), addV,
24892                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24893       }
24894   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24895     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24896       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24897         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24898                                    RHS.getOperand(1));
24899         return DAG.getSetCC(DL, N->getValueType(0), addV,
24900                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24901       }
24902
24903   if (VT.getScalarType() == MVT::i1 &&
24904       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24905     bool IsSEXT0 =
24906         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24907         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24908     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24909
24910     if (!IsSEXT0 || !IsVZero1) {
24911       // Swap the operands and update the condition code.
24912       std::swap(LHS, RHS);
24913       CC = ISD::getSetCCSwappedOperands(CC);
24914
24915       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24916                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24917       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24918     }
24919
24920     if (IsSEXT0 && IsVZero1) {
24921       assert(VT == LHS.getOperand(0).getValueType() &&
24922              "Uexpected operand type");
24923       if (CC == ISD::SETGT)
24924         return DAG.getConstant(0, DL, VT);
24925       if (CC == ISD::SETLE)
24926         return DAG.getConstant(1, DL, VT);
24927       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24928         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24929
24930       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24931              "Unexpected condition code!");
24932       return LHS.getOperand(0);
24933     }
24934   }
24935
24936   return SDValue();
24937 }
24938
24939 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24940                                          SelectionDAG &DAG) {
24941   SDLoc dl(Load);
24942   MVT VT = Load->getSimpleValueType(0);
24943   MVT EVT = VT.getVectorElementType();
24944   SDValue Addr = Load->getOperand(1);
24945   SDValue NewAddr = DAG.getNode(
24946       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24947       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24948                       Addr.getSimpleValueType()));
24949
24950   SDValue NewLoad =
24951       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24952                   DAG.getMachineFunction().getMachineMemOperand(
24953                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24954   return NewLoad;
24955 }
24956
24957 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24958                                       const X86Subtarget *Subtarget) {
24959   SDLoc dl(N);
24960   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24961   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24962          "X86insertps is only defined for v4x32");
24963
24964   SDValue Ld = N->getOperand(1);
24965   if (MayFoldLoad(Ld)) {
24966     // Extract the countS bits from the immediate so we can get the proper
24967     // address when narrowing the vector load to a specific element.
24968     // When the second source op is a memory address, insertps doesn't use
24969     // countS and just gets an f32 from that address.
24970     unsigned DestIndex =
24971         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24972
24973     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24974
24975     // Create this as a scalar to vector to match the instruction pattern.
24976     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24977     // countS bits are ignored when loading from memory on insertps, which
24978     // means we don't need to explicitly set them to 0.
24979     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24980                        LoadScalarToVector, N->getOperand(2));
24981   }
24982   return SDValue();
24983 }
24984
24985 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24986   SDValue V0 = N->getOperand(0);
24987   SDValue V1 = N->getOperand(1);
24988   SDLoc DL(N);
24989   EVT VT = N->getValueType(0);
24990
24991   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24992   // operands and changing the mask to 1. This saves us a bunch of
24993   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24994   // x86InstrInfo knows how to commute this back after instruction selection
24995   // if it would help register allocation.
24996
24997   // TODO: If optimizing for size or a processor that doesn't suffer from
24998   // partial register update stalls, this should be transformed into a MOVSD
24999   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25000
25001   if (VT == MVT::v2f64)
25002     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25003       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25004         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25005         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25006       }
25007
25008   return SDValue();
25009 }
25010
25011 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25012 // as "sbb reg,reg", since it can be extended without zext and produces
25013 // an all-ones bit which is more useful than 0/1 in some cases.
25014 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25015                                MVT VT) {
25016   if (VT == MVT::i8)
25017     return DAG.getNode(ISD::AND, DL, VT,
25018                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25019                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25020                                    EFLAGS),
25021                        DAG.getConstant(1, DL, VT));
25022   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25023   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25024                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25025                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25026                                  EFLAGS));
25027 }
25028
25029 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25030 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25031                                    TargetLowering::DAGCombinerInfo &DCI,
25032                                    const X86Subtarget *Subtarget) {
25033   SDLoc DL(N);
25034   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25035   SDValue EFLAGS = N->getOperand(1);
25036
25037   if (CC == X86::COND_A) {
25038     // Try to convert COND_A into COND_B in an attempt to facilitate
25039     // materializing "setb reg".
25040     //
25041     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25042     // cannot take an immediate as its first operand.
25043     //
25044     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25045         EFLAGS.getValueType().isInteger() &&
25046         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25047       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25048                                    EFLAGS.getNode()->getVTList(),
25049                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25050       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25051       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25052     }
25053   }
25054
25055   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25056   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25057   // cases.
25058   if (CC == X86::COND_B)
25059     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25060
25061   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25062     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25063     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25064   }
25065
25066   return SDValue();
25067 }
25068
25069 // Optimize branch condition evaluation.
25070 //
25071 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25072                                     TargetLowering::DAGCombinerInfo &DCI,
25073                                     const X86Subtarget *Subtarget) {
25074   SDLoc DL(N);
25075   SDValue Chain = N->getOperand(0);
25076   SDValue Dest = N->getOperand(1);
25077   SDValue EFLAGS = N->getOperand(3);
25078   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25079
25080   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25081     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25082     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25083                        Flags);
25084   }
25085
25086   return SDValue();
25087 }
25088
25089 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25090                                                          SelectionDAG &DAG) {
25091   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25092   // optimize away operation when it's from a constant.
25093   //
25094   // The general transformation is:
25095   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25096   //       AND(VECTOR_CMP(x,y), constant2)
25097   //    constant2 = UNARYOP(constant)
25098
25099   // Early exit if this isn't a vector operation, the operand of the
25100   // unary operation isn't a bitwise AND, or if the sizes of the operations
25101   // aren't the same.
25102   EVT VT = N->getValueType(0);
25103   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25104       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25105       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25106     return SDValue();
25107
25108   // Now check that the other operand of the AND is a constant. We could
25109   // make the transformation for non-constant splats as well, but it's unclear
25110   // that would be a benefit as it would not eliminate any operations, just
25111   // perform one more step in scalar code before moving to the vector unit.
25112   if (BuildVectorSDNode *BV =
25113           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25114     // Bail out if the vector isn't a constant.
25115     if (!BV->isConstant())
25116       return SDValue();
25117
25118     // Everything checks out. Build up the new and improved node.
25119     SDLoc DL(N);
25120     EVT IntVT = BV->getValueType(0);
25121     // Create a new constant of the appropriate type for the transformed
25122     // DAG.
25123     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25124     // The AND node needs bitcasts to/from an integer vector type around it.
25125     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25126     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25127                                  N->getOperand(0)->getOperand(0), MaskConst);
25128     SDValue Res = DAG.getBitcast(VT, NewAnd);
25129     return Res;
25130   }
25131
25132   return SDValue();
25133 }
25134
25135 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25136                                         const X86Subtarget *Subtarget) {
25137   SDValue Op0 = N->getOperand(0);
25138   EVT VT = N->getValueType(0);
25139   EVT InVT = Op0.getValueType();
25140   EVT InSVT = InVT.getScalarType();
25141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25142
25143   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25144   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25145   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25146     SDLoc dl(N);
25147     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25148                                  InVT.getVectorNumElements());
25149     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25150
25151     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25152       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25153
25154     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25155   }
25156
25157   return SDValue();
25158 }
25159
25160 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25161                                         const X86Subtarget *Subtarget) {
25162   // First try to optimize away the conversion entirely when it's
25163   // conditionally from a constant. Vectors only.
25164   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25165     return Res;
25166
25167   // Now move on to more general possibilities.
25168   SDValue Op0 = N->getOperand(0);
25169   EVT VT = N->getValueType(0);
25170   EVT InVT = Op0.getValueType();
25171   EVT InSVT = InVT.getScalarType();
25172
25173   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25174   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25175   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25176     SDLoc dl(N);
25177     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25178                                  InVT.getVectorNumElements());
25179     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25180     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25181   }
25182
25183   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25184   // a 32-bit target where SSE doesn't support i64->FP operations.
25185   if (Op0.getOpcode() == ISD::LOAD) {
25186     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25187     EVT LdVT = Ld->getValueType(0);
25188
25189     // This transformation is not supported if the result type is f16
25190     if (VT == MVT::f16)
25191       return SDValue();
25192
25193     if (!Ld->isVolatile() && !VT.isVector() &&
25194         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25195         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25196       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25197           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25198       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25199       return FILDChain;
25200     }
25201   }
25202   return SDValue();
25203 }
25204
25205 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25206 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25207                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25208   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25209   // the result is either zero or one (depending on the input carry bit).
25210   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25211   if (X86::isZeroNode(N->getOperand(0)) &&
25212       X86::isZeroNode(N->getOperand(1)) &&
25213       // We don't have a good way to replace an EFLAGS use, so only do this when
25214       // dead right now.
25215       SDValue(N, 1).use_empty()) {
25216     SDLoc DL(N);
25217     EVT VT = N->getValueType(0);
25218     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25219     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25220                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25221                                            DAG.getConstant(X86::COND_B, DL,
25222                                                            MVT::i8),
25223                                            N->getOperand(2)),
25224                                DAG.getConstant(1, DL, VT));
25225     return DCI.CombineTo(N, Res1, CarryOut);
25226   }
25227
25228   return SDValue();
25229 }
25230
25231 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25232 //      (add Y, (setne X, 0)) -> sbb -1, Y
25233 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25234 //      (sub (setne X, 0), Y) -> adc -1, Y
25235 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25236   SDLoc DL(N);
25237
25238   // Look through ZExts.
25239   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25240   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25241     return SDValue();
25242
25243   SDValue SetCC = Ext.getOperand(0);
25244   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25245     return SDValue();
25246
25247   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25248   if (CC != X86::COND_E && CC != X86::COND_NE)
25249     return SDValue();
25250
25251   SDValue Cmp = SetCC.getOperand(1);
25252   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25253       !X86::isZeroNode(Cmp.getOperand(1)) ||
25254       !Cmp.getOperand(0).getValueType().isInteger())
25255     return SDValue();
25256
25257   SDValue CmpOp0 = Cmp.getOperand(0);
25258   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25259                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25260
25261   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25262   if (CC == X86::COND_NE)
25263     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25264                        DL, OtherVal.getValueType(), OtherVal,
25265                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25266                        NewCmp);
25267   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25268                      DL, OtherVal.getValueType(), OtherVal,
25269                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25270 }
25271
25272 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25273 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25274                                  const X86Subtarget *Subtarget) {
25275   EVT VT = N->getValueType(0);
25276   SDValue Op0 = N->getOperand(0);
25277   SDValue Op1 = N->getOperand(1);
25278
25279   // Try to synthesize horizontal adds from adds of shuffles.
25280   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25281        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25282       isHorizontalBinOp(Op0, Op1, true))
25283     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25284
25285   return OptimizeConditionalInDecrement(N, DAG);
25286 }
25287
25288 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25289                                  const X86Subtarget *Subtarget) {
25290   SDValue Op0 = N->getOperand(0);
25291   SDValue Op1 = N->getOperand(1);
25292
25293   // X86 can't encode an immediate LHS of a sub. See if we can push the
25294   // negation into a preceding instruction.
25295   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25296     // If the RHS of the sub is a XOR with one use and a constant, invert the
25297     // immediate. Then add one to the LHS of the sub so we can turn
25298     // X-Y -> X+~Y+1, saving one register.
25299     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25300         isa<ConstantSDNode>(Op1.getOperand(1))) {
25301       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25302       EVT VT = Op0.getValueType();
25303       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25304                                    Op1.getOperand(0),
25305                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25306       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25307                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25308     }
25309   }
25310
25311   // Try to synthesize horizontal adds from adds of shuffles.
25312   EVT VT = N->getValueType(0);
25313   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25314        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25315       isHorizontalBinOp(Op0, Op1, true))
25316     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25317
25318   return OptimizeConditionalInDecrement(N, DAG);
25319 }
25320
25321 /// performVZEXTCombine - Performs build vector combines
25322 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25323                                    TargetLowering::DAGCombinerInfo &DCI,
25324                                    const X86Subtarget *Subtarget) {
25325   SDLoc DL(N);
25326   MVT VT = N->getSimpleValueType(0);
25327   SDValue Op = N->getOperand(0);
25328   MVT OpVT = Op.getSimpleValueType();
25329   MVT OpEltVT = OpVT.getVectorElementType();
25330   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25331
25332   // (vzext (bitcast (vzext (x)) -> (vzext x)
25333   SDValue V = Op;
25334   while (V.getOpcode() == ISD::BITCAST)
25335     V = V.getOperand(0);
25336
25337   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25338     MVT InnerVT = V.getSimpleValueType();
25339     MVT InnerEltVT = InnerVT.getVectorElementType();
25340
25341     // If the element sizes match exactly, we can just do one larger vzext. This
25342     // is always an exact type match as vzext operates on integer types.
25343     if (OpEltVT == InnerEltVT) {
25344       assert(OpVT == InnerVT && "Types must match for vzext!");
25345       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25346     }
25347
25348     // The only other way we can combine them is if only a single element of the
25349     // inner vzext is used in the input to the outer vzext.
25350     if (InnerEltVT.getSizeInBits() < InputBits)
25351       return SDValue();
25352
25353     // In this case, the inner vzext is completely dead because we're going to
25354     // only look at bits inside of the low element. Just do the outer vzext on
25355     // a bitcast of the input to the inner.
25356     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25357   }
25358
25359   // Check if we can bypass extracting and re-inserting an element of an input
25360   // vector. Essentialy:
25361   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25362   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25363       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25364       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25365     SDValue ExtractedV = V.getOperand(0);
25366     SDValue OrigV = ExtractedV.getOperand(0);
25367     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25368       if (ExtractIdx->getZExtValue() == 0) {
25369         MVT OrigVT = OrigV.getSimpleValueType();
25370         // Extract a subvector if necessary...
25371         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25372           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25373           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25374                                     OrigVT.getVectorNumElements() / Ratio);
25375           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25376                               DAG.getIntPtrConstant(0, DL));
25377         }
25378         Op = DAG.getBitcast(OpVT, OrigV);
25379         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25380       }
25381   }
25382
25383   return SDValue();
25384 }
25385
25386 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25387                                              DAGCombinerInfo &DCI) const {
25388   SelectionDAG &DAG = DCI.DAG;
25389   switch (N->getOpcode()) {
25390   default: break;
25391   case ISD::EXTRACT_VECTOR_ELT:
25392     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25393   case ISD::VSELECT:
25394   case ISD::SELECT:
25395   case X86ISD::SHRUNKBLEND:
25396     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25397   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25398   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25399   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25400   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25401   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25402   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25403   case ISD::SHL:
25404   case ISD::SRA:
25405   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25406   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25407   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25408   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25409   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25410   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25411   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25412   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25413   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25414   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25415   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25416   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25417   case X86ISD::FXOR:
25418   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25419   case X86ISD::FMIN:
25420   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25421   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25422   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25423   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25424   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25425   case ISD::ANY_EXTEND:
25426   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25427   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25428   case ISD::SIGN_EXTEND_INREG:
25429     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25430   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25431   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25432   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25433   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25434   case X86ISD::SHUFP:       // Handle all target specific shuffles
25435   case X86ISD::PALIGNR:
25436   case X86ISD::UNPCKH:
25437   case X86ISD::UNPCKL:
25438   case X86ISD::MOVHLPS:
25439   case X86ISD::MOVLHPS:
25440   case X86ISD::PSHUFB:
25441   case X86ISD::PSHUFD:
25442   case X86ISD::PSHUFHW:
25443   case X86ISD::PSHUFLW:
25444   case X86ISD::MOVSS:
25445   case X86ISD::MOVSD:
25446   case X86ISD::VPERMILPI:
25447   case X86ISD::VPERM2X128:
25448   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25449   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25450   case ISD::INTRINSIC_WO_CHAIN:
25451     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25452   case X86ISD::INSERTPS: {
25453     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25454       return PerformINSERTPSCombine(N, DAG, Subtarget);
25455     break;
25456   }
25457   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25458   }
25459
25460   return SDValue();
25461 }
25462
25463 /// isTypeDesirableForOp - Return true if the target has native support for
25464 /// the specified value type and it is 'desirable' to use the type for the
25465 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25466 /// instruction encodings are longer and some i16 instructions are slow.
25467 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25468   if (!isTypeLegal(VT))
25469     return false;
25470   if (VT != MVT::i16)
25471     return true;
25472
25473   switch (Opc) {
25474   default:
25475     return true;
25476   case ISD::LOAD:
25477   case ISD::SIGN_EXTEND:
25478   case ISD::ZERO_EXTEND:
25479   case ISD::ANY_EXTEND:
25480   case ISD::SHL:
25481   case ISD::SRL:
25482   case ISD::SUB:
25483   case ISD::ADD:
25484   case ISD::MUL:
25485   case ISD::AND:
25486   case ISD::OR:
25487   case ISD::XOR:
25488     return false;
25489   }
25490 }
25491
25492 /// IsDesirableToPromoteOp - This method query the target whether it is
25493 /// beneficial for dag combiner to promote the specified node. If true, it
25494 /// should return the desired promotion type by reference.
25495 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25496   EVT VT = Op.getValueType();
25497   if (VT != MVT::i16)
25498     return false;
25499
25500   bool Promote = false;
25501   bool Commute = false;
25502   switch (Op.getOpcode()) {
25503   default: break;
25504   case ISD::LOAD: {
25505     LoadSDNode *LD = cast<LoadSDNode>(Op);
25506     // If the non-extending load has a single use and it's not live out, then it
25507     // might be folded.
25508     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25509                                                      Op.hasOneUse()*/) {
25510       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25511              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25512         // The only case where we'd want to promote LOAD (rather then it being
25513         // promoted as an operand is when it's only use is liveout.
25514         if (UI->getOpcode() != ISD::CopyToReg)
25515           return false;
25516       }
25517     }
25518     Promote = true;
25519     break;
25520   }
25521   case ISD::SIGN_EXTEND:
25522   case ISD::ZERO_EXTEND:
25523   case ISD::ANY_EXTEND:
25524     Promote = true;
25525     break;
25526   case ISD::SHL:
25527   case ISD::SRL: {
25528     SDValue N0 = Op.getOperand(0);
25529     // Look out for (store (shl (load), x)).
25530     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25531       return false;
25532     Promote = true;
25533     break;
25534   }
25535   case ISD::ADD:
25536   case ISD::MUL:
25537   case ISD::AND:
25538   case ISD::OR:
25539   case ISD::XOR:
25540     Commute = true;
25541     // fallthrough
25542   case ISD::SUB: {
25543     SDValue N0 = Op.getOperand(0);
25544     SDValue N1 = Op.getOperand(1);
25545     if (!Commute && MayFoldLoad(N1))
25546       return false;
25547     // Avoid disabling potential load folding opportunities.
25548     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25549       return false;
25550     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25551       return false;
25552     Promote = true;
25553   }
25554   }
25555
25556   PVT = MVT::i32;
25557   return Promote;
25558 }
25559
25560 //===----------------------------------------------------------------------===//
25561 //                           X86 Inline Assembly Support
25562 //===----------------------------------------------------------------------===//
25563
25564 // Helper to match a string separated by whitespace.
25565 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25566   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25567
25568   for (StringRef Piece : Pieces) {
25569     if (!S.startswith(Piece)) // Check if the piece matches.
25570       return false;
25571
25572     S = S.substr(Piece.size());
25573     StringRef::size_type Pos = S.find_first_not_of(" \t");
25574     if (Pos == 0) // We matched a prefix.
25575       return false;
25576
25577     S = S.substr(Pos);
25578   }
25579
25580   return S.empty();
25581 }
25582
25583 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25584
25585   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25586     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25587         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25588         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25589
25590       if (AsmPieces.size() == 3)
25591         return true;
25592       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25593         return true;
25594     }
25595   }
25596   return false;
25597 }
25598
25599 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25600   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25601
25602   std::string AsmStr = IA->getAsmString();
25603
25604   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25605   if (!Ty || Ty->getBitWidth() % 16 != 0)
25606     return false;
25607
25608   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25609   SmallVector<StringRef, 4> AsmPieces;
25610   SplitString(AsmStr, AsmPieces, ";\n");
25611
25612   switch (AsmPieces.size()) {
25613   default: return false;
25614   case 1:
25615     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25616     // we will turn this bswap into something that will be lowered to logical
25617     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25618     // lower so don't worry about this.
25619     // bswap $0
25620     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25621         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25622         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25623         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25624         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25625         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25626       // No need to check constraints, nothing other than the equivalent of
25627       // "=r,0" would be valid here.
25628       return IntrinsicLowering::LowerToByteSwap(CI);
25629     }
25630
25631     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25632     if (CI->getType()->isIntegerTy(16) &&
25633         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25634         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25635          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25636       AsmPieces.clear();
25637       StringRef ConstraintsStr = IA->getConstraintString();
25638       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25639       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25640       if (clobbersFlagRegisters(AsmPieces))
25641         return IntrinsicLowering::LowerToByteSwap(CI);
25642     }
25643     break;
25644   case 3:
25645     if (CI->getType()->isIntegerTy(32) &&
25646         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25647         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25648         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25649         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25650       AsmPieces.clear();
25651       StringRef ConstraintsStr = IA->getConstraintString();
25652       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25653       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25654       if (clobbersFlagRegisters(AsmPieces))
25655         return IntrinsicLowering::LowerToByteSwap(CI);
25656     }
25657
25658     if (CI->getType()->isIntegerTy(64)) {
25659       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25660       if (Constraints.size() >= 2 &&
25661           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25662           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25663         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25664         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25665             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25666             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25667           return IntrinsicLowering::LowerToByteSwap(CI);
25668       }
25669     }
25670     break;
25671   }
25672   return false;
25673 }
25674
25675 /// getConstraintType - Given a constraint letter, return the type of
25676 /// constraint it is for this target.
25677 X86TargetLowering::ConstraintType
25678 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25679   if (Constraint.size() == 1) {
25680     switch (Constraint[0]) {
25681     case 'R':
25682     case 'q':
25683     case 'Q':
25684     case 'f':
25685     case 't':
25686     case 'u':
25687     case 'y':
25688     case 'x':
25689     case 'Y':
25690     case 'l':
25691       return C_RegisterClass;
25692     case 'a':
25693     case 'b':
25694     case 'c':
25695     case 'd':
25696     case 'S':
25697     case 'D':
25698     case 'A':
25699       return C_Register;
25700     case 'I':
25701     case 'J':
25702     case 'K':
25703     case 'L':
25704     case 'M':
25705     case 'N':
25706     case 'G':
25707     case 'C':
25708     case 'e':
25709     case 'Z':
25710       return C_Other;
25711     default:
25712       break;
25713     }
25714   }
25715   return TargetLowering::getConstraintType(Constraint);
25716 }
25717
25718 /// Examine constraint type and operand type and determine a weight value.
25719 /// This object must already have been set up with the operand type
25720 /// and the current alternative constraint selected.
25721 TargetLowering::ConstraintWeight
25722   X86TargetLowering::getSingleConstraintMatchWeight(
25723     AsmOperandInfo &info, const char *constraint) const {
25724   ConstraintWeight weight = CW_Invalid;
25725   Value *CallOperandVal = info.CallOperandVal;
25726     // If we don't have a value, we can't do a match,
25727     // but allow it at the lowest weight.
25728   if (!CallOperandVal)
25729     return CW_Default;
25730   Type *type = CallOperandVal->getType();
25731   // Look at the constraint type.
25732   switch (*constraint) {
25733   default:
25734     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25735   case 'R':
25736   case 'q':
25737   case 'Q':
25738   case 'a':
25739   case 'b':
25740   case 'c':
25741   case 'd':
25742   case 'S':
25743   case 'D':
25744   case 'A':
25745     if (CallOperandVal->getType()->isIntegerTy())
25746       weight = CW_SpecificReg;
25747     break;
25748   case 'f':
25749   case 't':
25750   case 'u':
25751     if (type->isFloatingPointTy())
25752       weight = CW_SpecificReg;
25753     break;
25754   case 'y':
25755     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25756       weight = CW_SpecificReg;
25757     break;
25758   case 'x':
25759   case 'Y':
25760     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25761         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25762       weight = CW_Register;
25763     break;
25764   case 'I':
25765     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25766       if (C->getZExtValue() <= 31)
25767         weight = CW_Constant;
25768     }
25769     break;
25770   case 'J':
25771     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25772       if (C->getZExtValue() <= 63)
25773         weight = CW_Constant;
25774     }
25775     break;
25776   case 'K':
25777     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25778       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25779         weight = CW_Constant;
25780     }
25781     break;
25782   case 'L':
25783     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25784       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25785         weight = CW_Constant;
25786     }
25787     break;
25788   case 'M':
25789     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25790       if (C->getZExtValue() <= 3)
25791         weight = CW_Constant;
25792     }
25793     break;
25794   case 'N':
25795     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25796       if (C->getZExtValue() <= 0xff)
25797         weight = CW_Constant;
25798     }
25799     break;
25800   case 'G':
25801   case 'C':
25802     if (isa<ConstantFP>(CallOperandVal)) {
25803       weight = CW_Constant;
25804     }
25805     break;
25806   case 'e':
25807     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25808       if ((C->getSExtValue() >= -0x80000000LL) &&
25809           (C->getSExtValue() <= 0x7fffffffLL))
25810         weight = CW_Constant;
25811     }
25812     break;
25813   case 'Z':
25814     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25815       if (C->getZExtValue() <= 0xffffffff)
25816         weight = CW_Constant;
25817     }
25818     break;
25819   }
25820   return weight;
25821 }
25822
25823 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25824 /// with another that has more specific requirements based on the type of the
25825 /// corresponding operand.
25826 const char *X86TargetLowering::
25827 LowerXConstraint(EVT ConstraintVT) const {
25828   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25829   // 'f' like normal targets.
25830   if (ConstraintVT.isFloatingPoint()) {
25831     if (Subtarget->hasSSE2())
25832       return "Y";
25833     if (Subtarget->hasSSE1())
25834       return "x";
25835   }
25836
25837   return TargetLowering::LowerXConstraint(ConstraintVT);
25838 }
25839
25840 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25841 /// vector.  If it is invalid, don't add anything to Ops.
25842 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25843                                                      std::string &Constraint,
25844                                                      std::vector<SDValue>&Ops,
25845                                                      SelectionDAG &DAG) const {
25846   SDValue Result;
25847
25848   // Only support length 1 constraints for now.
25849   if (Constraint.length() > 1) return;
25850
25851   char ConstraintLetter = Constraint[0];
25852   switch (ConstraintLetter) {
25853   default: break;
25854   case 'I':
25855     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25856       if (C->getZExtValue() <= 31) {
25857         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25858                                        Op.getValueType());
25859         break;
25860       }
25861     }
25862     return;
25863   case 'J':
25864     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25865       if (C->getZExtValue() <= 63) {
25866         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25867                                        Op.getValueType());
25868         break;
25869       }
25870     }
25871     return;
25872   case 'K':
25873     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25874       if (isInt<8>(C->getSExtValue())) {
25875         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25876                                        Op.getValueType());
25877         break;
25878       }
25879     }
25880     return;
25881   case 'L':
25882     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25883       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25884           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25885         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25886                                        Op.getValueType());
25887         break;
25888       }
25889     }
25890     return;
25891   case 'M':
25892     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25893       if (C->getZExtValue() <= 3) {
25894         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25895                                        Op.getValueType());
25896         break;
25897       }
25898     }
25899     return;
25900   case 'N':
25901     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25902       if (C->getZExtValue() <= 255) {
25903         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25904                                        Op.getValueType());
25905         break;
25906       }
25907     }
25908     return;
25909   case 'O':
25910     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25911       if (C->getZExtValue() <= 127) {
25912         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25913                                        Op.getValueType());
25914         break;
25915       }
25916     }
25917     return;
25918   case 'e': {
25919     // 32-bit signed value
25920     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25921       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25922                                            C->getSExtValue())) {
25923         // Widen to 64 bits here to get it sign extended.
25924         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25925         break;
25926       }
25927     // FIXME gcc accepts some relocatable values here too, but only in certain
25928     // memory models; it's complicated.
25929     }
25930     return;
25931   }
25932   case 'Z': {
25933     // 32-bit unsigned value
25934     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25935       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25936                                            C->getZExtValue())) {
25937         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25938                                        Op.getValueType());
25939         break;
25940       }
25941     }
25942     // FIXME gcc accepts some relocatable values here too, but only in certain
25943     // memory models; it's complicated.
25944     return;
25945   }
25946   case 'i': {
25947     // Literal immediates are always ok.
25948     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25949       // Widen to 64 bits here to get it sign extended.
25950       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25951       break;
25952     }
25953
25954     // In any sort of PIC mode addresses need to be computed at runtime by
25955     // adding in a register or some sort of table lookup.  These can't
25956     // be used as immediates.
25957     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25958       return;
25959
25960     // If we are in non-pic codegen mode, we allow the address of a global (with
25961     // an optional displacement) to be used with 'i'.
25962     GlobalAddressSDNode *GA = nullptr;
25963     int64_t Offset = 0;
25964
25965     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25966     while (1) {
25967       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25968         Offset += GA->getOffset();
25969         break;
25970       } else if (Op.getOpcode() == ISD::ADD) {
25971         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25972           Offset += C->getZExtValue();
25973           Op = Op.getOperand(0);
25974           continue;
25975         }
25976       } else if (Op.getOpcode() == ISD::SUB) {
25977         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25978           Offset += -C->getZExtValue();
25979           Op = Op.getOperand(0);
25980           continue;
25981         }
25982       }
25983
25984       // Otherwise, this isn't something we can handle, reject it.
25985       return;
25986     }
25987
25988     const GlobalValue *GV = GA->getGlobal();
25989     // If we require an extra load to get this address, as in PIC mode, we
25990     // can't accept it.
25991     if (isGlobalStubReference(
25992             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25993       return;
25994
25995     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25996                                         GA->getValueType(0), Offset);
25997     break;
25998   }
25999   }
26000
26001   if (Result.getNode()) {
26002     Ops.push_back(Result);
26003     return;
26004   }
26005   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26006 }
26007
26008 std::pair<unsigned, const TargetRegisterClass *>
26009 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26010                                                 StringRef Constraint,
26011                                                 MVT VT) const {
26012   // First, see if this is a constraint that directly corresponds to an LLVM
26013   // register class.
26014   if (Constraint.size() == 1) {
26015     // GCC Constraint Letters
26016     switch (Constraint[0]) {
26017     default: break;
26018       // TODO: Slight differences here in allocation order and leaving
26019       // RIP in the class. Do they matter any more here than they do
26020       // in the normal allocation?
26021     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26022       if (Subtarget->is64Bit()) {
26023         if (VT == MVT::i32 || VT == MVT::f32)
26024           return std::make_pair(0U, &X86::GR32RegClass);
26025         if (VT == MVT::i16)
26026           return std::make_pair(0U, &X86::GR16RegClass);
26027         if (VT == MVT::i8 || VT == MVT::i1)
26028           return std::make_pair(0U, &X86::GR8RegClass);
26029         if (VT == MVT::i64 || VT == MVT::f64)
26030           return std::make_pair(0U, &X86::GR64RegClass);
26031         break;
26032       }
26033       // 32-bit fallthrough
26034     case 'Q':   // Q_REGS
26035       if (VT == MVT::i32 || VT == MVT::f32)
26036         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26037       if (VT == MVT::i16)
26038         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26039       if (VT == MVT::i8 || VT == MVT::i1)
26040         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26041       if (VT == MVT::i64)
26042         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26043       break;
26044     case 'r':   // GENERAL_REGS
26045     case 'l':   // INDEX_REGS
26046       if (VT == MVT::i8 || VT == MVT::i1)
26047         return std::make_pair(0U, &X86::GR8RegClass);
26048       if (VT == MVT::i16)
26049         return std::make_pair(0U, &X86::GR16RegClass);
26050       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26051         return std::make_pair(0U, &X86::GR32RegClass);
26052       return std::make_pair(0U, &X86::GR64RegClass);
26053     case 'R':   // LEGACY_REGS
26054       if (VT == MVT::i8 || VT == MVT::i1)
26055         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26056       if (VT == MVT::i16)
26057         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26058       if (VT == MVT::i32 || !Subtarget->is64Bit())
26059         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26060       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26061     case 'f':  // FP Stack registers.
26062       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26063       // value to the correct fpstack register class.
26064       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26065         return std::make_pair(0U, &X86::RFP32RegClass);
26066       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26067         return std::make_pair(0U, &X86::RFP64RegClass);
26068       return std::make_pair(0U, &X86::RFP80RegClass);
26069     case 'y':   // MMX_REGS if MMX allowed.
26070       if (!Subtarget->hasMMX()) break;
26071       return std::make_pair(0U, &X86::VR64RegClass);
26072     case 'Y':   // SSE_REGS if SSE2 allowed
26073       if (!Subtarget->hasSSE2()) break;
26074       // FALL THROUGH.
26075     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26076       if (!Subtarget->hasSSE1()) break;
26077
26078       switch (VT.SimpleTy) {
26079       default: break;
26080       // Scalar SSE types.
26081       case MVT::f32:
26082       case MVT::i32:
26083         return std::make_pair(0U, &X86::FR32RegClass);
26084       case MVT::f64:
26085       case MVT::i64:
26086         return std::make_pair(0U, &X86::FR64RegClass);
26087       // Vector types.
26088       case MVT::v16i8:
26089       case MVT::v8i16:
26090       case MVT::v4i32:
26091       case MVT::v2i64:
26092       case MVT::v4f32:
26093       case MVT::v2f64:
26094         return std::make_pair(0U, &X86::VR128RegClass);
26095       // AVX types.
26096       case MVT::v32i8:
26097       case MVT::v16i16:
26098       case MVT::v8i32:
26099       case MVT::v4i64:
26100       case MVT::v8f32:
26101       case MVT::v4f64:
26102         return std::make_pair(0U, &X86::VR256RegClass);
26103       case MVT::v8f64:
26104       case MVT::v16f32:
26105       case MVT::v16i32:
26106       case MVT::v8i64:
26107         return std::make_pair(0U, &X86::VR512RegClass);
26108       }
26109       break;
26110     }
26111   }
26112
26113   // Use the default implementation in TargetLowering to convert the register
26114   // constraint into a member of a register class.
26115   std::pair<unsigned, const TargetRegisterClass*> Res;
26116   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26117
26118   // Not found as a standard register?
26119   if (!Res.second) {
26120     // Map st(0) -> st(7) -> ST0
26121     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26122         tolower(Constraint[1]) == 's' &&
26123         tolower(Constraint[2]) == 't' &&
26124         Constraint[3] == '(' &&
26125         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26126         Constraint[5] == ')' &&
26127         Constraint[6] == '}') {
26128
26129       Res.first = X86::FP0+Constraint[4]-'0';
26130       Res.second = &X86::RFP80RegClass;
26131       return Res;
26132     }
26133
26134     // GCC allows "st(0)" to be called just plain "st".
26135     if (StringRef("{st}").equals_lower(Constraint)) {
26136       Res.first = X86::FP0;
26137       Res.second = &X86::RFP80RegClass;
26138       return Res;
26139     }
26140
26141     // flags -> EFLAGS
26142     if (StringRef("{flags}").equals_lower(Constraint)) {
26143       Res.first = X86::EFLAGS;
26144       Res.second = &X86::CCRRegClass;
26145       return Res;
26146     }
26147
26148     // 'A' means EAX + EDX.
26149     if (Constraint == "A") {
26150       Res.first = X86::EAX;
26151       Res.second = &X86::GR32_ADRegClass;
26152       return Res;
26153     }
26154     return Res;
26155   }
26156
26157   // Otherwise, check to see if this is a register class of the wrong value
26158   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26159   // turn into {ax},{dx}.
26160   // MVT::Other is used to specify clobber names.
26161   if (Res.second->hasType(VT) || VT == MVT::Other)
26162     return Res;   // Correct type already, nothing to do.
26163
26164   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26165   // return "eax". This should even work for things like getting 64bit integer
26166   // registers when given an f64 type.
26167   const TargetRegisterClass *Class = Res.second;
26168   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26169       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26170     unsigned Size = VT.getSizeInBits();
26171     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26172                                   : Size == 16 ? MVT::i16
26173                                   : Size == 32 ? MVT::i32
26174                                   : Size == 64 ? MVT::i64
26175                                   : MVT::Other;
26176     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26177     if (DestReg > 0) {
26178       Res.first = DestReg;
26179       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26180                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26181                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26182                  : &X86::GR64RegClass;
26183       assert(Res.second->contains(Res.first) && "Register in register class");
26184     } else {
26185       // No register found/type mismatch.
26186       Res.first = 0;
26187       Res.second = nullptr;
26188     }
26189   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26190              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26191              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26192              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26193              Class == &X86::VR512RegClass) {
26194     // Handle references to XMM physical registers that got mapped into the
26195     // wrong class.  This can happen with constraints like {xmm0} where the
26196     // target independent register mapper will just pick the first match it can
26197     // find, ignoring the required type.
26198
26199     if (VT == MVT::f32 || VT == MVT::i32)
26200       Res.second = &X86::FR32RegClass;
26201     else if (VT == MVT::f64 || VT == MVT::i64)
26202       Res.second = &X86::FR64RegClass;
26203     else if (X86::VR128RegClass.hasType(VT))
26204       Res.second = &X86::VR128RegClass;
26205     else if (X86::VR256RegClass.hasType(VT))
26206       Res.second = &X86::VR256RegClass;
26207     else if (X86::VR512RegClass.hasType(VT))
26208       Res.second = &X86::VR512RegClass;
26209     else {
26210       // Type mismatch and not a clobber: Return an error;
26211       Res.first = 0;
26212       Res.second = nullptr;
26213     }
26214   }
26215
26216   return Res;
26217 }
26218
26219 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26220                                             const AddrMode &AM, Type *Ty,
26221                                             unsigned AS) const {
26222   // Scaling factors are not free at all.
26223   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26224   // will take 2 allocations in the out of order engine instead of 1
26225   // for plain addressing mode, i.e. inst (reg1).
26226   // E.g.,
26227   // vaddps (%rsi,%drx), %ymm0, %ymm1
26228   // Requires two allocations (one for the load, one for the computation)
26229   // whereas:
26230   // vaddps (%rsi), %ymm0, %ymm1
26231   // Requires just 1 allocation, i.e., freeing allocations for other operations
26232   // and having less micro operations to execute.
26233   //
26234   // For some X86 architectures, this is even worse because for instance for
26235   // stores, the complex addressing mode forces the instruction to use the
26236   // "load" ports instead of the dedicated "store" port.
26237   // E.g., on Haswell:
26238   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26239   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26240   if (isLegalAddressingMode(DL, AM, Ty, AS))
26241     // Scale represents reg2 * scale, thus account for 1
26242     // as soon as we use a second register.
26243     return AM.Scale != 0;
26244   return -1;
26245 }
26246
26247 bool X86TargetLowering::isTargetFTOL() const {
26248   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26249 }